repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/VisualStudio/CSharp/Impl/CodeModel/CSharpCodeModelServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel
{
[ExportLanguageServiceFactory(typeof(ICodeModelService), LanguageNames.CSharp), Shared]
internal partial class CSharpCodeModelServiceFactory : ILanguageServiceFactory
{
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly IThreadingContext _threadingContext;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCodeModelServiceFactory(
IEditorOptionsFactoryService editorOptionsFactoryService,
[ImportMany] IEnumerable<IRefactorNotifyService> refactorNotifyServices,
IThreadingContext threadingContext)
{
_editorOptionsFactoryService = editorOptionsFactoryService;
_refactorNotifyServices = refactorNotifyServices;
_threadingContext = threadingContext;
}
public ILanguageService CreateLanguageService(HostLanguageServices provider)
=> new CSharpCodeModelService(provider, _editorOptionsFactoryService, _refactorNotifyServices, _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.Collections.Generic;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel
{
[ExportLanguageServiceFactory(typeof(ICodeModelService), LanguageNames.CSharp), Shared]
internal partial class CSharpCodeModelServiceFactory : ILanguageServiceFactory
{
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly IThreadingContext _threadingContext;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCodeModelServiceFactory(
IEditorOptionsFactoryService editorOptionsFactoryService,
[ImportMany] IEnumerable<IRefactorNotifyService> refactorNotifyServices,
IThreadingContext threadingContext)
{
_editorOptionsFactoryService = editorOptionsFactoryService;
_refactorNotifyServices = refactorNotifyServices;
_threadingContext = threadingContext;
}
public ILanguageService CreateLanguageService(HostLanguageServices provider)
=> new CSharpCodeModelService(provider, _editorOptionsFactoryService, _refactorNotifyServices, _threadingContext);
}
}
| -1 |
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/EditorFeatures/Core/Implementation/SplitComment/ISplitCommentService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Editor.Implementation.SplitComment
{
internal interface ISplitCommentService : ILanguageService
{
string CommentStart { get; }
bool IsAllowed(SyntaxNode root, SyntaxTrivia trivia);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Editor.Implementation.SplitComment
{
internal interface ISplitCommentService : ILanguageService
{
string CommentStart { get; }
bool IsAllowed(SyntaxNode root, SyntaxTrivia trivia);
}
}
| -1 |
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Helpers/MefHostServicesHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection;
namespace Microsoft.CodeAnalysis.Host.Mef
{
internal static class MefHostServicesHelpers
{
public static ImmutableArray<Assembly> LoadNearbyAssemblies(IEnumerable<string> assemblyNames)
{
var assemblies = new List<Assembly>();
foreach (var assemblyName in assemblyNames)
{
var assembly = TryLoadNearbyAssembly(assemblyName);
if (assembly != null)
{
assemblies.Add(assembly);
}
}
return assemblies.ToImmutableArray();
}
private static Assembly TryLoadNearbyAssembly(string assemblySimpleName)
{
var thisAssemblyName = typeof(MefHostServicesHelpers).GetTypeInfo().Assembly.GetName();
var assemblyShortName = thisAssemblyName.Name;
var assemblyVersion = thisAssemblyName.Version;
var publicKeyToken = thisAssemblyName.GetPublicKeyToken().Aggregate(string.Empty, (s, b) => s + b.ToString("x2"));
if (string.IsNullOrEmpty(publicKeyToken))
{
publicKeyToken = "null";
}
var assemblyName = new AssemblyName(string.Format("{0}, Version={1}, Culture=neutral, PublicKeyToken={2}", assemblySimpleName, assemblyVersion, publicKeyToken));
try
{
return Assembly.Load(assemblyName);
}
catch (Exception)
{
return null;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
namespace Microsoft.CodeAnalysis.Host.Mef
{
internal static class MefHostServicesHelpers
{
public static ImmutableArray<Assembly> LoadNearbyAssemblies(IEnumerable<string> assemblyNames)
{
var assemblies = new List<Assembly>();
foreach (var assemblyName in assemblyNames)
{
var assembly = TryLoadNearbyAssembly(assemblyName);
if (assembly != null)
{
assemblies.Add(assembly);
}
}
return assemblies.ToImmutableArray();
}
private static Assembly TryLoadNearbyAssembly(string assemblySimpleName)
{
var thisAssemblyName = typeof(MefHostServicesHelpers).GetTypeInfo().Assembly.GetName();
var assemblyShortName = thisAssemblyName.Name;
var assemblyVersion = thisAssemblyName.Version;
var publicKeyToken = thisAssemblyName.GetPublicKeyToken().Aggregate(string.Empty, (s, b) => s + b.ToString("x2"));
if (string.IsNullOrEmpty(publicKeyToken))
{
publicKeyToken = "null";
}
var assemblyName = new AssemblyName(string.Format("{0}, Version={1}, Culture=neutral, PublicKeyToken={2}", assemblySimpleName, assemblyVersion, publicKeyToken));
try
{
return Assembly.Load(assemblyName);
}
catch (Exception)
{
return null;
}
}
}
}
| -1 |
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/DocumentExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.SemanticModelReuse;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
#if DEBUG
using System.Collections.Immutable;
using System.Diagnostics;
#endif
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class DocumentExtensions
{
// ⚠ Verify IVTs do not use this method before removing it.
public static TLanguageService? GetLanguageService<TLanguageService>(this Document? document) where TLanguageService : class, ILanguageService
=> document?.Project?.GetLanguageService<TLanguageService>();
public static TLanguageService GetRequiredLanguageService<TLanguageService>(this Document document) where TLanguageService : class, ILanguageService
=> document.Project.GetRequiredLanguageService<TLanguageService>();
public static async ValueTask<SemanticModel> GetRequiredSemanticModelAsync(this Document document, CancellationToken cancellationToken)
{
if (document.TryGetSemanticModel(out var semanticModel))
return semanticModel;
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return semanticModel ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name));
}
public static async ValueTask<SyntaxTree> GetRequiredSyntaxTreeAsync(this Document document, CancellationToken cancellationToken)
{
if (document.TryGetSyntaxTree(out var syntaxTree))
return syntaxTree;
syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return syntaxTree ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name));
}
#if !CODE_STYLE
public static SyntaxTree GetRequiredSyntaxTreeSynchronously(this Document document, CancellationToken cancellationToken)
{
var syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken);
return syntaxTree ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name));
}
#endif
public static async ValueTask<SyntaxNode> GetRequiredSyntaxRootAsync(this Document document, CancellationToken cancellationToken)
{
if (document.TryGetSyntaxRoot(out var root))
return root;
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return root ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name));
}
#if !CODE_STYLE
public static SyntaxNode GetRequiredSyntaxRootSynchronously(this Document document, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
return root ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name));
}
#endif
public static bool IsOpen(this TextDocument document)
{
var workspace = document.Project.Solution.Workspace;
return workspace != null && workspace.IsDocumentOpen(document.Id);
}
/// <summary>
/// Attempts to return an speculative semantic model for <paramref name="document"/> if possible if <paramref
/// name="position"/> is contained within a method body in the tree. Specifically, this will attempt to get an
/// existing cached semantic model for <paramref name="document"/>. If it can find one, and the top-level semantic
/// version for this project matches the cached version, and the position is within a method body, then it will
/// be returned, just with the previous corresponding method body swapped out with the current method body.
/// <para/>
/// If this is not possible, the regular semantic model for <paramref name="document"/> will be returned.
/// <para/>
/// When using this API, semantic model should only be used to ask questions about nodes inside of the member
/// that contains the given <paramref name="position"/>.
/// <para/>
/// As a speculative semantic model may be returned, location based information provided by it may be innacurate.
/// </summary>
public static ValueTask<SemanticModel> ReuseExistingSpeculativeModelAsync(this Document document, int position, CancellationToken cancellationToken)
=> ReuseExistingSpeculativeModelAsync(document, new TextSpan(position, 0), cancellationToken);
/// <summary>
/// Attempts to return an speculative semantic model for <paramref name="document"/> if possible if <paramref
/// name="span"/> is contained within a method body in the tree. Specifically, this will attempt to get an
/// existing cached semantic model <paramref name="document"/>. If it can find one, and the top-level semantic
/// version for this project matches the cached version, and the position is within a method body, then it will
/// be returned, just with the previous corresponding method body swapped out with the current method body.
/// <para/>
/// If this is not possible, the regular semantic model for <paramref name="document"/> will be returned.
/// <para/>
/// When using this API, semantic model should only be used to ask questions about nodes inside of the
/// member that contains the given <paramref name="span"/>.
/// <para/>
/// As a speculative semantic model may be returned, location based information provided by it may be innacurate.
/// </summary>
public static async ValueTask<SemanticModel> ReuseExistingSpeculativeModelAsync(this Document document, TextSpan span, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(document.SupportsSemanticModel);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(span.Start);
var node = token.Parent!.AncestorsAndSelf().First(a => a.FullSpan.Contains(span));
return await ReuseExistingSpeculativeModelAsync(document, node, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Attempts to return an speculative semantic model for <paramref name="document"/> if possible if <paramref
/// name="node"/> is contained within a method body in the tree. Specifically, this will attempt to get an
/// existing cached semantic model <paramref name="document"/>. If it can find one, and the top-level semantic
/// version for this project matches the cached version, and the position is within a method body, then it will
/// be returned, just with the previous corresponding method body swapped out with the current method body.
/// <para/>
/// If this is not possible, the regular semantic model for <paramref name="document"/> will be returned.
/// <para/>
/// When using this API, semantic model should only be used to ask questions about nodes inside of the
/// member that contains the given <paramref name="node"/>.
/// <para/>
/// As a speculative semantic model may be returned, location based information provided by it may be innacurate.
/// </summary>
public static ValueTask<SemanticModel> ReuseExistingSpeculativeModelAsync(this Document document, SyntaxNode? node, CancellationToken cancellationToken)
{
if (node == null)
return document.GetRequiredSemanticModelAsync(cancellationToken);
var workspace = document.Project.Solution.Workspace;
var semanticModelService = workspace.Services.GetRequiredService<ISemanticModelReuseWorkspaceService>();
return semanticModelService.ReuseExistingSpeculativeModelAsync(document, node, cancellationToken);
}
#if DEBUG
public static async Task<bool> HasAnyErrorsAsync(this Document document, CancellationToken cancellationToken, List<string>? ignoreErrorCode = null)
{
var errors = await GetErrorsAsync(document, cancellationToken, ignoreErrorCode).ConfigureAwait(false);
return errors.Length > 0;
}
public static async Task<ImmutableArray<Diagnostic>> GetErrorsAsync(this Document document, CancellationToken cancellationToken, IList<string>? ignoreErrorCode = null)
{
if (!document.SupportsSemanticModel)
{
return ImmutableArray<Diagnostic>.Empty;
}
ignoreErrorCode ??= SpecializedCollections.EmptyList<string>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return semanticModel!.GetDiagnostics(cancellationToken: cancellationToken).WhereAsArray(
diag => diag.Severity == DiagnosticSeverity.Error && !ignoreErrorCode.Contains(diag.Id));
}
/// <summary>
/// Debug only extension method to verify no errors were introduced by formatting, pretty listing and other related document altering service in error-free code.
/// </summary>
public static async Task VerifyNoErrorsAsync(this Document newDocument, string message, CancellationToken cancellationToken, List<string>? ignoreErrorCodes = null)
{
var errors = await newDocument.GetErrorsAsync(cancellationToken, ignoreErrorCodes).ConfigureAwait(false);
if (errors.Length > 0)
{
var diagnostics = string.Join(", ", errors.Select(d => d.ToString()));
Debug.Assert(false, message + ". " + diagnostics);
}
}
#endif
#if !CODE_STYLE
public static bool IsGeneratedCode(this Document document, CancellationToken cancellationToken)
{
var generatedCodeRecognitionService = document.GetLanguageService<IGeneratedCodeRecognitionService>();
return generatedCodeRecognitionService?.IsGeneratedCode(document, cancellationToken) == true;
}
#endif
public static async Task<bool> IsGeneratedCodeAsync(this Document document, CancellationToken cancellationToken)
{
var generatedCodeRecognitionService = document.GetLanguageService<IGeneratedCodeRecognitionService>();
return generatedCodeRecognitionService != null &&
await generatedCodeRecognitionService.IsGeneratedCodeAsync(document, cancellationToken).ConfigureAwait(false);
}
public static IEnumerable<Document> GetLinkedDocuments(this Document document)
{
var solution = document.Project.Solution;
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
yield return solution.GetRequiredDocument(linkedDocumentId);
}
}
public static bool CanAddImportsInHiddenRegions(this Document document)
{
#if !CODE_STYLE
// Normally we don't allow generation into a hidden region in the file. However, if we have a
// modern span mapper at our disposal, we do allow it as that host span mapper can handle mapping
// our edit to their domain appropriate.
var spanMapper = document.Services.GetService<ISpanMappingService>();
return spanMapper != null && spanMapper.SupportsMappingImportDirectives;
#else
return false;
#endif
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.SemanticModelReuse;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
#if DEBUG
using System.Collections.Immutable;
using System.Diagnostics;
#endif
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class DocumentExtensions
{
// ⚠ Verify IVTs do not use this method before removing it.
public static TLanguageService? GetLanguageService<TLanguageService>(this Document? document) where TLanguageService : class, ILanguageService
=> document?.Project?.GetLanguageService<TLanguageService>();
public static TLanguageService GetRequiredLanguageService<TLanguageService>(this Document document) where TLanguageService : class, ILanguageService
=> document.Project.GetRequiredLanguageService<TLanguageService>();
public static async ValueTask<SemanticModel> GetRequiredSemanticModelAsync(this Document document, CancellationToken cancellationToken)
{
if (document.TryGetSemanticModel(out var semanticModel))
return semanticModel;
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return semanticModel ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name));
}
public static async ValueTask<SyntaxTree> GetRequiredSyntaxTreeAsync(this Document document, CancellationToken cancellationToken)
{
if (document.TryGetSyntaxTree(out var syntaxTree))
return syntaxTree;
syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return syntaxTree ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name));
}
#if !CODE_STYLE
public static SyntaxTree GetRequiredSyntaxTreeSynchronously(this Document document, CancellationToken cancellationToken)
{
var syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken);
return syntaxTree ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name));
}
#endif
public static async ValueTask<SyntaxNode> GetRequiredSyntaxRootAsync(this Document document, CancellationToken cancellationToken)
{
if (document.TryGetSyntaxRoot(out var root))
return root;
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return root ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name));
}
#if !CODE_STYLE
public static SyntaxNode GetRequiredSyntaxRootSynchronously(this Document document, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
return root ?? throw new InvalidOperationException(string.Format(WorkspaceExtensionsResources.SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0, document.Name));
}
#endif
public static bool IsOpen(this TextDocument document)
{
var workspace = document.Project.Solution.Workspace;
return workspace != null && workspace.IsDocumentOpen(document.Id);
}
/// <summary>
/// Attempts to return an speculative semantic model for <paramref name="document"/> if possible if <paramref
/// name="position"/> is contained within a method body in the tree. Specifically, this will attempt to get an
/// existing cached semantic model for <paramref name="document"/>. If it can find one, and the top-level semantic
/// version for this project matches the cached version, and the position is within a method body, then it will
/// be returned, just with the previous corresponding method body swapped out with the current method body.
/// <para/>
/// If this is not possible, the regular semantic model for <paramref name="document"/> will be returned.
/// <para/>
/// When using this API, semantic model should only be used to ask questions about nodes inside of the member
/// that contains the given <paramref name="position"/>.
/// <para/>
/// As a speculative semantic model may be returned, location based information provided by it may be innacurate.
/// </summary>
public static ValueTask<SemanticModel> ReuseExistingSpeculativeModelAsync(this Document document, int position, CancellationToken cancellationToken)
=> ReuseExistingSpeculativeModelAsync(document, new TextSpan(position, 0), cancellationToken);
/// <summary>
/// Attempts to return an speculative semantic model for <paramref name="document"/> if possible if <paramref
/// name="span"/> is contained within a method body in the tree. Specifically, this will attempt to get an
/// existing cached semantic model <paramref name="document"/>. If it can find one, and the top-level semantic
/// version for this project matches the cached version, and the position is within a method body, then it will
/// be returned, just with the previous corresponding method body swapped out with the current method body.
/// <para/>
/// If this is not possible, the regular semantic model for <paramref name="document"/> will be returned.
/// <para/>
/// When using this API, semantic model should only be used to ask questions about nodes inside of the
/// member that contains the given <paramref name="span"/>.
/// <para/>
/// As a speculative semantic model may be returned, location based information provided by it may be innacurate.
/// </summary>
public static async ValueTask<SemanticModel> ReuseExistingSpeculativeModelAsync(this Document document, TextSpan span, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(document.SupportsSemanticModel);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(span.Start);
var node = token.Parent!.AncestorsAndSelf().First(a => a.FullSpan.Contains(span));
return await ReuseExistingSpeculativeModelAsync(document, node, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Attempts to return an speculative semantic model for <paramref name="document"/> if possible if <paramref
/// name="node"/> is contained within a method body in the tree. Specifically, this will attempt to get an
/// existing cached semantic model <paramref name="document"/>. If it can find one, and the top-level semantic
/// version for this project matches the cached version, and the position is within a method body, then it will
/// be returned, just with the previous corresponding method body swapped out with the current method body.
/// <para/>
/// If this is not possible, the regular semantic model for <paramref name="document"/> will be returned.
/// <para/>
/// When using this API, semantic model should only be used to ask questions about nodes inside of the
/// member that contains the given <paramref name="node"/>.
/// <para/>
/// As a speculative semantic model may be returned, location based information provided by it may be innacurate.
/// </summary>
public static ValueTask<SemanticModel> ReuseExistingSpeculativeModelAsync(this Document document, SyntaxNode? node, CancellationToken cancellationToken)
{
if (node == null)
return document.GetRequiredSemanticModelAsync(cancellationToken);
var workspace = document.Project.Solution.Workspace;
var semanticModelService = workspace.Services.GetRequiredService<ISemanticModelReuseWorkspaceService>();
return semanticModelService.ReuseExistingSpeculativeModelAsync(document, node, cancellationToken);
}
#if DEBUG
public static async Task<bool> HasAnyErrorsAsync(this Document document, CancellationToken cancellationToken, List<string>? ignoreErrorCode = null)
{
var errors = await GetErrorsAsync(document, cancellationToken, ignoreErrorCode).ConfigureAwait(false);
return errors.Length > 0;
}
public static async Task<ImmutableArray<Diagnostic>> GetErrorsAsync(this Document document, CancellationToken cancellationToken, IList<string>? ignoreErrorCode = null)
{
if (!document.SupportsSemanticModel)
{
return ImmutableArray<Diagnostic>.Empty;
}
ignoreErrorCode ??= SpecializedCollections.EmptyList<string>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return semanticModel!.GetDiagnostics(cancellationToken: cancellationToken).WhereAsArray(
diag => diag.Severity == DiagnosticSeverity.Error && !ignoreErrorCode.Contains(diag.Id));
}
/// <summary>
/// Debug only extension method to verify no errors were introduced by formatting, pretty listing and other related document altering service in error-free code.
/// </summary>
public static async Task VerifyNoErrorsAsync(this Document newDocument, string message, CancellationToken cancellationToken, List<string>? ignoreErrorCodes = null)
{
var errors = await newDocument.GetErrorsAsync(cancellationToken, ignoreErrorCodes).ConfigureAwait(false);
if (errors.Length > 0)
{
var diagnostics = string.Join(", ", errors.Select(d => d.ToString()));
Debug.Assert(false, message + ". " + diagnostics);
}
}
#endif
#if !CODE_STYLE
public static bool IsGeneratedCode(this Document document, CancellationToken cancellationToken)
{
var generatedCodeRecognitionService = document.GetLanguageService<IGeneratedCodeRecognitionService>();
return generatedCodeRecognitionService?.IsGeneratedCode(document, cancellationToken) == true;
}
#endif
public static async Task<bool> IsGeneratedCodeAsync(this Document document, CancellationToken cancellationToken)
{
var generatedCodeRecognitionService = document.GetLanguageService<IGeneratedCodeRecognitionService>();
return generatedCodeRecognitionService != null &&
await generatedCodeRecognitionService.IsGeneratedCodeAsync(document, cancellationToken).ConfigureAwait(false);
}
public static IEnumerable<Document> GetLinkedDocuments(this Document document)
{
var solution = document.Project.Solution;
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
yield return solution.GetRequiredDocument(linkedDocumentId);
}
}
public static bool CanAddImportsInHiddenRegions(this Document document)
{
#if !CODE_STYLE
// Normally we don't allow generation into a hidden region in the file. However, if we have a
// modern span mapper at our disposal, we do allow it as that host span mapper can handle mapping
// our edit to their domain appropriate.
var spanMapper = document.Services.GetService<ISpanMappingService>();
return spanMapper != null && spanMapper.SupportsMappingImportDirectives;
#else
return false;
#endif
}
}
}
| -1 |
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/EditorFeatures/Core.Cocoa/Preview/PreviewPaneService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Globalization;
using AppKit;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
[ExportWorkspaceServiceFactory(typeof(IPreviewPaneService), ServiceLayer.Host), Shared]
internal class PreviewPaneService : ForegroundThreadAffinitizedObject, IPreviewPaneService, IWorkspaceServiceFactory
{
private readonly IImageService imageService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewPaneService(IThreadingContext threadingContext, IImageService imageService)
: base(threadingContext)
{
this.imageService = imageService;
}
IWorkspaceService IWorkspaceServiceFactory.CreateService(HostWorkspaceServices workspaceServices)
{
return this;
}
#pragma warning disable IDE0051 // Remove unused private members
private NSImage GetSeverityIconForDiagnostic(DiagnosticData diagnostic)
#pragma warning restore IDE0051 // Remove unused private members
{
int? moniker = null;
switch (diagnostic.Severity)
{
case DiagnosticSeverity.Error:
moniker = KnownImageIds.StatusError;
break;
case DiagnosticSeverity.Warning:
moniker = KnownImageIds.StatusWarning;
break;
case DiagnosticSeverity.Info:
moniker = KnownImageIds.StatusInformation;
break;
case DiagnosticSeverity.Hidden:
moniker = KnownImageIds.StatusHidden;
break;
}
if (moniker.HasValue)
{
return (NSImage)imageService.GetImage(new ImageId(KnownImageIds.ImageCatalogGuid, moniker.Value));
}
return null;
}
object IPreviewPaneService.GetPreviewPane(
DiagnosticData data, IReadOnlyList<object> previewContent)
{
var title = data?.Message;
if (string.IsNullOrWhiteSpace(title))
{
if (previewContent == null)
{
// Bail out in cases where there is nothing to put in the header section
// of the preview pane and no preview content (i.e. no diff view) either.
return null;
}
return new PreviewPane(
severityIcon: null, id: null, title: null, description: null, helpLink: null, helpLinkToolTipText: null,
previewContent: previewContent, logIdVerbatimInTelemetry: false);
}
else
{
if (previewContent == null)
{
// TODO: Mac, if we have title but no content, we should still display title/help link...
return null;
}
}
var helpLinkUri = BrowserHelper.GetHelpLink(data);
var helpLinkToolTip = BrowserHelper.GetHelpLinkToolTip(data.Id, helpLinkUri);
return new PreviewPane(
severityIcon: null,//TODO: Mac GetSeverityIconForDiagnostic(diagnostic),
id: data.Id, title: title,
description: data.Description.ToString(CultureInfo.CurrentUICulture),
helpLink: helpLinkUri,
helpLinkToolTipText: helpLinkToolTip,
previewContent: previewContent,
logIdVerbatimInTelemetry: data.CustomTags.Contains(WellKnownDiagnosticTags.Telemetry));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Globalization;
using AppKit;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
[ExportWorkspaceServiceFactory(typeof(IPreviewPaneService), ServiceLayer.Host), Shared]
internal class PreviewPaneService : ForegroundThreadAffinitizedObject, IPreviewPaneService, IWorkspaceServiceFactory
{
private readonly IImageService imageService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public PreviewPaneService(IThreadingContext threadingContext, IImageService imageService)
: base(threadingContext)
{
this.imageService = imageService;
}
IWorkspaceService IWorkspaceServiceFactory.CreateService(HostWorkspaceServices workspaceServices)
{
return this;
}
#pragma warning disable IDE0051 // Remove unused private members
private NSImage GetSeverityIconForDiagnostic(DiagnosticData diagnostic)
#pragma warning restore IDE0051 // Remove unused private members
{
int? moniker = null;
switch (diagnostic.Severity)
{
case DiagnosticSeverity.Error:
moniker = KnownImageIds.StatusError;
break;
case DiagnosticSeverity.Warning:
moniker = KnownImageIds.StatusWarning;
break;
case DiagnosticSeverity.Info:
moniker = KnownImageIds.StatusInformation;
break;
case DiagnosticSeverity.Hidden:
moniker = KnownImageIds.StatusHidden;
break;
}
if (moniker.HasValue)
{
return (NSImage)imageService.GetImage(new ImageId(KnownImageIds.ImageCatalogGuid, moniker.Value));
}
return null;
}
object IPreviewPaneService.GetPreviewPane(
DiagnosticData data, IReadOnlyList<object> previewContent)
{
var title = data?.Message;
if (string.IsNullOrWhiteSpace(title))
{
if (previewContent == null)
{
// Bail out in cases where there is nothing to put in the header section
// of the preview pane and no preview content (i.e. no diff view) either.
return null;
}
return new PreviewPane(
severityIcon: null, id: null, title: null, description: null, helpLink: null, helpLinkToolTipText: null,
previewContent: previewContent, logIdVerbatimInTelemetry: false);
}
else
{
if (previewContent == null)
{
// TODO: Mac, if we have title but no content, we should still display title/help link...
return null;
}
}
var helpLinkUri = BrowserHelper.GetHelpLink(data);
var helpLinkToolTip = BrowserHelper.GetHelpLinkToolTip(data.Id, helpLinkUri);
return new PreviewPane(
severityIcon: null,//TODO: Mac GetSeverityIconForDiagnostic(diagnostic),
id: data.Id, title: title,
description: data.Description.ToString(CultureInfo.CurrentUICulture),
helpLink: helpLinkUri,
helpLinkToolTipText: helpLinkToolTip,
previewContent: previewContent,
logIdVerbatimInTelemetry: data.CustomTags.Contains(WellKnownDiagnosticTags.Telemetry));
}
}
}
| -1 |
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundLocalDeclaration.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundLocalDeclaration
Implements IBoundLocalDeclarations
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, initializerOpt As BoundExpression)
MyClass.New(syntax, localSymbol, initializerOpt, Nothing, False, False)
End Sub
Public ReadOnly Property InitializerOpt As BoundExpression
Get
Return If(DeclarationInitializerOpt, IdentifierInitializerOpt)
End Get
End Property
Private ReadOnly Property IBoundLocalDeclarations_Declarations As ImmutableArray(Of BoundLocalDeclarationBase) Implements IBoundLocalDeclarations.Declarations
Get
Return ImmutableArray.Create(Of BoundLocalDeclarationBase)(Me)
End Get
End Property
#If DEBUG Then
Private Sub Validate()
If InitializerOpt IsNot Nothing Then
InitializerOpt.AssertRValue()
Debug.Assert(DeclarationInitializerOpt IsNot IdentifierInitializerOpt)
If Not HasErrors Then
If InitializerOpt.Type Is Nothing Then
Debug.Assert(LocalSymbol.IsConst AndAlso InitializerOpt.IsStrictNothingLiteral())
Else
Debug.Assert(LocalSymbol.Type.IsSameTypeIgnoringAll(InitializerOpt.Type) OrElse InitializerOpt.Type.IsErrorType() OrElse
(LocalSymbol.IsConst AndAlso LocalSymbol.Type.SpecialType = SpecialType.System_Object AndAlso
InitializerOpt.IsConstant AndAlso InitializerOpt.ConstantValueOpt.IsNothing))
End If
End If
End If
End Sub
#End If
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundLocalDeclaration
Implements IBoundLocalDeclarations
Public Sub New(syntax As SyntaxNode, localSymbol As LocalSymbol, initializerOpt As BoundExpression)
MyClass.New(syntax, localSymbol, initializerOpt, Nothing, False, False)
End Sub
Public ReadOnly Property InitializerOpt As BoundExpression
Get
Return If(DeclarationInitializerOpt, IdentifierInitializerOpt)
End Get
End Property
Private ReadOnly Property IBoundLocalDeclarations_Declarations As ImmutableArray(Of BoundLocalDeclarationBase) Implements IBoundLocalDeclarations.Declarations
Get
Return ImmutableArray.Create(Of BoundLocalDeclarationBase)(Me)
End Get
End Property
#If DEBUG Then
Private Sub Validate()
If InitializerOpt IsNot Nothing Then
InitializerOpt.AssertRValue()
Debug.Assert(DeclarationInitializerOpt IsNot IdentifierInitializerOpt)
If Not HasErrors Then
If InitializerOpt.Type Is Nothing Then
Debug.Assert(LocalSymbol.IsConst AndAlso InitializerOpt.IsStrictNothingLiteral())
Else
Debug.Assert(LocalSymbol.Type.IsSameTypeIgnoringAll(InitializerOpt.Type) OrElse InitializerOpt.Type.IsErrorType() OrElse
(LocalSymbol.IsConst AndAlso LocalSymbol.Type.SpecialType = SpecialType.System_Object AndAlso
InitializerOpt.IsConstant AndAlso InitializerOpt.ConstantValueOpt.IsNothing))
End If
End If
End If
End Sub
#End If
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/EditorFeatures/Core/Implementation/TextDiffing/EditorTextDifferencingService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TextDiffing
{
[ExportWorkspaceService(typeof(IDocumentTextDifferencingService), ServiceLayer.Host), Shared]
internal class EditorTextDifferencingService : IDocumentTextDifferencingService
{
private readonly ITextDifferencingSelectorService _differenceSelectorService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EditorTextDifferencingService(ITextDifferencingSelectorService differenceSelectorService)
=> _differenceSelectorService = differenceSelectorService;
public Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken)
=> GetTextChangesAsync(oldDocument, newDocument, TextDifferenceTypes.Word, cancellationToken);
public async Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, TextDifferenceTypes preferredDifferenceType, CancellationToken cancellationToken)
{
var oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
var diffService = _differenceSelectorService.GetTextDifferencingService(oldDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType())
?? _differenceSelectorService.DefaultTextDifferencingService;
var differenceOptions = GetDifferenceOptions(preferredDifferenceType);
var oldTextSnapshot = oldText.FindCorrespondingEditorTextSnapshot();
var newTextSnapshot = newText.FindCorrespondingEditorTextSnapshot();
var useSnapshots = oldTextSnapshot != null && newTextSnapshot != null;
var diffResult = useSnapshots
? diffService.DiffSnapshotSpans(oldTextSnapshot.GetFullSpan(), newTextSnapshot.GetFullSpan(), differenceOptions)
: diffService.DiffStrings(oldText.ToString(), newText.ToString(), differenceOptions);
return diffResult.Differences.Select(d =>
new TextChange(
diffResult.LeftDecomposition.GetSpanInOriginal(d.Left).ToTextSpan(),
newText.GetSubText(diffResult.RightDecomposition.GetSpanInOriginal(d.Right).ToTextSpan()).ToString())).ToImmutableArray();
}
private static StringDifferenceOptions GetDifferenceOptions(TextDifferenceTypes differenceTypes)
{
StringDifferenceTypes stringDifferenceTypes = default;
if (differenceTypes.HasFlag(TextDifferenceTypes.Line))
{
stringDifferenceTypes |= StringDifferenceTypes.Line;
}
if (differenceTypes.HasFlag(TextDifferenceTypes.Word))
{
stringDifferenceTypes |= StringDifferenceTypes.Word;
}
if (differenceTypes.HasFlag(TextDifferenceTypes.Character))
{
stringDifferenceTypes |= StringDifferenceTypes.Character;
}
return new StringDifferenceOptions()
{
DifferenceType = stringDifferenceTypes
};
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TextDiffing
{
[ExportWorkspaceService(typeof(IDocumentTextDifferencingService), ServiceLayer.Host), Shared]
internal class EditorTextDifferencingService : IDocumentTextDifferencingService
{
private readonly ITextDifferencingSelectorService _differenceSelectorService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EditorTextDifferencingService(ITextDifferencingSelectorService differenceSelectorService)
=> _differenceSelectorService = differenceSelectorService;
public Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken)
=> GetTextChangesAsync(oldDocument, newDocument, TextDifferenceTypes.Word, cancellationToken);
public async Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, TextDifferenceTypes preferredDifferenceType, CancellationToken cancellationToken)
{
var oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
var diffService = _differenceSelectorService.GetTextDifferencingService(oldDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType())
?? _differenceSelectorService.DefaultTextDifferencingService;
var differenceOptions = GetDifferenceOptions(preferredDifferenceType);
var oldTextSnapshot = oldText.FindCorrespondingEditorTextSnapshot();
var newTextSnapshot = newText.FindCorrespondingEditorTextSnapshot();
var useSnapshots = oldTextSnapshot != null && newTextSnapshot != null;
var diffResult = useSnapshots
? diffService.DiffSnapshotSpans(oldTextSnapshot.GetFullSpan(), newTextSnapshot.GetFullSpan(), differenceOptions)
: diffService.DiffStrings(oldText.ToString(), newText.ToString(), differenceOptions);
return diffResult.Differences.Select(d =>
new TextChange(
diffResult.LeftDecomposition.GetSpanInOriginal(d.Left).ToTextSpan(),
newText.GetSubText(diffResult.RightDecomposition.GetSpanInOriginal(d.Right).ToTextSpan()).ToString())).ToImmutableArray();
}
private static StringDifferenceOptions GetDifferenceOptions(TextDifferenceTypes differenceTypes)
{
StringDifferenceTypes stringDifferenceTypes = default;
if (differenceTypes.HasFlag(TextDifferenceTypes.Line))
{
stringDifferenceTypes |= StringDifferenceTypes.Line;
}
if (differenceTypes.HasFlag(TextDifferenceTypes.Word))
{
stringDifferenceTypes |= StringDifferenceTypes.Word;
}
if (differenceTypes.HasFlag(TextDifferenceTypes.Character))
{
stringDifferenceTypes |= StringDifferenceTypes.Character;
}
return new StringDifferenceOptions()
{
DifferenceType = stringDifferenceTypes
};
}
}
}
| -1 |
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/Compilers/CSharp/Portable/Compiler/SynthesizedMetadataCompiler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
#if DEBUG
using Roslyn.Utilities;
#endif
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// When compiling in metadata-only mode, <see cref="MethodCompiler"/> is not run. This is problematic because
/// <see cref="MethodCompiler"/> adds synthesized explicit implementations to the list of synthesized definitions.
/// In lieu of running <see cref="MethodCompiler"/>, this class performs a quick
/// traversal of the symbol table and performs processing of synthesized symbols if necessary
/// </summary>
internal sealed class SynthesizedMetadataCompiler : CSharpSymbolVisitor
{
private readonly PEModuleBuilder _moduleBeingBuilt;
private readonly CancellationToken _cancellationToken;
private SynthesizedMetadataCompiler(PEModuleBuilder moduleBeingBuilt, CancellationToken cancellationToken)
{
Debug.Assert(moduleBeingBuilt != null);
_moduleBeingBuilt = moduleBeingBuilt;
_cancellationToken = cancellationToken;
}
/// <summary>
/// Traverse the symbol table and call Module.AddSynthesizedDefinition for each
/// synthesized explicit implementation stub that has been generated (e.g. when the real
/// implementation doesn't have the appropriate custom modifiers).
/// </summary>
public static void ProcessSynthesizedMembers(
CSharpCompilation compilation,
PEModuleBuilder moduleBeingBuilt,
CancellationToken cancellationToken)
{
Debug.Assert(moduleBeingBuilt != null);
var compiler = new SynthesizedMetadataCompiler(moduleBeingBuilt, cancellationToken);
compiler.Visit(compilation.SourceModule.GlobalNamespace);
}
public override void VisitNamespace(NamespaceSymbol symbol)
{
_cancellationToken.ThrowIfCancellationRequested();
foreach (var s in symbol.GetMembers())
{
s.Accept(this);
}
}
public override void VisitNamedType(NamedTypeSymbol symbol)
{
_cancellationToken.ThrowIfCancellationRequested();
var sourceTypeSymbol = symbol as SourceMemberContainerTypeSymbol;
if ((object)sourceTypeSymbol != null)
{
if (_moduleBeingBuilt != null)
{
// In some circumstances (e.g. implicit implementation of an interface method by a non-virtual method in a
// base type from another assembly) it is necessary for the compiler to generate explicit implementations for
// some interface methods. They don't go in the symbol table, but if we are emitting metadata, then we should
// generate MethodDef entries for them.
foreach (var synthesizedExplicitImpl in sourceTypeSymbol.GetSynthesizedExplicitImplementations(_cancellationToken).ForwardingMethods)
{
_moduleBeingBuilt.AddSynthesizedDefinition(symbol, synthesizedExplicitImpl.GetCciAdapter());
}
}
}
foreach (Symbol member in symbol.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.Property:
case SymbolKind.NamedType:
member.Accept(this);
break;
}
}
}
public override void VisitProperty(PropertySymbol symbol)
{
var sourceProperty = symbol as SourcePropertySymbolBase;
if ((object)sourceProperty != null && sourceProperty.IsSealed)
{
var synthesizedAccessor = sourceProperty.SynthesizedSealedAccessorOpt;
if ((object)synthesizedAccessor != null)
{
_moduleBeingBuilt.AddSynthesizedDefinition(sourceProperty.ContainingType, synthesizedAccessor.GetCciAdapter());
}
}
}
#if DEBUG
public override void VisitMethod(MethodSymbol symbol)
{
throw ExceptionUtilities.Unreachable;
}
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
#if DEBUG
using Roslyn.Utilities;
#endif
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// When compiling in metadata-only mode, <see cref="MethodCompiler"/> is not run. This is problematic because
/// <see cref="MethodCompiler"/> adds synthesized explicit implementations to the list of synthesized definitions.
/// In lieu of running <see cref="MethodCompiler"/>, this class performs a quick
/// traversal of the symbol table and performs processing of synthesized symbols if necessary
/// </summary>
internal sealed class SynthesizedMetadataCompiler : CSharpSymbolVisitor
{
private readonly PEModuleBuilder _moduleBeingBuilt;
private readonly CancellationToken _cancellationToken;
private SynthesizedMetadataCompiler(PEModuleBuilder moduleBeingBuilt, CancellationToken cancellationToken)
{
Debug.Assert(moduleBeingBuilt != null);
_moduleBeingBuilt = moduleBeingBuilt;
_cancellationToken = cancellationToken;
}
/// <summary>
/// Traverse the symbol table and call Module.AddSynthesizedDefinition for each
/// synthesized explicit implementation stub that has been generated (e.g. when the real
/// implementation doesn't have the appropriate custom modifiers).
/// </summary>
public static void ProcessSynthesizedMembers(
CSharpCompilation compilation,
PEModuleBuilder moduleBeingBuilt,
CancellationToken cancellationToken)
{
Debug.Assert(moduleBeingBuilt != null);
var compiler = new SynthesizedMetadataCompiler(moduleBeingBuilt, cancellationToken);
compiler.Visit(compilation.SourceModule.GlobalNamespace);
}
public override void VisitNamespace(NamespaceSymbol symbol)
{
_cancellationToken.ThrowIfCancellationRequested();
foreach (var s in symbol.GetMembers())
{
s.Accept(this);
}
}
public override void VisitNamedType(NamedTypeSymbol symbol)
{
_cancellationToken.ThrowIfCancellationRequested();
var sourceTypeSymbol = symbol as SourceMemberContainerTypeSymbol;
if ((object)sourceTypeSymbol != null)
{
if (_moduleBeingBuilt != null)
{
// In some circumstances (e.g. implicit implementation of an interface method by a non-virtual method in a
// base type from another assembly) it is necessary for the compiler to generate explicit implementations for
// some interface methods. They don't go in the symbol table, but if we are emitting metadata, then we should
// generate MethodDef entries for them.
foreach (var synthesizedExplicitImpl in sourceTypeSymbol.GetSynthesizedExplicitImplementations(_cancellationToken).ForwardingMethods)
{
_moduleBeingBuilt.AddSynthesizedDefinition(symbol, synthesizedExplicitImpl.GetCciAdapter());
}
}
}
foreach (Symbol member in symbol.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.Property:
case SymbolKind.NamedType:
member.Accept(this);
break;
}
}
}
public override void VisitProperty(PropertySymbol symbol)
{
var sourceProperty = symbol as SourcePropertySymbolBase;
if ((object)sourceProperty != null && sourceProperty.IsSealed)
{
var synthesizedAccessor = sourceProperty.SynthesizedSealedAccessorOpt;
if ((object)synthesizedAccessor != null)
{
_moduleBeingBuilt.AddSynthesizedDefinition(sourceProperty.ContainingType, synthesizedAccessor.GetCciAdapter());
}
}
}
#if DEBUG
public override void VisitMethod(MethodSymbol symbol)
{
throw ExceptionUtilities.Unreachable;
}
#endif
}
}
| -1 |
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.it.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="it" original="../CSharpCompilerExtensionsResources.resx">
<body>
<trans-unit id="Code_block_preferences">
<source>Code-block preferences</source>
<target state="translated">Preferenze per blocchi di codice</target>
<note />
</trans-unit>
<trans-unit id="Expected_string_or_char_literal">
<source>Expected string or char literal</source>
<target state="translated">È previsto un valore letterale di tipo stringa o char</target>
<note />
</trans-unit>
<trans-unit id="Expression_bodied_members">
<source>Expression-bodied members</source>
<target state="translated">Membri con corpo di espressione</target>
<note />
</trans-unit>
<trans-unit id="Null_checking_preferences">
<source>Null-checking preferences</source>
<target state="translated">Preference per controllo valori Null</target>
<note />
</trans-unit>
<trans-unit id="Pattern_matching_preferences">
<source>Pattern matching preferences</source>
<target state="translated">Preferenze per criteri di ricerca</target>
<note />
</trans-unit>
<trans-unit id="_0_1_is_not_supported_in_this_version">
<source>'{0}.{1}' is not supported in this version</source>
<target state="translated">'{0}.{1}' non è supportato in questa versione</target>
<note>{0}: A type name
{1}: A member name</note>
</trans-unit>
<trans-unit id="using_directive_preferences">
<source>'using' directive preferences</source>
<target state="translated">Preferenze per direttive 'using'</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="var_preferences">
<source>var preferences</source>
<target state="translated">Preferenze per var</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="it" original="../CSharpCompilerExtensionsResources.resx">
<body>
<trans-unit id="Code_block_preferences">
<source>Code-block preferences</source>
<target state="translated">Preferenze per blocchi di codice</target>
<note />
</trans-unit>
<trans-unit id="Expected_string_or_char_literal">
<source>Expected string or char literal</source>
<target state="translated">È previsto un valore letterale di tipo stringa o char</target>
<note />
</trans-unit>
<trans-unit id="Expression_bodied_members">
<source>Expression-bodied members</source>
<target state="translated">Membri con corpo di espressione</target>
<note />
</trans-unit>
<trans-unit id="Null_checking_preferences">
<source>Null-checking preferences</source>
<target state="translated">Preference per controllo valori Null</target>
<note />
</trans-unit>
<trans-unit id="Pattern_matching_preferences">
<source>Pattern matching preferences</source>
<target state="translated">Preferenze per criteri di ricerca</target>
<note />
</trans-unit>
<trans-unit id="_0_1_is_not_supported_in_this_version">
<source>'{0}.{1}' is not supported in this version</source>
<target state="translated">'{0}.{1}' non è supportato in questa versione</target>
<note>{0}: A type name
{1}: A member name</note>
</trans-unit>
<trans-unit id="using_directive_preferences">
<source>'using' directive preferences</source>
<target state="translated">Preferenze per direttive 'using'</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="var_preferences">
<source>var preferences</source>
<target state="translated">Preferenze per var</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/Features/Core/Portable/TodoComments/AbstractTodoCommentService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.TodoComments
{
internal abstract class AbstractTodoCommentService : ITodoCommentService
{
protected abstract bool PreprocessorHasComment(SyntaxTrivia trivia);
protected abstract bool IsSingleLineComment(SyntaxTrivia trivia);
protected abstract bool IsMultilineComment(SyntaxTrivia trivia);
protected abstract bool IsIdentifierCharacter(char ch);
protected abstract string GetNormalizedText(string message);
protected abstract int GetCommentStartingIndex(string message);
protected abstract void AppendTodoComments(ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, ArrayBuilder<TodoComment> todoList);
public async Task<ImmutableArray<TodoComment>> GetTodoCommentsAsync(
Document document,
ImmutableArray<TodoCommentDescriptor> commentDescriptors,
CancellationToken cancellationToken)
{
if (commentDescriptors.IsEmpty)
return ImmutableArray<TodoComment>.Empty;
cancellationToken.ThrowIfCancellationRequested();
// strongly hold onto text and tree
var syntaxDoc = await SyntacticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
// reuse list
using var _ = ArrayBuilder<TodoComment>.GetInstance(out var todoList);
foreach (var trivia in syntaxDoc.Root.DescendantTrivia())
{
cancellationToken.ThrowIfCancellationRequested();
if (!ContainsComments(trivia))
continue;
AppendTodoComments(commentDescriptors, syntaxDoc, trivia, todoList);
}
return todoList.ToImmutable();
}
private bool ContainsComments(SyntaxTrivia trivia)
=> PreprocessorHasComment(trivia) || IsSingleLineComment(trivia) || IsMultilineComment(trivia);
protected void AppendTodoCommentInfoFromSingleLine(
ImmutableArray<TodoCommentDescriptor> commentDescriptors,
string message, int start,
ArrayBuilder<TodoComment> todoList)
{
var index = GetCommentStartingIndex(message);
if (index >= message.Length)
{
return;
}
var normalized = GetNormalizedText(message);
foreach (var commentDescriptor in commentDescriptors)
{
var token = commentDescriptor.Text;
if (string.Compare(
normalized, index, token, indexB: 0,
length: token.Length, comparisonType: StringComparison.OrdinalIgnoreCase) != 0)
{
continue;
}
if ((message.Length > index + token.Length) && IsIdentifierCharacter(message[index + token.Length]))
{
// they wrote something like:
// todoboo
// instead of
// todo
continue;
}
todoList.Add(new TodoComment(commentDescriptor, message[index..], start + index));
}
}
protected void ProcessMultilineComment(
ImmutableArray<TodoCommentDescriptor> commentDescriptors,
SyntacticDocument document,
SyntaxTrivia trivia, int postfixLength,
ArrayBuilder<TodoComment> todoList)
{
// this is okay since we know it is already alive
var text = document.Text;
var fullSpan = trivia.FullSpan;
var fullString = trivia.ToFullString();
var startLine = text.Lines.GetLineFromPosition(fullSpan.Start);
var endLine = text.Lines.GetLineFromPosition(fullSpan.End);
// single line multiline comments
if (startLine.LineNumber == endLine.LineNumber)
{
var message = postfixLength == 0 ? fullString : fullString.Substring(0, fullSpan.Length - postfixLength);
AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, fullSpan.Start, todoList);
return;
}
// multiline
var startMessage = text.ToString(TextSpan.FromBounds(fullSpan.Start, startLine.End));
AppendTodoCommentInfoFromSingleLine(commentDescriptors, startMessage, fullSpan.Start, todoList);
for (var lineNumber = startLine.LineNumber + 1; lineNumber < endLine.LineNumber; lineNumber++)
{
var line = text.Lines[lineNumber];
var message = line.ToString();
AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, line.Start, todoList);
}
var length = fullSpan.End - endLine.Start;
if (length >= postfixLength)
{
length -= postfixLength;
}
var endMessage = text.ToString(new TextSpan(endLine.Start, length));
AppendTodoCommentInfoFromSingleLine(commentDescriptors, endMessage, endLine.Start, todoList);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.TodoComments
{
internal abstract class AbstractTodoCommentService : ITodoCommentService
{
protected abstract bool PreprocessorHasComment(SyntaxTrivia trivia);
protected abstract bool IsSingleLineComment(SyntaxTrivia trivia);
protected abstract bool IsMultilineComment(SyntaxTrivia trivia);
protected abstract bool IsIdentifierCharacter(char ch);
protected abstract string GetNormalizedText(string message);
protected abstract int GetCommentStartingIndex(string message);
protected abstract void AppendTodoComments(ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, ArrayBuilder<TodoComment> todoList);
public async Task<ImmutableArray<TodoComment>> GetTodoCommentsAsync(
Document document,
ImmutableArray<TodoCommentDescriptor> commentDescriptors,
CancellationToken cancellationToken)
{
if (commentDescriptors.IsEmpty)
return ImmutableArray<TodoComment>.Empty;
cancellationToken.ThrowIfCancellationRequested();
// strongly hold onto text and tree
var syntaxDoc = await SyntacticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
// reuse list
using var _ = ArrayBuilder<TodoComment>.GetInstance(out var todoList);
foreach (var trivia in syntaxDoc.Root.DescendantTrivia())
{
cancellationToken.ThrowIfCancellationRequested();
if (!ContainsComments(trivia))
continue;
AppendTodoComments(commentDescriptors, syntaxDoc, trivia, todoList);
}
return todoList.ToImmutable();
}
private bool ContainsComments(SyntaxTrivia trivia)
=> PreprocessorHasComment(trivia) || IsSingleLineComment(trivia) || IsMultilineComment(trivia);
protected void AppendTodoCommentInfoFromSingleLine(
ImmutableArray<TodoCommentDescriptor> commentDescriptors,
string message, int start,
ArrayBuilder<TodoComment> todoList)
{
var index = GetCommentStartingIndex(message);
if (index >= message.Length)
{
return;
}
var normalized = GetNormalizedText(message);
foreach (var commentDescriptor in commentDescriptors)
{
var token = commentDescriptor.Text;
if (string.Compare(
normalized, index, token, indexB: 0,
length: token.Length, comparisonType: StringComparison.OrdinalIgnoreCase) != 0)
{
continue;
}
if ((message.Length > index + token.Length) && IsIdentifierCharacter(message[index + token.Length]))
{
// they wrote something like:
// todoboo
// instead of
// todo
continue;
}
todoList.Add(new TodoComment(commentDescriptor, message[index..], start + index));
}
}
protected void ProcessMultilineComment(
ImmutableArray<TodoCommentDescriptor> commentDescriptors,
SyntacticDocument document,
SyntaxTrivia trivia, int postfixLength,
ArrayBuilder<TodoComment> todoList)
{
// this is okay since we know it is already alive
var text = document.Text;
var fullSpan = trivia.FullSpan;
var fullString = trivia.ToFullString();
var startLine = text.Lines.GetLineFromPosition(fullSpan.Start);
var endLine = text.Lines.GetLineFromPosition(fullSpan.End);
// single line multiline comments
if (startLine.LineNumber == endLine.LineNumber)
{
var message = postfixLength == 0 ? fullString : fullString.Substring(0, fullSpan.Length - postfixLength);
AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, fullSpan.Start, todoList);
return;
}
// multiline
var startMessage = text.ToString(TextSpan.FromBounds(fullSpan.Start, startLine.End));
AppendTodoCommentInfoFromSingleLine(commentDescriptors, startMessage, fullSpan.Start, todoList);
for (var lineNumber = startLine.LineNumber + 1; lineNumber < endLine.LineNumber; lineNumber++)
{
var line = text.Lines[lineNumber];
var message = line.ToString();
AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, line.Start, todoList);
}
var length = fullSpan.End - endLine.Start;
if (length >= postfixLength)
{
length -= postfixLength;
}
var endMessage = text.ToString(new TextSpan(endLine.Start, length));
AppendTodoCommentInfoFromSingleLine(commentDescriptors, endMessage, endLine.Start, todoList);
}
}
}
| -1 |
dotnet/roslyn | 55,481 | include help link uri in lsp pull diagnostics | Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | dibarbet | 2021-08-06T22:08:03Z | 2021-08-09T17:51:07Z | 845e2f4f5dfbc7433562ac242927c09fdfb15414 | 58c4cceb4aa4fe5212b59307603898fa3c6b8bee | include help link uri in lsp pull diagnostics. Realized this was not being set for c# LSP pull diagnostics after the xaml PR. | ./src/VisualStudio/Core/Def/Implementation/Experimentation/KeybindingsResetLogger.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Internal.Log;
namespace Microsoft.CodeAnalysis.Experimentation
{
internal static class KeybindingsResetLogger
{
private const string Name = "KeybindingsResetDetector";
public static void Log(string action)
{
Logger.Log(FunctionId.Experiment_KeybindingsReset, KeyValueLogMessage.Create(LogType.UserAction, m =>
{
m[nameof(Name)] = Name;
m[nameof(action)] = action;
}));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Internal.Log;
namespace Microsoft.CodeAnalysis.Experimentation
{
internal static class KeybindingsResetLogger
{
private const string Name = "KeybindingsResetDetector";
public static void Log(string action)
{
Logger.Log(FunctionId.Experiment_KeybindingsReset, KeyValueLogMessage.Create(LogType.UserAction, m =>
{
m[nameof(Name)] = Name;
m[nameof(action)] = action;
}));
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/VisualStudio/CSharp/Impl/LanguageService/CSharpCreateServicesOnTextViewConnection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets
{
[Export(typeof(IWpfTextViewConnectionListener))]
[ContentType(ContentTypeNames.CSharpContentType)]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
internal class CSharpCreateServicesOnTextViewConnection : AbstractCreateServicesOnTextViewConnection
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCreateServicesOnTextViewConnection(
VisualStudioWorkspace workspace,
[ImportMany] IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> languageServices)
: base(workspace, languageServices, LanguageNames.CSharp)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets
{
[Export(typeof(IWpfTextViewConnectionListener))]
[ContentType(ContentTypeNames.CSharpContentType)]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
internal class CSharpCreateServicesOnTextViewConnection : AbstractCreateServicesOnTextViewConnection
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCreateServicesOnTextViewConnection(
VisualStudioWorkspace workspace,
IAsynchronousOperationListenerProvider listenerProvider,
IThreadingContext threadingContext)
: base(workspace, listenerProvider, threadingContext, LanguageNames.CSharp)
{
}
}
}
| 1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractCreateServicesOnTextViewConnection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Snippets;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
{
/// <summary>
/// Creates services on the first connection of an applicable subject buffer to an IWpfTextView.
/// This ensures the services are available by the time an open document or the interactive window needs them.
/// </summary>
internal abstract class AbstractCreateServicesOnTextViewConnection : IWpfTextViewConnectionListener
{
private readonly VisualStudioWorkspace _workspace;
private readonly IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> _languageServices;
private readonly string _languageName;
private bool _initialized = false;
public AbstractCreateServicesOnTextViewConnection(
VisualStudioWorkspace workspace,
IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> languageServices,
string languageName)
{
_workspace = workspace;
_languageName = languageName;
_languageServices = languageServices;
}
void IWpfTextViewConnectionListener.SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
if (!_initialized)
{
CreateServicesOnUIThread();
CreateServicesInBackground();
_initialized = true;
}
}
void IWpfTextViewConnectionListener.SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
}
/// <summary>
/// Must be invoked from the UI thread.
/// </summary>
private void CreateServicesOnUIThread()
{
var serviceTypeAssemblyQualifiedName = typeof(ISnippetInfoService).AssemblyQualifiedName;
foreach (var languageService in _languageServices)
{
if (languageService.Metadata.ServiceType == serviceTypeAssemblyQualifiedName &&
languageService.Metadata.Language == _languageName)
{
_ = languageService.Value;
break;
}
}
}
private void CreateServicesInBackground()
{
_ = Task.Run(ImportCompletionProviders);
// Preload completion providers on a background thread since assembly loads can be slow
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1242321
void ImportCompletionProviders()
{
if (_workspace.Services.GetLanguageService<CompletionService>(_languageName) is CompletionServiceWithProviders service)
{
_ = service.GetImportedProviders().SelectAsArray(p => p.Value);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Snippets;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
{
/// <summary>
/// Creates services on the first connection of an applicable subject buffer to an IWpfTextView.
/// This ensures the services are available by the time an open document or the interactive window needs them.
/// </summary>
internal abstract class AbstractCreateServicesOnTextViewConnection : IWpfTextViewConnectionListener
{
private readonly VisualStudioWorkspace _workspace;
private readonly IAsynchronousOperationListener _listener;
private readonly IThreadingContext _threadingContext;
private readonly string _languageName;
private bool _initialized = false;
public AbstractCreateServicesOnTextViewConnection(
VisualStudioWorkspace workspace,
IAsynchronousOperationListenerProvider listenerProvider,
IThreadingContext threadingContext,
string languageName)
{
_workspace = workspace;
_listener = listenerProvider.GetListener(FeatureAttribute.Workspace);
_threadingContext = threadingContext;
_languageName = languageName;
}
void IWpfTextViewConnectionListener.SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
if (!_initialized)
{
var token = _listener.BeginAsyncOperation(nameof(InitializeServicesAsync));
InitializeServicesAsync().CompletesAsyncOperation(token);
_initialized = true;
}
}
void IWpfTextViewConnectionListener.SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers)
{
}
private async Task InitializeServicesAsync()
{
await TaskScheduler.Default;
var languageServices = _workspace.Services.GetExtendedLanguageServices(_languageName);
_ = languageServices.GetService<ISnippetInfoService>();
// Preload completion providers on a background thread since assembly loads can be slow
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1242321
if (languageServices.GetService<CompletionService>() is CompletionServiceWithProviders service)
{
_ = service.GetImportedProviders().SelectAsArray(p => p.Value);
}
}
}
}
| 1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicCreateServicesOnTextViewConnection.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel.Composition
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
<Export(GetType(IWpfTextViewConnectionListener))>
<ContentType(ContentTypeNames.VisualBasicContentType)>
<TextViewRole(PredefinedTextViewRoles.Interactive)>
Friend Class VisualBasicCreateServicesOnTextViewConnection
Inherits AbstractCreateServicesOnTextViewConnection
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(workspace As VisualStudioWorkspace, <ImportMany> languageServices As IEnumerable(Of Lazy(Of ILanguageService, LanguageServiceMetadata)))
MyBase.New(workspace, languageServices, languageName:=LanguageNames.VisualBasic)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel.Composition
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
<Export(GetType(IWpfTextViewConnectionListener))>
<ContentType(ContentTypeNames.VisualBasicContentType)>
<TextViewRole(PredefinedTextViewRoles.Interactive)>
Friend Class VisualBasicCreateServicesOnTextViewConnection
Inherits AbstractCreateServicesOnTextViewConnection
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(
workspace As VisualStudioWorkspace,
listenerProvider As IAsynchronousOperationListenerProvider,
threadingContext As IThreadingContext)
MyBase.New(workspace, listenerProvider, threadingContext, languageName:=LanguageNames.VisualBasic)
End Sub
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/EditorFeatures/Core/Extensibility/Composition/OrderableContentTypeMetadata.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor
{
internal class OrderableContentTypeMetadata : OrderableMetadata, IContentTypeMetadata
{
public IEnumerable<string> ContentTypes { get; }
public OrderableContentTypeMetadata(IDictionary<string, object> data)
: base(data)
{
this.ContentTypes = (IEnumerable<string>)data.GetValueOrDefault("ContentTypes");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor
{
internal class OrderableContentTypeMetadata : OrderableMetadata, IContentTypeMetadata
{
public IEnumerable<string> ContentTypes { get; }
public OrderableContentTypeMetadata(IDictionary<string, object> data)
: base(data)
{
this.ContentTypes = (IEnumerable<string>)data.GetValueOrDefault("ContentTypes");
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionSimpleTypeName.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions
{
internal sealed class SnippetFunctionSimpleTypeName : AbstractSnippetFunctionSimpleTypeName
{
public SnippetFunctionSimpleTypeName(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName)
: base(snippetExpansionClient, subjectBuffer, fieldName, fullyQualifiedName)
{
}
protected override bool TryGetSimplifiedTypeName(Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName)
{
simplifiedTypeName = string.Empty;
var typeAnnotation = new SyntaxAnnotation();
var syntaxRoot = documentWithFullyQualifiedTypeName.GetRequiredSyntaxRootSynchronously(cancellationToken);
var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == updatedTextSpan);
if (nodeToReplace == null)
{
return false;
}
var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation));
var documentWithAnnotations = documentWithFullyQualifiedTypeName.WithSyntaxRoot(updatedRoot);
var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
simplifiedTypeName = simplifiedDocument.GetRequiredSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString();
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions
{
internal sealed class SnippetFunctionSimpleTypeName : AbstractSnippetFunctionSimpleTypeName
{
public SnippetFunctionSimpleTypeName(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName)
: base(snippetExpansionClient, subjectBuffer, fieldName, fullyQualifiedName)
{
}
protected override bool TryGetSimplifiedTypeName(Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName)
{
simplifiedTypeName = string.Empty;
var typeAnnotation = new SyntaxAnnotation();
var syntaxRoot = documentWithFullyQualifiedTypeName.GetRequiredSyntaxRootSynchronously(cancellationToken);
var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == updatedTextSpan);
if (nodeToReplace == null)
{
return false;
}
var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation));
var documentWithAnnotations = documentWithFullyQualifiedTypeName.WithSyntaxRoot(updatedRoot);
var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
simplifiedTypeName = simplifiedDocument.GetRequiredSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString();
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceParameterSymbolBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Base class for all parameters that are emitted.
/// </summary>
internal abstract class SourceParameterSymbolBase : ParameterSymbol
{
private readonly Symbol _containingSymbol;
private readonly ushort _ordinal;
public SourceParameterSymbolBase(Symbol containingSymbol, int ordinal)
{
Debug.Assert((object)containingSymbol != null);
_ordinal = (ushort)ordinal;
_containingSymbol = containingSymbol;
}
public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if (obj == (object)this)
{
return true;
}
if (obj is NativeIntegerParameterSymbol nps)
{
return nps.Equals(this, compareKind);
}
var symbol = obj as SourceParameterSymbolBase;
return (object)symbol != null
&& symbol.Ordinal == this.Ordinal
&& symbol._containingSymbol.Equals(_containingSymbol, compareKind);
}
public sealed override int GetHashCode()
{
return Hash.Combine(_containingSymbol.GetHashCode(), this.Ordinal);
}
public sealed override int Ordinal
{
get { return _ordinal; }
}
public sealed override Symbol ContainingSymbol
{
get { return _containingSymbol; }
}
public sealed override AssemblySymbol ContainingAssembly
{
get { return _containingSymbol.ContainingAssembly; }
}
internal abstract ConstantValue DefaultValueFromAttributes { get; }
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
var compilation = this.DeclaringCompilation;
if (this.IsParams)
{
AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_ParamArrayAttribute__ctor));
}
// Synthesize DecimalConstantAttribute if we don't have an explicit custom attribute already:
var defaultValue = this.ExplicitDefaultConstantValue;
if (defaultValue != ConstantValue.NotAvailable &&
defaultValue.SpecialType == SpecialType.System_Decimal &&
DefaultValueFromAttributes == ConstantValue.NotAvailable)
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(defaultValue.DecimalValue));
}
var type = this.TypeWithAnnotations;
if (type.Type.ContainsDynamic())
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind));
}
if (type.Type.ContainsNativeInteger())
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type));
}
if (type.Type.ContainsTupleNames())
{
AddSynthesizedAttribute(ref attributes,
compilation.SynthesizeTupleNamesAttribute(type.Type));
}
if (this.RefKind == RefKind.RefReadOnly)
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this));
}
if (compilation.ShouldEmitNullableAttributes(this))
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), type));
}
}
internal abstract ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Base class for all parameters that are emitted.
/// </summary>
internal abstract class SourceParameterSymbolBase : ParameterSymbol
{
private readonly Symbol _containingSymbol;
private readonly ushort _ordinal;
public SourceParameterSymbolBase(Symbol containingSymbol, int ordinal)
{
Debug.Assert((object)containingSymbol != null);
_ordinal = (ushort)ordinal;
_containingSymbol = containingSymbol;
}
public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if (obj == (object)this)
{
return true;
}
if (obj is NativeIntegerParameterSymbol nps)
{
return nps.Equals(this, compareKind);
}
var symbol = obj as SourceParameterSymbolBase;
return (object)symbol != null
&& symbol.Ordinal == this.Ordinal
&& symbol._containingSymbol.Equals(_containingSymbol, compareKind);
}
public sealed override int GetHashCode()
{
return Hash.Combine(_containingSymbol.GetHashCode(), this.Ordinal);
}
public sealed override int Ordinal
{
get { return _ordinal; }
}
public sealed override Symbol ContainingSymbol
{
get { return _containingSymbol; }
}
public sealed override AssemblySymbol ContainingAssembly
{
get { return _containingSymbol.ContainingAssembly; }
}
internal abstract ConstantValue DefaultValueFromAttributes { get; }
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
var compilation = this.DeclaringCompilation;
if (this.IsParams)
{
AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_ParamArrayAttribute__ctor));
}
// Synthesize DecimalConstantAttribute if we don't have an explicit custom attribute already:
var defaultValue = this.ExplicitDefaultConstantValue;
if (defaultValue != ConstantValue.NotAvailable &&
defaultValue.SpecialType == SpecialType.System_Decimal &&
DefaultValueFromAttributes == ConstantValue.NotAvailable)
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(defaultValue.DecimalValue));
}
var type = this.TypeWithAnnotations;
if (type.Type.ContainsDynamic())
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind));
}
if (type.Type.ContainsNativeInteger())
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type));
}
if (type.Type.ContainsTupleNames())
{
AddSynthesizedAttribute(ref attributes,
compilation.SynthesizeTupleNamesAttribute(type.Type));
}
if (this.RefKind == RefKind.RefReadOnly)
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this));
}
if (compilation.ShouldEmitNullableAttributes(this))
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), type));
}
}
internal abstract ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams);
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IAnonymousObjectCreationOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IAnonymousObjectCreationOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_01()
{
string source = @"
using System;
class C
{
void M(object p, int i, int j)
/*<bind>*/{
p = new { a = i, b = j };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a ... i, b = j };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a = i, b = j }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = i, b = j }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = i, b = j }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i, b = j }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = j')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i, b = j }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_02()
{
// Verify initializers that are not simple assignments.
string source = @"
using System;
class B
{
public int j = 0;
}
class C
{
private B b = new B();
void M(object p, int i)
/*<bind>*/{
p = new { i, b.j };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b.j')
Value:
IFieldReferenceOperation: System.Int32 B.j (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b.j')
Instance Receiver:
IFieldReferenceOperation: B C.b (OperationKind.FieldReference, Type: B) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { i, b.j };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { i, b.j }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { i, b.j }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 i, System.Int32 j>) (Syntax: 'new { i, b.j }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 i, System.Int32 j>.i { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 i, System.Int32 j>, IsImplicit) (Syntax: 'new { i, b.j }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b.j')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 i, System.Int32 j>.j { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'b.j')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 i, System.Int32 j>, IsImplicit) (Syntax: 'new { i, b.j }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b.j')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_03()
{
// Verify initializers that are mix of simple assignments and non-assignments.
string source = @"
using System;
class C
{
void M(object p, int a, int i)
/*<bind>*/{
p = new { a, b = i };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a, b = i };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a, b = i }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a, b = i }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a, b = i }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a, b = i }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a, b = i }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_04()
{
// Verify anonymous object creation in query.
string source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(object p, List<int> a, List<string> b)
/*<bind>*/{
p = from x in a
from y in b
where x == 0
select 0;
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = from x ... select 0;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = from x ... select 0')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'from x in a ... select 0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from x in a ... select 0')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<<anonymous type: System.Int32 x, System.String y>, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>> source, System.Func<<anonymous type: System.Int32 x, System.String y>, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select 0')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'where x == 0')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>> System.Linq.Enumerable.Where<<anonymous type: System.Int32 x, System.String y>>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>> source, System.Func<<anonymous type: System.Int32 x, System.String y>, System.Boolean> predicate)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>>, IsImplicit) (Syntax: 'where x == 0')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from y in b')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>> System.Linq.Enumerable.SelectMany<System.Int32, System.String, <anonymous type: System.Int32 x, System.String y>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.String>> collectionSelector, System.Func<System.Int32, System.String, <anonymous type: System.Int32 x, System.String y>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>>, IsImplicit) (Syntax: 'from y in b')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x in a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'b')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.String>>, IsImplicit) (Syntax: 'b')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: 'b')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Block[B1#A0] - Block
Predecessors: [B0#A0]
Statements (0)
Next (Return) Block[B2#A0]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'b')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Collections.Generic.List<System.String>) (Syntax: 'b')
Block[B2#A0] - Exit
Predecessors: [B1#A0]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from y in b')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.String, <anonymous type: System.Int32 x, System.String y>>, IsImplicit) (Syntax: 'from y in b')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: 'from y in b')
{
Block[B0#A1] - Entry
Statements (0)
Next (Regular) Block[B1#A1]
Entering: {R1#A1}
.locals {R1#A1}
{
CaptureIds: [0] [1]
Block[B1#A1] - Block
Predecessors: [B0#A1]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'from y in b')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in b')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'from y in b')
Value:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String, IsImplicit) (Syntax: 'from y in b')
Next (Return) Block[B2#A1]
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.String y>, IsImplicit) (Syntax: 'from y in b')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from y in b ... select 0')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.String y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.String y>, IsImplicit) (Syntax: 'from y in b')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in b')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'from y in b ... select 0')
Left:
IPropertyReferenceOperation: System.String <anonymous type: System.Int32 x, System.String y>.y { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'from y in b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.String y>, IsImplicit) (Syntax: 'from y in b')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'from y in b')
Leaving: {R1#A1}
}
Block[B2#A1] - Exit
Predecessors: [B1#A1]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x == 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.String y>, System.Boolean>, IsImplicit) (Syntax: 'x == 0')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: 'x == 0')
{
Block[B0#A2] - Entry
Statements (0)
Next (Regular) Block[B1#A2]
Block[B1#A2] - Block
Predecessors: [B0#A2]
Statements (0)
Next (Return) Block[B2#A2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x == 0')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.String y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.String y>, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Block[B2#A2] - Exit
Predecessors: [B1#A2]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.String y>, System.Int32>, IsImplicit) (Syntax: '0')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: '0')
{
Block[B0#A3] - Entry
Statements (0)
Next (Regular) Block[B1#A3]
Block[B1#A3] - Block
Predecessors: [B0#A3]
Statements (0)
Next (Return) Block[B2#A3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Block[B2#A3] - Exit
Predecessors: [B1#A3]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_05()
{
// Verify anonymous object creation in query with transparent identifiers.
string source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(object p, List<int> a)
/*<bind>*/{
p = from x in a
let y = x
where x == 0
select 0;
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = from x ... select 0;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = from x ... select 0')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'from x in a ... select 0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from x in a ... select 0')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select 0')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'where x == 0')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> System.Linq.Enumerable.Where<<anonymous type: System.Int32 x, System.Int32 y>>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Boolean> predicate)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'where x == 0')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let y = x')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> System.Linq.Enumerable.Select<System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, <anonymous type: System.Int32 x, System.Int32 y>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'let y = x')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x in a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'x')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Entering: {R1#A0}
.locals {R1#A0}
{
CaptureIds: [0] [1]
Block[B1#A0] - Block
Predecessors: [B0#A0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'let y = x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'let y = x')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Next (Return) Block[B2#A0]
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'let y = x')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let y = x ... select 0')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'let y = x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'let y = x')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'let y = x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let y = x')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'let y = x')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Leaving: {R1#A0}
}
Block[B2#A0] - Exit
Predecessors: [B1#A0]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x == 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Boolean>, IsImplicit) (Syntax: 'x == 0')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: 'x == 0')
{
Block[B0#A1] - Entry
Statements (0)
Next (Regular) Block[B1#A1]
Block[B1#A1] - Block
Predecessors: [B0#A1]
Statements (0)
Next (Return) Block[B2#A1]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x == 0')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Block[B2#A1] - Exit
Predecessors: [B1#A1]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32>, IsImplicit) (Syntax: '0')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: '0')
{
Block[B0#A2] - Entry
Statements (0)
Next (Regular) Block[B1#A2]
Block[B1#A2] - Block
Predecessors: [B0#A2]
Statements (0)
Next (Return) Block[B2#A2]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Block[B2#A2] - Exit
Predecessors: [B1#A2]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_06()
{
// Verify anonymous object creation nested in object creation initializer.
string source = @"
using System;
class C
{
public int a = 1;
public object b;
void M(object p, int i1, int i2, int i3)
/*<bind>*/{
p = new C() { a = i1, b = new { a = i2, b = i3 }};
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C() { a ... , b = i3 }}')
Value:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { a ... , b = i3 }}')
Arguments(0)
Initializer:
null
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i1')
Left:
IFieldReferenceOperation: System.Int32 C.a (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'new C() { a ... , b = i3 }}')
Right:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2] [3]
Block[B2] - Block
Predecessors: [B1]
Statements (3)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'b = new { a ... 2, b = i3 }')
Left:
IFieldReferenceOperation: System.Object C.b (OperationKind.FieldReference, Type: System.Object) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'new C() { a ... , b = i3 }}')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = i2, b = i3 }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = i3')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3')
Next (Regular) Block[B3]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new C() ... b = i3 }};')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new C() ... , b = i3 }}')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new C() { a ... , b = i3 }}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'new C() { a ... , b = i3 }}')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_07()
{
// Verify anonymous object creation nested in anonymous object creation initializer.
string source = @"
using System;
class C
{
void M(object p, int i1, int i2, int i3)
/*<bind>*/{
p = new { a = i1, b = new { a = i2, b = i3 }};
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [4]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2] [3]
Block[B2] - Block
Predecessors: [B1]
Statements (3)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Value:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = i2, b = i3 }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = i3')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3')
Next (Regular) Block[B3]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a ... b = i3 }};')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a ... , b = i3 }}')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = i ... , b = i3 }}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, <anonymous type: System.Int32 a, System.Int32 b> b>) (Syntax: 'new { a = i ... , b = i3 }}')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i1')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, <anonymous type: System.Int32 a, System.Int32 b> b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, <anonymous type: System.Int32 a, System.Int32 b> b>, IsImplicit) (Syntax: 'new { a = i ... , b = i3 }}')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'b = new { a ... 2, b = i3 }')
Left:
IPropertyReferenceOperation: <anonymous type: System.Int32 a, System.Int32 b> <anonymous type: System.Int32 a, <anonymous type: System.Int32 a, System.Int32 b> b>.b { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, <anonymous type: System.Int32 a, System.Int32 b> b>, IsImplicit) (Syntax: 'new { a = i ... , b = i3 }}')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_08()
{
// Verify anonymous object creation with no initializers.
string source = @"
using System;
class C
{
void M(object p)
/*<bind>*/{
p = new { };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { }')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <empty anonymous type>) (Syntax: 'new { }')
Initializers(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_Error01()
{
// Duplicate property name, ensure we have same number of initializers as properties.
string source = @"
using System;
class C
{
void M(object p, int i)
/*<bind>*/{
p = new { i, i };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = new { i, i };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'p = new { i, i }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'new { i, i }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 i, System.Int32 $1>, IsInvalid) (Syntax: 'new { i, i }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 i, System.Int32 $1>.i { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 i, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { i, i }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 i, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 i, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { i, i }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,22): error CS0833: An anonymous type cannot have multiple properties with the same name
// p = new { i, i };
Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "i").WithLocation(8, 22)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_Error02()
{
// Missing value for property assignment.
string source = @"
using System;
class C
{
void M(object p)
/*<bind>*/{
p = new { a = };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Value:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = new { a = };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'p = new { a = }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'new { a = }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: ? a>, IsInvalid) (Syntax: 'new { a = }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'a = ')
Left:
IPropertyReferenceOperation: ? <anonymous type: ? a>.a { get; } (OperationKind.PropertyReference, Type: ?) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: ? a>, IsInvalid, IsImplicit) (Syntax: 'new { a = }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,23): error CS1525: Invalid expression term '}'
// p = new { a = };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(8, 23)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_Error03()
{
// Invalid expression as initializer target, ensure we don't drop this expression from the flow graph.
string source = @"
using System;
class C
{
void M(object p, int i)
/*<bind>*/{
p = new { M2() = i };
}/*</bind>*/
int M2() => 0;
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2() = i')
Value:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'M2() = i')
Left:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()')
Children(1):
IInvocationOperation ( System.Int32 C.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
Arguments(0)
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = new { M2() = i };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'p = new { M2() = i }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'new { M2() = i }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 $0>, IsInvalid) (Syntax: 'new { M2() = i }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2() = i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 $0>.$0 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2() = i')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 $0>, IsInvalid, IsImplicit) (Syntax: 'new { M2() = i }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2() = i')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,19): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
// p = new { M2() = i };
Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "M2() = i").WithLocation(8, 19),
// file.cs(8,19): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// p = new { M2() = i };
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "M2()").WithLocation(8, 19)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_Error04()
{
// Property reference with argument as an assignment target.
string source = @"
using System;
class C
{
void M(object p, int i, int j)
/*<bind>*/{
p = new { a[i] = j };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a[i] = j')
Value:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'a[i] = j')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'a[i]')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i')
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'a')
Children(0)
Right:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = new { a[i] = j };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'p = new { a[i] = j }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'new { a[i] = j }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: ? $0>, IsInvalid) (Syntax: 'new { a[i] = j }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'a[i] = j')
Left:
IPropertyReferenceOperation: ? <anonymous type: ? $0>.$0 { get; } (OperationKind.PropertyReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'a[i] = j')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: ? $0>, IsInvalid, IsImplicit) (Syntax: 'new { a[i] = j }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'a[i] = j')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,19): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
// p = new { a[i] = j };
Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "a[i] = j").WithLocation(8, 19),
// file.cs(8,19): error CS0103: The name 'a' does not exist in the current context
// p = new { a[i] = j };
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(8, 19)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_ControlFlowInFirstInitializer()
{
string source = @"
using System;
class C
{
void M(object p, int? i1, int i2, int j)
/*<bind>*/{
p = new { a = i1 ?? i2, b = j };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a ... 2, b = j };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a ... i2, b = j }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = i ... i2, b = j }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = i ... i2, b = j }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i1 ?? i2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i ... i2, b = j }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1 ?? i2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = j')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i ... i2, b = j }')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_ControlFlowInSecondInitializer()
{
string source = @"
using System;
class C
{
void M(object p, int? i1, int i2, int j)
/*<bind>*/{
p = new { a = j, b = i1 ?? i2 };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a ... i1 ?? i2 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a ... i1 ?? i2 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = j ... i1 ?? i2 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = j ... i1 ?? i2 }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = j')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = j ... i1 ?? i2 }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = i1 ?? i2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = j ... i1 ?? i2 }')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1 ?? i2')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_ControlFlowInMultipleInitializers()
{
string source = @"
using System;
class C
{
void M(object p, int? i1, int i2, int? j1, int j2)
/*<bind>*/{
p = new { a = i1 ?? i2, b = j1 ?? j2 };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2] [4]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Entering: {R3}
.locals {R3}
{
CaptureIds: [3]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'j1')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'j1')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'j1')
Leaving: {R3}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'j1')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'j1')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R3}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j2')
Value:
IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a ... j1 ?? j2 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a ... j1 ?? j2 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = i ... j1 ?? j2 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = i ... j1 ?? j2 }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i1 ?? i2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i ... j1 ?? j2 }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1 ?? i2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = j1 ?? j2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i ... j1 ?? j2 }')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j1 ?? j2')
Next (Regular) Block[B9]
Leaving: {R1}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[Fact]
public void AnonymousObjectCreation_NullableEnabled_PropertyMatches()
{
var source = @"
#nullable enable
class C
{
void M(int i1, object o1)
{
var obj = /*<bind>*/new { a = i1, o1, b = ""Hello world!"" }/*</bind>*/;
}
}";
var expectedOperationTree = @"
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Object o1, System.String b>) (Syntax: 'new { a = i ... o world!"" }')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i1')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Object o1, System.String b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Object o1, System.String b>, IsImplicit) (Syntax: 'new { a = i ... o world!"" }')
Right:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'o1')
Left:
IPropertyReferenceOperation: System.Object <anonymous type: System.Int32 a, System.Object o1, System.String b>.o1 { get; } (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'o1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Object o1, System.String b>, IsImplicit) (Syntax: 'new { a = i ... o world!"" }')
Right:
IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, Constant: ""Hello world!"") (Syntax: 'b = ""Hello world!""')
Left:
IPropertyReferenceOperation: System.String <anonymous type: System.Int32 a, System.Object o1, System.String b>.b { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Object o1, System.String b>, IsImplicit) (Syntax: 'new { a = i ... o world!"" }')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Hello world!"") (Syntax: '""Hello world!""')";
VerifyOperationTreeAndDiagnosticsForTest<AnonymousObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: DiagnosticDescription.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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IAnonymousObjectCreationOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_01()
{
string source = @"
using System;
class C
{
void M(object p, int i, int j)
/*<bind>*/{
p = new { a = i, b = j };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a ... i, b = j };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a = i, b = j }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = i, b = j }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = i, b = j }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i, b = j }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = j')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i, b = j }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_02()
{
// Verify initializers that are not simple assignments.
string source = @"
using System;
class B
{
public int j = 0;
}
class C
{
private B b = new B();
void M(object p, int i)
/*<bind>*/{
p = new { i, b.j };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b.j')
Value:
IFieldReferenceOperation: System.Int32 B.j (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b.j')
Instance Receiver:
IFieldReferenceOperation: B C.b (OperationKind.FieldReference, Type: B) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'b')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { i, b.j };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { i, b.j }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { i, b.j }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 i, System.Int32 j>) (Syntax: 'new { i, b.j }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 i, System.Int32 j>.i { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 i, System.Int32 j>, IsImplicit) (Syntax: 'new { i, b.j }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b.j')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 i, System.Int32 j>.j { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'b.j')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 i, System.Int32 j>, IsImplicit) (Syntax: 'new { i, b.j }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b.j')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_03()
{
// Verify initializers that are mix of simple assignments and non-assignments.
string source = @"
using System;
class C
{
void M(object p, int a, int i)
/*<bind>*/{
p = new { a, b = i };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a, b = i };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a, b = i }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a, b = i }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a, b = i }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'a')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a, b = i }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a, b = i }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_04()
{
// Verify anonymous object creation in query.
string source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(object p, List<int> a, List<string> b)
/*<bind>*/{
p = from x in a
from y in b
where x == 0
select 0;
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = from x ... select 0;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = from x ... select 0')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'from x in a ... select 0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from x in a ... select 0')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<<anonymous type: System.Int32 x, System.String y>, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>> source, System.Func<<anonymous type: System.Int32 x, System.String y>, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select 0')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'where x == 0')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>> System.Linq.Enumerable.Where<<anonymous type: System.Int32 x, System.String y>>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>> source, System.Func<<anonymous type: System.Int32 x, System.String y>, System.Boolean> predicate)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>>, IsImplicit) (Syntax: 'where x == 0')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from y in b')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>> System.Linq.Enumerable.SelectMany<System.Int32, System.String, <anonymous type: System.Int32 x, System.String y>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.String>> collectionSelector, System.Func<System.Int32, System.String, <anonymous type: System.Int32 x, System.String y>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.String y>>, IsImplicit) (Syntax: 'from y in b')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x in a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'b')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.String>>, IsImplicit) (Syntax: 'b')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: 'b')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Block[B1#A0] - Block
Predecessors: [B0#A0]
Statements (0)
Next (Return) Block[B2#A0]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'b')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Collections.Generic.List<System.String>) (Syntax: 'b')
Block[B2#A0] - Exit
Predecessors: [B1#A0]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from y in b')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.String, <anonymous type: System.Int32 x, System.String y>>, IsImplicit) (Syntax: 'from y in b')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: 'from y in b')
{
Block[B0#A1] - Entry
Statements (0)
Next (Regular) Block[B1#A1]
Entering: {R1#A1}
.locals {R1#A1}
{
CaptureIds: [0] [1]
Block[B1#A1] - Block
Predecessors: [B0#A1]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'from y in b')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in b')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'from y in b')
Value:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String, IsImplicit) (Syntax: 'from y in b')
Next (Return) Block[B2#A1]
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.String y>, IsImplicit) (Syntax: 'from y in b')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from y in b ... select 0')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.String y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.String y>, IsImplicit) (Syntax: 'from y in b')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in b')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'from y in b ... select 0')
Left:
IPropertyReferenceOperation: System.String <anonymous type: System.Int32 x, System.String y>.y { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'from y in b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.String y>, IsImplicit) (Syntax: 'from y in b')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'from y in b')
Leaving: {R1#A1}
}
Block[B2#A1] - Exit
Predecessors: [B1#A1]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x == 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.String y>, System.Boolean>, IsImplicit) (Syntax: 'x == 0')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: 'x == 0')
{
Block[B0#A2] - Entry
Statements (0)
Next (Regular) Block[B1#A2]
Block[B1#A2] - Block
Predecessors: [B0#A2]
Statements (0)
Next (Return) Block[B2#A2]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x == 0')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.String y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.String y>, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Block[B2#A2] - Exit
Predecessors: [B1#A2]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.String y>, System.Int32>, IsImplicit) (Syntax: '0')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: '0')
{
Block[B0#A3] - Entry
Statements (0)
Next (Regular) Block[B1#A3]
Block[B1#A3] - Block
Predecessors: [B0#A3]
Statements (0)
Next (Return) Block[B2#A3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Block[B2#A3] - Exit
Predecessors: [B1#A3]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_05()
{
// Verify anonymous object creation in query with transparent identifiers.
string source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(object p, List<int> a)
/*<bind>*/{
p = from x in a
let y = x
where x == 0
select 0;
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = from x ... select 0;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = from x ... select 0')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'from x in a ... select 0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from x in a ... select 0')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select 0')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'where x == 0')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> System.Linq.Enumerable.Where<<anonymous type: System.Int32 x, System.Int32 y>>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Boolean> predicate)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'where x == 0')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let y = x')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> System.Linq.Enumerable.Select<System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, <anonymous type: System.Int32 x, System.Int32 y>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'let y = x')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in a')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x in a')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'x')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Entering: {R1#A0}
.locals {R1#A0}
{
CaptureIds: [0] [1]
Block[B1#A0] - Block
Predecessors: [B0#A0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'let y = x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'let y = x')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Next (Return) Block[B2#A0]
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'let y = x')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let y = x ... select 0')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'let y = x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'let y = x')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'let y = x')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let y = x')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'let y = x')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x')
Leaving: {R1#A0}
}
Block[B2#A0] - Exit
Predecessors: [B1#A0]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x == 0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Boolean>, IsImplicit) (Syntax: 'x == 0')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: 'x == 0')
{
Block[B0#A1] - Entry
Statements (0)
Next (Regular) Block[B1#A1]
Block[B1#A1] - Block
Predecessors: [B0#A1]
Statements (0)
Next (Return) Block[B2#A1]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x == 0')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Block[B2#A1] - Exit
Predecessors: [B1#A1]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '0')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32>, IsImplicit) (Syntax: '0')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsImplicit) (Syntax: '0')
{
Block[B0#A2] - Entry
Statements (0)
Next (Regular) Block[B1#A2]
Block[B1#A2] - Block
Predecessors: [B0#A2]
Statements (0)
Next (Return) Block[B2#A2]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Block[B2#A2] - Exit
Predecessors: [B1#A2]
Statements (0)
}
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_06()
{
// Verify anonymous object creation nested in object creation initializer.
string source = @"
using System;
class C
{
public int a = 1;
public object b;
void M(object p, int i1, int i2, int i3)
/*<bind>*/{
p = new C() { a = i1, b = new { a = i2, b = i3 }};
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new C() { a ... , b = i3 }}')
Value:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C() { a ... , b = i3 }}')
Arguments(0)
Initializer:
null
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i1')
Left:
IFieldReferenceOperation: System.Int32 C.a (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'new C() { a ... , b = i3 }}')
Right:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2] [3]
Block[B2] - Block
Predecessors: [B1]
Statements (3)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'b = new { a ... 2, b = i3 }')
Left:
IFieldReferenceOperation: System.Object C.b (OperationKind.FieldReference, Type: System.Object) (Syntax: 'b')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'new C() { a ... , b = i3 }}')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = i2, b = i3 }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = i3')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3')
Next (Regular) Block[B3]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new C() ... b = i3 }};')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new C() ... , b = i3 }}')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new C() { a ... , b = i3 }}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'new C() { a ... , b = i3 }}')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_07()
{
// Verify anonymous object creation nested in anonymous object creation initializer.
string source = @"
using System;
class C
{
void M(object p, int i1, int i2, int i3)
/*<bind>*/{
p = new { a = i1, b = new { a = i2, b = i3 }};
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [4]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2] [3]
Block[B2] - Block
Predecessors: [B1]
Statements (3)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Value:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = i2, b = i3 }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = i3')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3')
Next (Regular) Block[B3]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a ... b = i3 }};')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a ... , b = i3 }}')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = i ... , b = i3 }}')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, <anonymous type: System.Int32 a, System.Int32 b> b>) (Syntax: 'new { a = i ... , b = i3 }}')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i1')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, <anonymous type: System.Int32 a, System.Int32 b> b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, <anonymous type: System.Int32 a, System.Int32 b> b>, IsImplicit) (Syntax: 'new { a = i ... , b = i3 }}')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'b = new { a ... 2, b = i3 }')
Left:
IPropertyReferenceOperation: <anonymous type: System.Int32 a, System.Int32 b> <anonymous type: System.Int32 a, <anonymous type: System.Int32 a, System.Int32 b> b>.b { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, <anonymous type: System.Int32 a, System.Int32 b> b>, IsImplicit) (Syntax: 'new { a = i ... , b = i3 }}')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i2, b = i3 }')
Next (Regular) Block[B4]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_08()
{
// Verify anonymous object creation with no initializers.
string source = @"
using System;
class C
{
void M(object p)
/*<bind>*/{
p = new { };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { }')
Left:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <empty anonymous type>) (Syntax: 'new { }')
Initializers(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_Error01()
{
// Duplicate property name, ensure we have same number of initializers as properties.
string source = @"
using System;
class C
{
void M(object p, int i)
/*<bind>*/{
p = new { i, i };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = new { i, i };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'p = new { i, i }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'new { i, i }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 i, System.Int32 $1>, IsInvalid) (Syntax: 'new { i, i }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 i, System.Int32 $1>.i { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 i, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { i, i }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 i, System.Int32 $1>.$1 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 i, System.Int32 $1>, IsInvalid, IsImplicit) (Syntax: 'new { i, i }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,22): error CS0833: An anonymous type cannot have multiple properties with the same name
// p = new { i, i };
Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "i").WithLocation(8, 22)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_Error02()
{
// Missing value for property assignment.
string source = @"
using System;
class C
{
void M(object p)
/*<bind>*/{
p = new { a = };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Value:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = new { a = };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'p = new { a = }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'new { a = }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: ? a>, IsInvalid) (Syntax: 'new { a = }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'a = ')
Left:
IPropertyReferenceOperation: ? <anonymous type: ? a>.a { get; } (OperationKind.PropertyReference, Type: ?) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: ? a>, IsInvalid, IsImplicit) (Syntax: 'new { a = }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,23): error CS1525: Invalid expression term '}'
// p = new { a = };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(8, 23)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_Error03()
{
// Invalid expression as initializer target, ensure we don't drop this expression from the flow graph.
string source = @"
using System;
class C
{
void M(object p, int i)
/*<bind>*/{
p = new { M2() = i };
}/*</bind>*/
int M2() => 0;
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2() = i')
Value:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'M2() = i')
Left:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2()')
Children(1):
IInvocationOperation ( System.Int32 C.M2()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
Arguments(0)
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = new { M2() = i };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'p = new { M2() = i }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'new { M2() = i }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 $0>, IsInvalid) (Syntax: 'new { M2() = i }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2() = i')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 $0>.$0 { get; } (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2() = i')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 $0>, IsInvalid, IsImplicit) (Syntax: 'new { M2() = i }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2() = i')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,19): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
// p = new { M2() = i };
Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "M2() = i").WithLocation(8, 19),
// file.cs(8,19): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// p = new { M2() = i };
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "M2()").WithLocation(8, 19)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_NoControlFlow_Error04()
{
// Property reference with argument as an assignment target.
string source = @"
using System;
class C
{
void M(object p, int i, int j)
/*<bind>*/{
p = new { a[i] = j };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a[i] = j')
Value:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'a[i] = j')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'a[i]')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'i')
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'a')
Children(0)
Right:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'j')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'p = new { a[i] = j };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'p = new { a[i] = j }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'new { a[i] = j }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: ? $0>, IsInvalid) (Syntax: 'new { a[i] = j }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'a[i] = j')
Left:
IPropertyReferenceOperation: ? <anonymous type: ? $0>.$0 { get; } (OperationKind.PropertyReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'a[i] = j')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: ? $0>, IsInvalid, IsImplicit) (Syntax: 'new { a[i] = j }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'a[i] = j')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(8,19): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
// p = new { a[i] = j };
Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "a[i] = j").WithLocation(8, 19),
// file.cs(8,19): error CS0103: The name 'a' does not exist in the current context
// p = new { a[i] = j };
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(8, 19)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_ControlFlowInFirstInitializer()
{
string source = @"
using System;
class C
{
void M(object p, int? i1, int i2, int j)
/*<bind>*/{
p = new { a = i1 ?? i2, b = j };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a ... 2, b = j };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a ... i2, b = j }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = i ... i2, b = j }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = i ... i2, b = j }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i1 ?? i2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i ... i2, b = j }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1 ?? i2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = j')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i ... i2, b = j }')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_ControlFlowInSecondInitializer()
{
string source = @"
using System;
class C
{
void M(object p, int? i1, int i2, int j)
/*<bind>*/{
p = new { a = j, b = i1 ?? i2 };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a ... i1 ?? i2 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a ... i1 ?? i2 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = j ... i1 ?? i2 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = j ... i1 ?? i2 }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = j')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = j ... i1 ?? i2 }')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = i1 ?? i2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = j ... i1 ?? i2 }')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1 ?? i2')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void AnonymousObjectCreation_ControlFlowInMultipleInitializers()
{
string source = @"
using System;
class C
{
void M(object p, int? i1, int i2, int? j1, int j2)
/*<bind>*/{
p = new { a = i1 ?? i2, b = j1 ?? j2 };
}/*</bind>*/
}
";
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2] [4]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p')
Value:
IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
Entering: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Next (Regular) Block[B5]
Entering: {R3}
.locals {R3}
{
CaptureIds: [3]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IParameterReferenceOperation: j1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'j1')
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'j1')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'j1')
Leaving: {R3}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j1')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'j1')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'j1')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R3}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j2')
Value:
IParameterReferenceOperation: j2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = new { a ... j1 ?? j2 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'p = new { a ... j1 ?? j2 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'p')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'new { a = i ... j1 ?? j2 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Int32 b>) (Syntax: 'new { a = i ... j1 ?? j2 }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i1 ?? i2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i ... j1 ?? j2 }')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1 ?? i2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'b = j1 ?? j2')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Int32 b>.b { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Int32 b>, IsImplicit) (Syntax: 'new { a = i ... j1 ?? j2 }')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j1 ?? j2')
Next (Regular) Block[B9]
Leaving: {R1}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[Fact]
public void AnonymousObjectCreation_NullableEnabled_PropertyMatches()
{
var source = @"
#nullable enable
class C
{
void M(int i1, object o1)
{
var obj = /*<bind>*/new { a = i1, o1, b = ""Hello world!"" }/*</bind>*/;
}
}";
var expectedOperationTree = @"
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 a, System.Object o1, System.String b>) (Syntax: 'new { a = i ... o world!"" }')
Initializers(3):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = i1')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 a, System.Object o1, System.String b>.a { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'a')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Object o1, System.String b>, IsImplicit) (Syntax: 'new { a = i ... o world!"" }')
Right:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'o1')
Left:
IPropertyReferenceOperation: System.Object <anonymous type: System.Int32 a, System.Object o1, System.String b>.o1 { get; } (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'o1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Object o1, System.String b>, IsImplicit) (Syntax: 'new { a = i ... o world!"" }')
Right:
IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, Constant: ""Hello world!"") (Syntax: 'b = ""Hello world!""')
Left:
IPropertyReferenceOperation: System.String <anonymous type: System.Int32 a, System.Object o1, System.String b>.b { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 a, System.Object o1, System.String b>, IsImplicit) (Syntax: 'new { a = i ... o world!"" }')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Hello world!"") (Syntax: '""Hello world!""')";
VerifyOperationTreeAndDiagnosticsForTest<AnonymousObjectCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: DiagnosticDescription.None);
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Compilers/VisualBasic/Portable/Symbols/LabelSymbol.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.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend MustInherit Class LabelSymbol
Inherits Symbol
Implements ILabelSymbol
Public Sub New(name As String)
Me._name = name
End Sub
Private ReadOnly _name As String
Public Overrides ReadOnly Property Name As String
Get
Return Me._name
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.NotApplicable
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Friend Overloads Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Return visitor.VisitLabel(Me, arg)
End Function
Public Overridable ReadOnly Property ContainingMethod As MethodSymbol
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return ContainingMethod
End Get
End Property
Public Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.Label
End Get
End Property
' Get the token that defined this label symbol. This is useful for robustly checking
' if a label symbol actually matches a particular definition, even in the presence of duplicates.
Friend Overridable ReadOnly Property LabelName As SyntaxToken
Get
Return Nothing
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
#Region "ILabelSymbol"
Friend ReadOnly Property ILabelSymbol_ContainingMethod As IMethodSymbol Implements ILabelSymbol.ContainingMethod
Get
Return ContainingMethod
End Get
End Property
#End Region
#Region "ISymbol"
Public Overrides Sub Accept(visitor As SymbolVisitor)
visitor.VisitLabel(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult
Return visitor.VisitLabel(Me)
End Function
Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
visitor.VisitLabel(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Return visitor.VisitLabel(Me)
End Function
#End Region
End Class
Friend Class GeneratedLabelSymbol
Inherits LabelSymbol
Public Sub New(name As String)
MyBase.New(name)
End Sub
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
End Class
Friend Class GeneratedUnstructuredExceptionHandlingResumeLabel
Inherits GeneratedLabelSymbol
''' <summary>
''' A [Resume] or [On Error Resume Next] statement.
''' </summary>
Public ReadOnly ResumeStatement As StatementSyntax
Public Sub New(resumeStmt As StatementSyntax)
MyBase.New("$VB$UnstructuredExceptionHandling_TargetResumeLabel")
Debug.Assert(resumeStmt.Kind = SyntaxKind.OnErrorResumeNextStatement OrElse
resumeStmt.Kind = SyntaxKind.ResumeNextStatement OrElse
resumeStmt.Kind = SyntaxKind.ResumeStatement)
ResumeStatement = resumeStmt
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.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend MustInherit Class LabelSymbol
Inherits Symbol
Implements ILabelSymbol
Public Sub New(name As String)
Me._name = name
End Sub
Private ReadOnly _name As String
Public Overrides ReadOnly Property Name As String
Get
Return Me._name
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.NotApplicable
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Friend Overloads Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult
Return visitor.VisitLabel(Me, arg)
End Function
Public Overridable ReadOnly Property ContainingMethod As MethodSymbol
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return ContainingMethod
End Get
End Property
Public Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.Label
End Get
End Property
' Get the token that defined this label symbol. This is useful for robustly checking
' if a label symbol actually matches a particular definition, even in the presence of duplicates.
Friend Overridable ReadOnly Property LabelName As SyntaxToken
Get
Return Nothing
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
#Region "ILabelSymbol"
Friend ReadOnly Property ILabelSymbol_ContainingMethod As IMethodSymbol Implements ILabelSymbol.ContainingMethod
Get
Return ContainingMethod
End Get
End Property
#End Region
#Region "ISymbol"
Public Overrides Sub Accept(visitor As SymbolVisitor)
visitor.VisitLabel(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult
Return visitor.VisitLabel(Me)
End Function
Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
visitor.VisitLabel(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Return visitor.VisitLabel(Me)
End Function
#End Region
End Class
Friend Class GeneratedLabelSymbol
Inherits LabelSymbol
Public Sub New(name As String)
MyBase.New(name)
End Sub
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
End Class
Friend Class GeneratedUnstructuredExceptionHandlingResumeLabel
Inherits GeneratedLabelSymbol
''' <summary>
''' A [Resume] or [On Error Resume Next] statement.
''' </summary>
Public ReadOnly ResumeStatement As StatementSyntax
Public Sub New(resumeStmt As StatementSyntax)
MyBase.New("$VB$UnstructuredExceptionHandling_TargetResumeLabel")
Debug.Assert(resumeStmt.Kind = SyntaxKind.OnErrorResumeNextStatement OrElse
resumeStmt.Kind = SyntaxKind.ResumeNextStatement OrElse
resumeStmt.Kind = SyntaxKind.ResumeStatement)
ResumeStatement = resumeStmt
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/VisualStudio/IntegrationTest/TestUtilities/Common/ProjectUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils
{
public abstract class Identity
{
protected Identity(string name)
{
Name = name;
}
public string Name { get; }
}
public class Project : Identity
{
public Project(string name, string projectExtension = ".csproj", string? relativePath = null)
: base(name)
{
if (string.IsNullOrWhiteSpace(relativePath))
{
RelativePath = Path.Combine(name, name + projectExtension);
}
else
{
RelativePath = relativePath;
}
}
/// <summary>
/// This path is relative to the Solution file. Default value is set to ProjectName\ProjectName.csproj
/// </summary>
public string? RelativePath { get; }
}
public class ProjectReference : Identity
{
public ProjectReference(string name)
: base(name)
{
}
}
public class AssemblyReference : Identity
{
public AssemblyReference(string name)
: base(name)
{
}
}
public class PackageReference : Identity
{
public string Version { get; }
public PackageReference(string name, string version)
: base(name)
{
Version = version;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils
{
public abstract class Identity
{
protected Identity(string name)
{
Name = name;
}
public string Name { get; }
}
public class Project : Identity
{
public Project(string name, string projectExtension = ".csproj", string? relativePath = null)
: base(name)
{
if (string.IsNullOrWhiteSpace(relativePath))
{
RelativePath = Path.Combine(name, name + projectExtension);
}
else
{
RelativePath = relativePath;
}
}
/// <summary>
/// This path is relative to the Solution file. Default value is set to ProjectName\ProjectName.csproj
/// </summary>
public string? RelativePath { get; }
}
public class ProjectReference : Identity
{
public ProjectReference(string name)
: base(name)
{
}
}
public class AssemblyReference : Identity
{
public AssemblyReference(string name)
: base(name)
{
}
}
public class PackageReference : Identity
{
public string Version { get; }
public PackageReference(string name, string version)
: base(name)
{
Version = version;
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Workspaces/Core/Portable/Options/OptionServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Options
{
[ExportWorkspaceServiceFactory(typeof(IOptionService)), Shared]
internal class OptionServiceFactory : IWorkspaceServiceFactory
{
private readonly IGlobalOptionService _globalOptionService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public OptionServiceFactory(IGlobalOptionService globalOptionService)
=> _globalOptionService = globalOptionService;
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new OptionService(_globalOptionService, workspaceServices);
/// <summary>
/// Wraps an underlying <see cref="IGlobalOptionService"/> and exposes its data to workspace
/// clients. Also takes the <see cref="IGlobalOptionService.OptionChanged"/> notifications
/// and forwards them along using the same <see cref="TaskQueue"/> used by the
/// <see cref="Workspace"/> this is connected to. i.e. instead of synchronously just passing
/// along the underlying events, these will be enqueued onto the workspace's eventing queue.
/// </summary>
internal sealed class OptionService : IWorkspaceOptionService
{
private readonly IGlobalOptionService _globalOptionService;
private readonly TaskQueue _taskQueue;
/// <summary>
/// Gate guarding <see cref="_eventHandlers"/> and <see cref="_documentOptionsProviders"/>.
/// </summary>
private readonly object _gate = new();
private ImmutableArray<EventHandler<OptionChangedEventArgs>> _eventHandlers =
ImmutableArray<EventHandler<OptionChangedEventArgs>>.Empty;
private ImmutableArray<IDocumentOptionsProvider> _documentOptionsProviders =
ImmutableArray<IDocumentOptionsProvider>.Empty;
public OptionService(
IGlobalOptionService globalOptionService,
HostWorkspaceServices workspaceServices)
{
_globalOptionService = globalOptionService;
var schedulerProvider = workspaceServices.GetRequiredService<ITaskSchedulerProvider>();
var listenerProvider = workspaceServices.GetRequiredService<IWorkspaceAsynchronousOperationListenerProvider>();
_taskQueue = new TaskQueue(listenerProvider.GetListener(), schedulerProvider.CurrentContextScheduler);
_globalOptionService.OptionChanged += OnGlobalOptionServiceOptionChanged;
}
public void OnWorkspaceDisposed(Workspace workspace)
{
// Disconnect us from the underlying global service. That way it doesn't
// keep us around (and all the event handlers we're holding onto) forever.
_globalOptionService.OptionChanged -= OnGlobalOptionServiceOptionChanged;
}
private void OnGlobalOptionServiceOptionChanged(object? sender, OptionChangedEventArgs e)
{
_taskQueue.ScheduleTask(nameof(OptionService) + "." + nameof(OnGlobalOptionServiceOptionChanged), () =>
{
// Ensure we grab the event handlers inside the scheduled task to prevent a race of people unsubscribing
// but getting the event later on the UI thread
var eventHandlers = GetEventHandlers();
foreach (var handler in eventHandlers)
{
handler(this, e);
}
}, CancellationToken.None);
}
private ImmutableArray<EventHandler<OptionChangedEventArgs>> GetEventHandlers()
{
lock (_gate)
{
return _eventHandlers;
}
}
public event EventHandler<OptionChangedEventArgs> OptionChanged
{
add
{
lock (_gate)
{
_eventHandlers = _eventHandlers.Add(value);
}
}
remove
{
lock (_gate)
{
_eventHandlers = _eventHandlers.Remove(value);
}
}
}
// Simple forwarding functions.
public SerializableOptionSet GetOptions() => GetSerializableOptionsSnapshot(ImmutableHashSet<string>.Empty);
public SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet<string> languages) => _globalOptionService.GetSerializableOptionsSnapshot(languages, this);
public object? GetOption(OptionKey optionKey) => _globalOptionService.GetOption(optionKey);
public T? GetOption<T>(Option<T> option) => _globalOptionService.GetOption(option);
public T? GetOption<T>(Option2<T> option) => _globalOptionService.GetOption(option);
public T? GetOption<T>(PerLanguageOption<T> option, string? languageName) => _globalOptionService.GetOption(option, languageName);
public T? GetOption<T>(PerLanguageOption2<T> option, string? languageName) => _globalOptionService.GetOption(option, languageName);
public IEnumerable<IOption> GetRegisteredOptions() => _globalOptionService.GetRegisteredOptions();
public bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey) => _globalOptionService.TryMapEditorConfigKeyToOption(key, language, out storageLocation, out optionKey);
public ImmutableHashSet<IOption> GetRegisteredSerializableOptions(ImmutableHashSet<string> languages) => _globalOptionService.GetRegisteredSerializableOptions(languages);
public void SetOptions(OptionSet optionSet) => _globalOptionService.SetOptions(optionSet);
public void RegisterWorkspace(Workspace workspace) => _globalOptionService.RegisterWorkspace(workspace);
public void UnregisterWorkspace(Workspace workspace) => _globalOptionService.UnregisterWorkspace(workspace);
public void RegisterDocumentOptionsProvider(IDocumentOptionsProvider documentOptionsProvider)
{
if (documentOptionsProvider == null)
{
throw new ArgumentNullException(nameof(documentOptionsProvider));
}
lock (_gate)
{
_documentOptionsProviders = _documentOptionsProviders.Add(documentOptionsProvider);
}
}
public async Task<OptionSet> GetUpdatedOptionSetForDocumentAsync(Document document, OptionSet optionSet, CancellationToken cancellationToken)
{
ImmutableArray<IDocumentOptionsProvider> documentOptionsProviders;
lock (_gate)
{
documentOptionsProviders = _documentOptionsProviders;
}
var realizedDocumentOptions = new List<IDocumentOptions>();
foreach (var provider in documentOptionsProviders)
{
cancellationToken.ThrowIfCancellationRequested();
var documentOption = await provider.GetOptionsForDocumentAsync(document, cancellationToken).ConfigureAwait(false);
if (documentOption != null)
{
realizedDocumentOptions.Add(documentOption);
}
}
return new DocumentSpecificOptionSet(realizedDocumentOptions, optionSet);
}
private class DocumentSpecificOptionSet : OptionSet
{
private readonly OptionSet _underlyingOptions;
private readonly List<IDocumentOptions> _documentOptions;
private ImmutableDictionary<OptionKey, object?> _values;
public DocumentSpecificOptionSet(List<IDocumentOptions> documentOptions, OptionSet underlyingOptions)
: this(documentOptions, underlyingOptions, ImmutableDictionary<OptionKey, object?>.Empty)
{
}
public DocumentSpecificOptionSet(List<IDocumentOptions> documentOptions, OptionSet underlyingOptions, ImmutableDictionary<OptionKey, object?> values)
{
_documentOptions = documentOptions;
_underlyingOptions = underlyingOptions;
_values = values;
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)]
private protected override object? GetOptionCore(OptionKey optionKey)
{
// If we already know the document specific value, we're done
if (_values.TryGetValue(optionKey, out var value))
{
return value;
}
foreach (var documentOptionSource in _documentOptions)
{
if (documentOptionSource.TryGetDocumentOption(optionKey, out value))
{
// Cache and return
return ImmutableInterlocked.GetOrAdd(ref _values, optionKey, value);
}
}
// We don't have a document specific value, so forward
return _underlyingOptions.GetOption(optionKey);
}
public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value)
=> new DocumentSpecificOptionSet(_documentOptions, _underlyingOptions, _values.SetItem(optionAndLanguage, value));
internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet)
{
// GetChangedOptions only needs to be supported for OptionSets that need to be compared during application,
// but that's already enforced it must be a full SerializableOptionSet.
throw new NotSupportedException();
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Options
{
[ExportWorkspaceServiceFactory(typeof(IOptionService)), Shared]
internal class OptionServiceFactory : IWorkspaceServiceFactory
{
private readonly IGlobalOptionService _globalOptionService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public OptionServiceFactory(IGlobalOptionService globalOptionService)
=> _globalOptionService = globalOptionService;
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new OptionService(_globalOptionService, workspaceServices);
/// <summary>
/// Wraps an underlying <see cref="IGlobalOptionService"/> and exposes its data to workspace
/// clients. Also takes the <see cref="IGlobalOptionService.OptionChanged"/> notifications
/// and forwards them along using the same <see cref="TaskQueue"/> used by the
/// <see cref="Workspace"/> this is connected to. i.e. instead of synchronously just passing
/// along the underlying events, these will be enqueued onto the workspace's eventing queue.
/// </summary>
internal sealed class OptionService : IWorkspaceOptionService
{
private readonly IGlobalOptionService _globalOptionService;
private readonly TaskQueue _taskQueue;
/// <summary>
/// Gate guarding <see cref="_eventHandlers"/> and <see cref="_documentOptionsProviders"/>.
/// </summary>
private readonly object _gate = new();
private ImmutableArray<EventHandler<OptionChangedEventArgs>> _eventHandlers =
ImmutableArray<EventHandler<OptionChangedEventArgs>>.Empty;
private ImmutableArray<IDocumentOptionsProvider> _documentOptionsProviders =
ImmutableArray<IDocumentOptionsProvider>.Empty;
public OptionService(
IGlobalOptionService globalOptionService,
HostWorkspaceServices workspaceServices)
{
_globalOptionService = globalOptionService;
var schedulerProvider = workspaceServices.GetRequiredService<ITaskSchedulerProvider>();
var listenerProvider = workspaceServices.GetRequiredService<IWorkspaceAsynchronousOperationListenerProvider>();
_taskQueue = new TaskQueue(listenerProvider.GetListener(), schedulerProvider.CurrentContextScheduler);
_globalOptionService.OptionChanged += OnGlobalOptionServiceOptionChanged;
}
public void OnWorkspaceDisposed(Workspace workspace)
{
// Disconnect us from the underlying global service. That way it doesn't
// keep us around (and all the event handlers we're holding onto) forever.
_globalOptionService.OptionChanged -= OnGlobalOptionServiceOptionChanged;
}
private void OnGlobalOptionServiceOptionChanged(object? sender, OptionChangedEventArgs e)
{
_taskQueue.ScheduleTask(nameof(OptionService) + "." + nameof(OnGlobalOptionServiceOptionChanged), () =>
{
// Ensure we grab the event handlers inside the scheduled task to prevent a race of people unsubscribing
// but getting the event later on the UI thread
var eventHandlers = GetEventHandlers();
foreach (var handler in eventHandlers)
{
handler(this, e);
}
}, CancellationToken.None);
}
private ImmutableArray<EventHandler<OptionChangedEventArgs>> GetEventHandlers()
{
lock (_gate)
{
return _eventHandlers;
}
}
public event EventHandler<OptionChangedEventArgs> OptionChanged
{
add
{
lock (_gate)
{
_eventHandlers = _eventHandlers.Add(value);
}
}
remove
{
lock (_gate)
{
_eventHandlers = _eventHandlers.Remove(value);
}
}
}
// Simple forwarding functions.
public SerializableOptionSet GetOptions() => GetSerializableOptionsSnapshot(ImmutableHashSet<string>.Empty);
public SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet<string> languages) => _globalOptionService.GetSerializableOptionsSnapshot(languages, this);
public object? GetOption(OptionKey optionKey) => _globalOptionService.GetOption(optionKey);
public T? GetOption<T>(Option<T> option) => _globalOptionService.GetOption(option);
public T? GetOption<T>(Option2<T> option) => _globalOptionService.GetOption(option);
public T? GetOption<T>(PerLanguageOption<T> option, string? languageName) => _globalOptionService.GetOption(option, languageName);
public T? GetOption<T>(PerLanguageOption2<T> option, string? languageName) => _globalOptionService.GetOption(option, languageName);
public IEnumerable<IOption> GetRegisteredOptions() => _globalOptionService.GetRegisteredOptions();
public bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey) => _globalOptionService.TryMapEditorConfigKeyToOption(key, language, out storageLocation, out optionKey);
public ImmutableHashSet<IOption> GetRegisteredSerializableOptions(ImmutableHashSet<string> languages) => _globalOptionService.GetRegisteredSerializableOptions(languages);
public void SetOptions(OptionSet optionSet) => _globalOptionService.SetOptions(optionSet);
public void RegisterWorkspace(Workspace workspace) => _globalOptionService.RegisterWorkspace(workspace);
public void UnregisterWorkspace(Workspace workspace) => _globalOptionService.UnregisterWorkspace(workspace);
public void RegisterDocumentOptionsProvider(IDocumentOptionsProvider documentOptionsProvider)
{
if (documentOptionsProvider == null)
{
throw new ArgumentNullException(nameof(documentOptionsProvider));
}
lock (_gate)
{
_documentOptionsProviders = _documentOptionsProviders.Add(documentOptionsProvider);
}
}
public async Task<OptionSet> GetUpdatedOptionSetForDocumentAsync(Document document, OptionSet optionSet, CancellationToken cancellationToken)
{
ImmutableArray<IDocumentOptionsProvider> documentOptionsProviders;
lock (_gate)
{
documentOptionsProviders = _documentOptionsProviders;
}
var realizedDocumentOptions = new List<IDocumentOptions>();
foreach (var provider in documentOptionsProviders)
{
cancellationToken.ThrowIfCancellationRequested();
var documentOption = await provider.GetOptionsForDocumentAsync(document, cancellationToken).ConfigureAwait(false);
if (documentOption != null)
{
realizedDocumentOptions.Add(documentOption);
}
}
return new DocumentSpecificOptionSet(realizedDocumentOptions, optionSet);
}
private class DocumentSpecificOptionSet : OptionSet
{
private readonly OptionSet _underlyingOptions;
private readonly List<IDocumentOptions> _documentOptions;
private ImmutableDictionary<OptionKey, object?> _values;
public DocumentSpecificOptionSet(List<IDocumentOptions> documentOptions, OptionSet underlyingOptions)
: this(documentOptions, underlyingOptions, ImmutableDictionary<OptionKey, object?>.Empty)
{
}
public DocumentSpecificOptionSet(List<IDocumentOptions> documentOptions, OptionSet underlyingOptions, ImmutableDictionary<OptionKey, object?> values)
{
_documentOptions = documentOptions;
_underlyingOptions = underlyingOptions;
_values = values;
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)]
private protected override object? GetOptionCore(OptionKey optionKey)
{
// If we already know the document specific value, we're done
if (_values.TryGetValue(optionKey, out var value))
{
return value;
}
foreach (var documentOptionSource in _documentOptions)
{
if (documentOptionSource.TryGetDocumentOption(optionKey, out value))
{
// Cache and return
return ImmutableInterlocked.GetOrAdd(ref _values, optionKey, value);
}
}
// We don't have a document specific value, so forward
return _underlyingOptions.GetOption(optionKey);
}
public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value)
=> new DocumentSpecificOptionSet(_documentOptions, _underlyingOptions, _values.SetItem(optionAndLanguage, value));
internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet)
{
// GetChangedOptions only needs to be supported for OptionSets that need to be compared during application,
// but that's already enforced it must be a full SerializableOptionSet.
throw new NotSupportedException();
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/VisualStudio/IntegrationTest/TestUtilities/Input/ButtonBaseExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using Microsoft.VisualStudio.Threading;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input
{
public static class ButtonBaseExtensions
{
private static readonly MethodInfo s_executeCoreMethod;
static ButtonBaseExtensions()
{
var methodInfo = typeof(RoutedCommand).GetMethod("ExecuteCore", BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(object), typeof(IInputElement), typeof(bool) }, null);
s_executeCoreMethod = methodInfo;
//s_executeCore = (Action<RoutedCommand, object, IInputElement, bool>)Delegate.CreateDelegate(typeof(Action<RoutedCommand, object, IInputElement, bool>), firstArgument: null, methodInfo);
}
public static async Task<bool> SimulateClickAsync(this ButtonBase button, JoinableTaskFactory joinableTaskFactory)
{
await joinableTaskFactory.SwitchToMainThreadAsync();
if (!button.IsEnabled || !button.IsVisible)
{
return false;
}
if (button is RadioButton radioButton)
{
ISelectionItemProvider peer = new RadioButtonAutomationPeer(radioButton);
peer.Select();
}
else if (button is Button button2)
{
IInvokeProvider peer = new ButtonAutomationPeer(button2);
peer.Invoke();
}
else
{
button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
ExecuteCommandSource(button, true);
}
// Wait for changes to propagate
await Task.Yield();
return true;
}
private static void ExecuteCommandSource(ICommandSource commandSource, bool userInitiated)
{
var command = commandSource.Command;
if (command is null)
{
return;
}
var commandParameter = commandSource.CommandParameter;
var commandTarget = commandSource.CommandTarget;
if (command is RoutedCommand routedCommand)
{
if (commandTarget is null)
{
commandTarget = commandSource as IInputElement;
}
if (routedCommand.CanExecute(commandParameter, commandTarget))
{
s_executeCoreMethod.Invoke(routedCommand, new[] { commandParameter, commandTarget, userInitiated });
//s_executeCore(routedCommand, commandParameter, commandTarget, userInitiated);
}
}
else if (command.CanExecute(commandParameter))
{
command.Execute(commandParameter);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using Microsoft.VisualStudio.Threading;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input
{
public static class ButtonBaseExtensions
{
private static readonly MethodInfo s_executeCoreMethod;
static ButtonBaseExtensions()
{
var methodInfo = typeof(RoutedCommand).GetMethod("ExecuteCore", BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(object), typeof(IInputElement), typeof(bool) }, null);
s_executeCoreMethod = methodInfo;
//s_executeCore = (Action<RoutedCommand, object, IInputElement, bool>)Delegate.CreateDelegate(typeof(Action<RoutedCommand, object, IInputElement, bool>), firstArgument: null, methodInfo);
}
public static async Task<bool> SimulateClickAsync(this ButtonBase button, JoinableTaskFactory joinableTaskFactory)
{
await joinableTaskFactory.SwitchToMainThreadAsync();
if (!button.IsEnabled || !button.IsVisible)
{
return false;
}
if (button is RadioButton radioButton)
{
ISelectionItemProvider peer = new RadioButtonAutomationPeer(radioButton);
peer.Select();
}
else if (button is Button button2)
{
IInvokeProvider peer = new ButtonAutomationPeer(button2);
peer.Invoke();
}
else
{
button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
ExecuteCommandSource(button, true);
}
// Wait for changes to propagate
await Task.Yield();
return true;
}
private static void ExecuteCommandSource(ICommandSource commandSource, bool userInitiated)
{
var command = commandSource.Command;
if (command is null)
{
return;
}
var commandParameter = commandSource.CommandParameter;
var commandTarget = commandSource.CommandTarget;
if (command is RoutedCommand routedCommand)
{
if (commandTarget is null)
{
commandTarget = commandSource as IInputElement;
}
if (routedCommand.CanExecute(commandParameter, commandTarget))
{
s_executeCoreMethod.Invoke(routedCommand, new[] { commandParameter, commandTarget, userInitiated });
//s_executeCore(routedCommand, commandParameter, commandTarget, userInitiated);
}
}
else if (command.CanExecute(commandParameter))
{
command.Execute(commandParameter);
}
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.ActiveFileState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2
{
internal partial class DiagnosticIncrementalAnalyzer
{
/// <summary>
/// state that is responsible to hold onto local diagnostics data regarding active/opened files (depends on host)
/// in memory.
/// </summary>
private sealed class ActiveFileState
{
// file state this is for
public readonly DocumentId DocumentId;
// analysis data for each kind
private DocumentAnalysisData _syntax = DocumentAnalysisData.Empty;
private DocumentAnalysisData _semantic = DocumentAnalysisData.Empty;
public ActiveFileState(DocumentId documentId)
=> DocumentId = documentId;
public bool IsEmpty => _syntax.Items.IsEmpty && _semantic.Items.IsEmpty;
public void ResetVersion()
{
// reset version of cached data so that we can recalculate new data (ex, OnDocumentReset)
_syntax = new DocumentAnalysisData(VersionStamp.Default, _syntax.Items);
_semantic = new DocumentAnalysisData(VersionStamp.Default, _semantic.Items);
}
public DocumentAnalysisData GetAnalysisData(AnalysisKind kind)
=> kind switch
{
AnalysisKind.Syntax => _syntax,
AnalysisKind.Semantic => _semantic,
_ => throw ExceptionUtilities.UnexpectedValue(kind)
};
public void Save(AnalysisKind kind, DocumentAnalysisData data)
{
Contract.ThrowIfFalse(data.OldItems.IsDefault);
switch (kind)
{
case AnalysisKind.Syntax:
_syntax = data;
return;
case AnalysisKind.Semantic:
_semantic = data;
return;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2
{
internal partial class DiagnosticIncrementalAnalyzer
{
/// <summary>
/// state that is responsible to hold onto local diagnostics data regarding active/opened files (depends on host)
/// in memory.
/// </summary>
private sealed class ActiveFileState
{
// file state this is for
public readonly DocumentId DocumentId;
// analysis data for each kind
private DocumentAnalysisData _syntax = DocumentAnalysisData.Empty;
private DocumentAnalysisData _semantic = DocumentAnalysisData.Empty;
public ActiveFileState(DocumentId documentId)
=> DocumentId = documentId;
public bool IsEmpty => _syntax.Items.IsEmpty && _semantic.Items.IsEmpty;
public void ResetVersion()
{
// reset version of cached data so that we can recalculate new data (ex, OnDocumentReset)
_syntax = new DocumentAnalysisData(VersionStamp.Default, _syntax.Items);
_semantic = new DocumentAnalysisData(VersionStamp.Default, _semantic.Items);
}
public DocumentAnalysisData GetAnalysisData(AnalysisKind kind)
=> kind switch
{
AnalysisKind.Syntax => _syntax,
AnalysisKind.Semantic => _semantic,
_ => throw ExceptionUtilities.UnexpectedValue(kind)
};
public void Save(AnalysisKind kind, DocumentAnalysisData data)
{
Contract.ThrowIfFalse(data.OldItems.IsDefault);
switch (kind)
{
case AnalysisKind.Syntax:
_syntax = data;
return;
case AnalysisKind.Semantic:
_semantic = data;
return;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Compilers/VisualBasic/Portable/Binding/SemanticModelBinder.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Returns True for <see cref="Binder.IsSemanticModelBinder"/>
''' </summary>
Friend Class SemanticModelBinder
Inherits Binder
Private ReadOnly _ignoreAccessibility As Boolean = False
Protected Sub New(containingBinder As Binder, Optional ignoreAccessibility As Boolean = False)
MyBase.New(containingBinder)
_ignoreAccessibility = ignoreAccessibility
End Sub
Public Shared Function Mark(binder As Binder, Optional ignoreAccessibility As Boolean = False) As Binder
Return If(
binder.IsSemanticModelBinder AndAlso binder.IgnoresAccessibility = ignoreAccessibility,
binder,
New SemanticModelBinder(binder, ignoreAccessibility))
End Function
Friend Overrides Function BinderSpecificLookupOptions(ByVal options As LookupOptions) As LookupOptions
If (_ignoreAccessibility) Then
Return MyBase.BinderSpecificLookupOptions(options) Or LookupOptions.IgnoreAccessibility
Else
Return MyBase.BinderSpecificLookupOptions(options)
End If
End Function
Public NotOverridable Overrides ReadOnly Property IsSemanticModelBinder As Boolean
Get
Return True
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Returns True for <see cref="Binder.IsSemanticModelBinder"/>
''' </summary>
Friend Class SemanticModelBinder
Inherits Binder
Private ReadOnly _ignoreAccessibility As Boolean = False
Protected Sub New(containingBinder As Binder, Optional ignoreAccessibility As Boolean = False)
MyBase.New(containingBinder)
_ignoreAccessibility = ignoreAccessibility
End Sub
Public Shared Function Mark(binder As Binder, Optional ignoreAccessibility As Boolean = False) As Binder
Return If(
binder.IsSemanticModelBinder AndAlso binder.IgnoresAccessibility = ignoreAccessibility,
binder,
New SemanticModelBinder(binder, ignoreAccessibility))
End Function
Friend Overrides Function BinderSpecificLookupOptions(ByVal options As LookupOptions) As LookupOptions
If (_ignoreAccessibility) Then
Return MyBase.BinderSpecificLookupOptions(options) Or LookupOptions.IgnoreAccessibility
Else
Return MyBase.BinderSpecificLookupOptions(options)
End If
End Function
Public NotOverridable Overrides ReadOnly Property IsSemanticModelBinder As Boolean
Get
Return True
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Features/Core/Portable/NavigationBar/NavigationBarItems/RoslynNavigationBarItem.GenerateDefaultConstructorItem.cs | // Licensed to the .NET Foundation under one or more 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.NavigationBar
{
internal abstract partial class RoslynNavigationBarItem
{
public class GenerateDefaultConstructor : AbstractGenerateCodeItem
{
public GenerateDefaultConstructor(string text, SymbolKey destinationTypeSymbolKey)
: base(RoslynNavigationBarItemKind.GenerateDefaultConstructor, text, Glyph.MethodPublic, destinationTypeSymbolKey)
{
}
protected internal override SerializableNavigationBarItem Dehydrate()
=> SerializableNavigationBarItem.GenerateDefaultConstructor(Text, DestinationTypeSymbolKey);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.NavigationBar
{
internal abstract partial class RoslynNavigationBarItem
{
public class GenerateDefaultConstructor : AbstractGenerateCodeItem
{
public GenerateDefaultConstructor(string text, SymbolKey destinationTypeSymbolKey)
: base(RoslynNavigationBarItemKind.GenerateDefaultConstructor, text, Glyph.MethodPublic, destinationTypeSymbolKey)
{
}
protected internal override SerializableNavigationBarItem Dehydrate()
=> SerializableNavigationBarItem.GenerateDefaultConstructor(Text, DestinationTypeSymbolKey);
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IOmittedArgumentOperation.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub OmittedArgument_ReferenceConversionInOmittedArgument()
Dim source = <![CDATA[
Imports System.Collections.Generic
Public Class C
Public Sub M1(i As Integer, i2 As Integer)
i = M2(i2,,i2)
End Sub
Public Function M2(i as String, Optional i2 as IEnumerable(Of String) = Nothing, Optional i3 as String = Nothing)
Return i2
End Function
End Class
]]>.Value
Dim compilation = CreateCompilation(source)
Dim syntaxTree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(syntaxTree)
Dim method = syntaxTree.GetRoot().DescendantNodes().OfType(Of MethodBlockSyntax).First()
Dim methodOperation = semanticModel.GetOperation(method)
' When we fetch an omitted argument that involves a conversion, there was a bug that involved
' a synthesized conversion node being introduced without a corresponding BoundNode that got
' incorrectly duplicated. This excercises that code path to ensure that the BoundNode is correctly
' cached in the tree.
Dim operationsToAnalyze = methodOperation.DescendantsAndSelf().ToArray()
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub OmittedArgumentFlow_01()
Dim source = <![CDATA[
Public Class C
Public Sub M1(i As Integer, i2 As Integer)'BIND:"Public Sub M1(i As Integer, i2 As Integer)"
i = M2(i2,,)
End Sub
Public Function M2(i as Integer, optional i2 as Integer = 0)
Return i2
End Function
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30057: Too many arguments to 'Public Function M2(i As Integer, [i2 As Integer = 0]) As Object'.
i = M2(i2,,)
~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M2(i2,,)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M2(i2,,)')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2(i2,,)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'M2(i2,,)')
Children(4):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null) (Syntax: '')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null, IsInvalid) (Syntax: '')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub OmittedArgumentFlow_02()
Dim source = <![CDATA[
Public Class C
Public Sub M1(i As Integer, i2 As Integer, b As Boolean)'BIND:"Public Sub M1(i As Integer, i2 As Integer, b As Boolean)"
i = M2(i2, , If(b,1,2))
End Sub
Public Function M2(i as Integer, optional i2 as Integer = 0)
Return i2
End Function
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30057: Too many arguments to 'Public Function M2(i As Integer, [i2 As Integer = 0]) As Object'.
i = M2(i2, , If(b,1,2))
~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2')
Value:
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M2(i2, , If(b,1,2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M2(i2, , If(b,1,2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2(i2, , If(b,1,2))')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'M2(i2, , If(b,1,2))')
Children(4):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, IsImplicit) (Syntax: 'M2')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null) (Syntax: '')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'If(b,1,2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub OmittedArgumentFlow_03()
Dim source = <![CDATA[
Public Class C
Public Sub M1(i As Integer, j As Integer, x As Object) 'BIND:"Public Sub M1(i As Integer, j As Integer, x As Object)"
x.M(i,, j)
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x.M(i,, j)')
Expression:
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'x.M(i,, j)')
Expression:
IDynamicMemberReferenceOperation (Member Name: "M", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'x.M')
Type Arguments(0)
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x')
Arguments(3):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: System.Object) (Syntax: '')
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
ArgumentNames(0)
ArgumentRefKinds: null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub OmittedArgumentFlow_04()
Dim source = <![CDATA[
Public Class C
Public Sub M1(o As Object, i As Integer, b As Boolean) 'BIND:"Public Sub M1(o As Object, i As Integer, b As Boolean)"
i = o.M2( , If(b, 1, 2))
End Sub
End Class
Public Class D
Public Function M2(Optional i2 As Integer = 0)
Return i2
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o')
Value:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = o.M2( , If(b, 1, 2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = o.M2( , If(b, 1, 2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'o.M2( , If(b, 1, 2))')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'o.M2( , If(b, 1, 2))')
Expression:
IDynamicMemberReferenceOperation (Member Name: "M2", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'o.M2')
Type Arguments(0)
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o')
Arguments(2):
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: System.Object) (Syntax: '')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'If(b, 1, 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningValue)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 1, 2)')
ArgumentNames(0)
ArgumentRefKinds: null
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub OmittedArgument_ReferenceConversionInOmittedArgument()
Dim source = <![CDATA[
Imports System.Collections.Generic
Public Class C
Public Sub M1(i As Integer, i2 As Integer)
i = M2(i2,,i2)
End Sub
Public Function M2(i as String, Optional i2 as IEnumerable(Of String) = Nothing, Optional i3 as String = Nothing)
Return i2
End Function
End Class
]]>.Value
Dim compilation = CreateCompilation(source)
Dim syntaxTree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(syntaxTree)
Dim method = syntaxTree.GetRoot().DescendantNodes().OfType(Of MethodBlockSyntax).First()
Dim methodOperation = semanticModel.GetOperation(method)
' When we fetch an omitted argument that involves a conversion, there was a bug that involved
' a synthesized conversion node being introduced without a corresponding BoundNode that got
' incorrectly duplicated. This excercises that code path to ensure that the BoundNode is correctly
' cached in the tree.
Dim operationsToAnalyze = methodOperation.DescendantsAndSelf().ToArray()
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub OmittedArgumentFlow_01()
Dim source = <![CDATA[
Public Class C
Public Sub M1(i As Integer, i2 As Integer)'BIND:"Public Sub M1(i As Integer, i2 As Integer)"
i = M2(i2,,)
End Sub
Public Function M2(i as Integer, optional i2 as Integer = 0)
Return i2
End Function
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30057: Too many arguments to 'Public Function M2(i As Integer, [i2 As Integer = 0]) As Object'.
i = M2(i2,,)
~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M2(i2,,)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M2(i2,,)')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2(i2,,)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'M2(i2,,)')
Children(4):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null) (Syntax: '')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null, IsInvalid) (Syntax: '')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub OmittedArgumentFlow_02()
Dim source = <![CDATA[
Public Class C
Public Sub M1(i As Integer, i2 As Integer, b As Boolean)'BIND:"Public Sub M1(i As Integer, i2 As Integer, b As Boolean)"
i = M2(i2, , If(b,1,2))
End Sub
Public Function M2(i as Integer, optional i2 as Integer = 0)
Return i2
End Function
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30057: Too many arguments to 'Public Function M2(i As Integer, [i2 As Integer = 0]) As Object'.
i = M2(i2, , If(b,1,2))
~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2')
Value:
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M2(i2, , If(b,1,2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M2(i2, , If(b,1,2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M2(i2, , If(b,1,2))')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'M2(i2, , If(b,1,2))')
Children(4):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, IsImplicit) (Syntax: 'M2')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null) (Syntax: '')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'If(b,1,2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub OmittedArgumentFlow_03()
Dim source = <![CDATA[
Public Class C
Public Sub M1(i As Integer, j As Integer, x As Object) 'BIND:"Public Sub M1(i As Integer, j As Integer, x As Object)"
x.M(i,, j)
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x.M(i,, j)')
Expression:
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'x.M(i,, j)')
Expression:
IDynamicMemberReferenceOperation (Member Name: "M", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'x.M')
Type Arguments(0)
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x')
Arguments(3):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: System.Object) (Syntax: '')
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
ArgumentNames(0)
ArgumentRefKinds: null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub OmittedArgumentFlow_04()
Dim source = <![CDATA[
Public Class C
Public Sub M1(o As Object, i As Integer, b As Boolean) 'BIND:"Public Sub M1(o As Object, i As Integer, b As Boolean)"
i = o.M2( , If(b, 1, 2))
End Sub
End Class
Public Class D
Public Function M2(Optional i2 As Integer = 0)
Return i2
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o')
Value:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = o.M2( , If(b, 1, 2))')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = o.M2( , If(b, 1, 2))')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'o.M2( , If(b, 1, 2))')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'o.M2( , If(b, 1, 2))')
Expression:
IDynamicMemberReferenceOperation (Member Name: "M2", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'o.M2')
Type Arguments(0)
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o')
Arguments(2):
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: System.Object) (Syntax: '')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'If(b, 1, 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningValue)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b, 1, 2)')
ArgumentNames(0)
ArgumentRefKinds: null
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Features/Lsif/GeneratorTest/OutputFormatTests.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 Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests
<UseExportProvider>
Public NotInheritable Class OutputFormatTests
<Fact>
Public Async Function TestLineModeOutput() As Task
Dim stringWriter = New StringWriter()
Dim jsonWriter = New LineModeLsifJsonWriter(stringWriter)
Await TestLsifOutput.GenerateForWorkspaceAsync(
TestWorkspace.CreateWorkspace(
<Workspace>
<Project Language="C#" Name="TestProject" FilePath="Z:\TestProject.csproj">
<Document Name="A.cs" FilePath="Z:\A.cs"/>
</Project>
</Workspace>), jsonWriter)
AssertEx.EqualOrDiff(
"{""hoverProvider"":true,""declarationProvider"":false,""definitionProvider"":true,""referencesProvider"":true,""typeDefinitionProvider"":false,""documentSymbolProvider"":false,""foldingRangeProvider"":true,""diagnosticProvider"":false,""id"":1,""type"":""vertex"",""label"":""capabilities""}
{""kind"":""csharp"",""resource"":""file:///Z:/TestProject.csproj"",""id"":2,""type"":""vertex"",""label"":""project""}
{""kind"":""begin"",""scope"":""project"",""data"":2,""id"":3,""type"":""vertex"",""label"":""$event""}
{""uri"":""file:///Z:/A.cs"",""languageId"":""csharp"",""id"":4,""type"":""vertex"",""label"":""document""}
{""kind"":""begin"",""scope"":""document"",""data"":4,""id"":5,""type"":""vertex"",""label"":""$event""}
{""outV"":4,""inVs"":[],""id"":6,""type"":""edge"",""label"":""contains""}
{""result"":[],""id"":7,""type"":""vertex"",""label"":""foldingRangeResult""}
{""outV"":4,""inVs"":[7],""id"":8,""type"":""edge"",""label"":""textDocument/foldingRange""}
{""kind"":""end"",""scope"":""document"",""data"":4,""id"":9,""type"":""vertex"",""label"":""$event""}
{""outV"":2,""inVs"":[4],""id"":10,""type"":""edge"",""label"":""contains""}
{""kind"":""end"",""scope"":""project"",""data"":2,""id"":11,""type"":""vertex"",""label"":""$event""}
", stringWriter.ToString())
End Function
<Fact>
Public Async Function TestJsonModeOutput() As Task
Dim stringWriter = New StringWriter()
Using jsonWriter = New JsonModeLsifJsonWriter(stringWriter)
Await TestLsifOutput.GenerateForWorkspaceAsync(
TestWorkspace.CreateWorkspace(
<Workspace>
<Project Language="C#" Name="TestProject" FilePath="Z:\TestProject.csproj">
<Document Name="A.cs" FilePath="Z:\A.cs"/>
</Project>
</Workspace>), jsonWriter)
End Using
AssertEx.EqualOrDiff(
"[
{
""hoverProvider"": true,
""declarationProvider"": false,
""definitionProvider"": true,
""referencesProvider"": true,
""typeDefinitionProvider"": false,
""documentSymbolProvider"": false,
""foldingRangeProvider"": true,
""diagnosticProvider"": false,
""id"": 1,
""type"": ""vertex"",
""label"": ""capabilities""
},
{
""kind"": ""csharp"",
""resource"": ""file:///Z:/TestProject.csproj"",
""id"": 2,
""type"": ""vertex"",
""label"": ""project""
},
{
""kind"": ""begin"",
""scope"": ""project"",
""data"": 2,
""id"": 3,
""type"": ""vertex"",
""label"": ""$event""
},
{
""uri"": ""file:///Z:/A.cs"",
""languageId"": ""csharp"",
""id"": 4,
""type"": ""vertex"",
""label"": ""document""
},
{
""kind"": ""begin"",
""scope"": ""document"",
""data"": 4,
""id"": 5,
""type"": ""vertex"",
""label"": ""$event""
},
{
""outV"": 4,
""inVs"": [],
""id"": 6,
""type"": ""edge"",
""label"": ""contains""
},
{
""result"": [],
""id"": 7,
""type"": ""vertex"",
""label"": ""foldingRangeResult""
},
{
""outV"": 4,
""inVs"": [
7
],
""id"": 8,
""type"": ""edge"",
""label"": ""textDocument/foldingRange""
},
{
""kind"": ""end"",
""scope"": ""document"",
""data"": 4,
""id"": 9,
""type"": ""vertex"",
""label"": ""$event""
},
{
""outV"": 2,
""inVs"": [
4
],
""id"": 10,
""type"": ""edge"",
""label"": ""contains""
},
{
""kind"": ""end"",
""scope"": ""project"",
""data"": 2,
""id"": 11,
""type"": ""vertex"",
""label"": ""$event""
}
]", stringWriter.ToString())
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.IO
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests
<UseExportProvider>
Public NotInheritable Class OutputFormatTests
<Fact>
Public Async Function TestLineModeOutput() As Task
Dim stringWriter = New StringWriter()
Dim jsonWriter = New LineModeLsifJsonWriter(stringWriter)
Await TestLsifOutput.GenerateForWorkspaceAsync(
TestWorkspace.CreateWorkspace(
<Workspace>
<Project Language="C#" Name="TestProject" FilePath="Z:\TestProject.csproj">
<Document Name="A.cs" FilePath="Z:\A.cs"/>
</Project>
</Workspace>), jsonWriter)
AssertEx.EqualOrDiff(
"{""hoverProvider"":true,""declarationProvider"":false,""definitionProvider"":true,""referencesProvider"":true,""typeDefinitionProvider"":false,""documentSymbolProvider"":false,""foldingRangeProvider"":true,""diagnosticProvider"":false,""id"":1,""type"":""vertex"",""label"":""capabilities""}
{""kind"":""csharp"",""resource"":""file:///Z:/TestProject.csproj"",""id"":2,""type"":""vertex"",""label"":""project""}
{""kind"":""begin"",""scope"":""project"",""data"":2,""id"":3,""type"":""vertex"",""label"":""$event""}
{""uri"":""file:///Z:/A.cs"",""languageId"":""csharp"",""id"":4,""type"":""vertex"",""label"":""document""}
{""kind"":""begin"",""scope"":""document"",""data"":4,""id"":5,""type"":""vertex"",""label"":""$event""}
{""outV"":4,""inVs"":[],""id"":6,""type"":""edge"",""label"":""contains""}
{""result"":[],""id"":7,""type"":""vertex"",""label"":""foldingRangeResult""}
{""outV"":4,""inVs"":[7],""id"":8,""type"":""edge"",""label"":""textDocument/foldingRange""}
{""kind"":""end"",""scope"":""document"",""data"":4,""id"":9,""type"":""vertex"",""label"":""$event""}
{""outV"":2,""inVs"":[4],""id"":10,""type"":""edge"",""label"":""contains""}
{""kind"":""end"",""scope"":""project"",""data"":2,""id"":11,""type"":""vertex"",""label"":""$event""}
", stringWriter.ToString())
End Function
<Fact>
Public Async Function TestJsonModeOutput() As Task
Dim stringWriter = New StringWriter()
Using jsonWriter = New JsonModeLsifJsonWriter(stringWriter)
Await TestLsifOutput.GenerateForWorkspaceAsync(
TestWorkspace.CreateWorkspace(
<Workspace>
<Project Language="C#" Name="TestProject" FilePath="Z:\TestProject.csproj">
<Document Name="A.cs" FilePath="Z:\A.cs"/>
</Project>
</Workspace>), jsonWriter)
End Using
AssertEx.EqualOrDiff(
"[
{
""hoverProvider"": true,
""declarationProvider"": false,
""definitionProvider"": true,
""referencesProvider"": true,
""typeDefinitionProvider"": false,
""documentSymbolProvider"": false,
""foldingRangeProvider"": true,
""diagnosticProvider"": false,
""id"": 1,
""type"": ""vertex"",
""label"": ""capabilities""
},
{
""kind"": ""csharp"",
""resource"": ""file:///Z:/TestProject.csproj"",
""id"": 2,
""type"": ""vertex"",
""label"": ""project""
},
{
""kind"": ""begin"",
""scope"": ""project"",
""data"": 2,
""id"": 3,
""type"": ""vertex"",
""label"": ""$event""
},
{
""uri"": ""file:///Z:/A.cs"",
""languageId"": ""csharp"",
""id"": 4,
""type"": ""vertex"",
""label"": ""document""
},
{
""kind"": ""begin"",
""scope"": ""document"",
""data"": 4,
""id"": 5,
""type"": ""vertex"",
""label"": ""$event""
},
{
""outV"": 4,
""inVs"": [],
""id"": 6,
""type"": ""edge"",
""label"": ""contains""
},
{
""result"": [],
""id"": 7,
""type"": ""vertex"",
""label"": ""foldingRangeResult""
},
{
""outV"": 4,
""inVs"": [
7
],
""id"": 8,
""type"": ""edge"",
""label"": ""textDocument/foldingRange""
},
{
""kind"": ""end"",
""scope"": ""document"",
""data"": 4,
""id"": 9,
""type"": ""vertex"",
""label"": ""$event""
},
{
""outV"": 2,
""inVs"": [
4
],
""id"": 10,
""type"": ""edge"",
""label"": ""contains""
},
{
""kind"": ""end"",
""scope"": ""project"",
""data"": 2,
""id"": 11,
""type"": ""vertex"",
""label"": ""$event""
}
]", stringWriter.ToString())
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/VisualStudio/Core/Test/Diagnostics/TodoListTableDataSourceTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Common
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.TodoComments
Imports Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
Imports Microsoft.VisualStudio.Shell.TableManager
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Diagnostics
<[UseExportProvider]>
Public Class TodoListTableDataSourceTests
<Fact>
Public Sub TestCreation()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim provider = New TestTodoListProvider()
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Assert.Equal(manager.Identifier, StandardTables.TasksTable)
Assert.Equal(1, manager.Sources.Count())
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
AssertEx.SetEqual(table.Columns, manager.GetColumnsForSources(SpecializedCollections.SingletonEnumerable(source)))
Assert.Equal(ServicesVSResources.CSharp_VB_Todo_List_Table_Data_Source, source.DisplayName)
Assert.Equal(StandardTableDataSources.CommentTableDataSource, source.SourceTypeIdentifier)
Assert.Equal(1, manager.Sinks_TestOnly.Count())
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Assert.Equal(0, sink.Entries.Count())
Assert.Equal(1, source.NumberOfSubscription_TestOnly)
subscription.Dispose()
Assert.Equal(0, source.NumberOfSubscription_TestOnly)
End Using
End Sub
<Fact>
Public Sub TestInitialEntries()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim provider = New TestTodoListProvider(CreateItem(documentId))
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Assert.Equal(1, sink.Entries.Count)
End Using
End Sub
<Fact>
Public Sub TestEntryChanged()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim provider = New TestTodoListProvider()
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
provider.Items = New TodoCommentData() {CreateItem(documentId)}
provider.RaiseTodoListUpdated(workspace)
Assert.Equal(1, sink.Entries.Count)
provider.Items = Array.Empty(Of TodoCommentData)()
provider.RaiseClearTodoListUpdated(workspace, documentId)
Assert.Equal(0, sink.Entries.Count)
End Using
End Sub
<Fact>
Public Sub TestEntry()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
Assert.Equal(1, snapshot.Count)
Dim filename = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
Assert.Equal(item.OriginalFilePath, filename)
Dim text = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Text, text))
Assert.Equal(item.Message, text)
Dim line = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Line, line))
Assert.Equal(item.MappedLine, line)
Dim column = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Column, column))
Assert.Equal(item.MappedColumn, column)
End Using
End Sub
<Fact>
Public Sub TestSnapshotEntry()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim snapshot1 = factory.GetCurrentSnapshot()
factory.OnRefreshed()
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(snapshot1.VersionNumber + 1, snapshot2.VersionNumber)
Assert.Equal(1, snapshot1.Count)
Dim filename = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
Assert.Equal(item.OriginalFilePath, filename)
Dim text = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Text, text))
Assert.Equal(item.Message, text)
Dim line = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Line, line))
Assert.Equal(item.MappedLine, line)
Dim column = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Column, column))
Assert.Equal(item.MappedColumn, column)
End Using
End Sub
<Fact>
Public Sub TestSnapshotTranslateTo()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim snapshot1 = factory.GetCurrentSnapshot()
factory.OnRefreshed()
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(0, snapshot1.IndexOf(0, snapshot2))
End Using
End Sub
<Fact>
Public Sub TestSnapshotTranslateTo2()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim snapshot1 = factory.GetCurrentSnapshot()
provider.Items = New TodoCommentData() {
New TodoCommentData(priority:=1, message:="test2", documentId:=documentId, mappedLine:=11, originalLine:=11, mappedColumn:=21, originalColumn:=21, mappedFilePath:=Nothing, originalFilePath:="test2"),
New TodoCommentData(priority:=0, message:="test", documentId:=documentId, mappedLine:=11, originalLine:=11, mappedColumn:=21, originalColumn:=21, mappedFilePath:=Nothing, originalFilePath:="test1")
}
provider.RaiseTodoListUpdated(workspace)
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(1, snapshot1.IndexOf(0, snapshot2))
End Using
End Sub
<Fact>
Public Sub TestSnapshotTranslateTo3()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim snapshot1 = factory.GetCurrentSnapshot()
provider.Items = New TodoCommentData() {
New TodoCommentData(priority:=1, message:="test2", documentId:=documentId, mappedLine:=11, originalLine:=11, mappedColumn:=21, originalColumn:=21, mappedFilePath:=Nothing, originalFilePath:="test2"),
New TodoCommentData(priority:=0, message:="test3", documentId:=documentId, mappedLine:=11, originalLine:=11, mappedColumn:=21, originalColumn:=21, mappedFilePath:=Nothing, originalFilePath:="test3")
}
provider.RaiseTodoListUpdated(workspace)
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(-1, snapshot1.IndexOf(0, snapshot2))
End Using
End Sub
<Fact>
Public Sub TestInvalidEntry()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
Assert.Equal(1, snapshot.Count)
Dim temp = Nothing
Assert.False(snapshot.TryGetValue(-1, StandardTableKeyNames.DocumentName, temp))
Assert.False(snapshot.TryGetValue(1, StandardTableKeyNames.DocumentName, temp))
Assert.False(snapshot.TryGetValue(0, "Test", temp))
End Using
End Sub
<Fact>
Public Sub TestAggregatedEntries()
Dim markup = <Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="Proj1">
<Document FilePath="test1"><![CDATA[// TODO hello]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="Proj1" LinkFilePath="test1"/>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(markup)
Dim projects = workspace.CurrentSolution.Projects.ToArray()
Dim item1 = CreateItem(projects(0).DocumentIds.First())
Dim item2 = CreateItem(projects(1).DocumentIds.First())
Dim provider = New TestTodoListProvider()
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.Items = New TodoCommentData() {item1, item2}
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
Assert.Equal(1, snapshot.Count)
Dim filename As Object = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
Assert.Equal("test1", filename)
Dim projectname As Object = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.ProjectName, projectname))
Assert.Equal("Proj1, Proj2", projectname)
Dim projectnames As Object = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.ProjectName + "s", projectnames))
Assert.Equal(2, DirectCast(projectnames, String()).Length)
Dim projectguid As Object = Nothing
Assert.False(snapshot.TryGetValue(0, StandardTableKeyNames.ProjectGuid, projectguid))
End Using
End Sub
Private Function CreateItem(documentId As DocumentId) As TodoCommentData
Return New TodoCommentData(
priority:=0,
message:="test",
documentId:=documentId,
mappedLine:=10,
originalLine:=10,
mappedColumn:=20,
originalColumn:=20,
mappedFilePath:=Nothing,
originalFilePath:="test1")
End Function
Private Class TestTodoListProvider
Implements ITodoListProvider
Public Items As TodoCommentData()
Public Sub New(ParamArray items As TodoCommentData())
Me.Items = items
End Sub
Public Event TodoListUpdated As EventHandler(Of TodoItemsUpdatedArgs) Implements ITodoListProvider.TodoListUpdated
Public Function GetTodoItems(workspace As Workspace, documentId As DocumentId, cancellationToken As CancellationToken) As ImmutableArray(Of TodoCommentData) Implements ITodoListProvider.GetTodoItems
Assert.NotNull(workspace)
Assert.NotNull(documentId)
Return Items.Where(Function(t) t.DocumentId Is documentId).ToImmutableArrayOrEmpty()
End Function
Public Sub RaiseTodoListUpdated(workspace As Workspace)
Dim map = Items.ToLookup(Function(t) t.DocumentId)
For Each group In map
RaiseEvent TodoListUpdated(Me, New TodoItemsUpdatedArgs(
Tuple.Create(Me, group.Key), workspace, workspace.CurrentSolution, group.Key.ProjectId, group.Key, group.ToImmutableArrayOrEmpty()))
Next
End Sub
Public Sub RaiseClearTodoListUpdated(workspace As Microsoft.CodeAnalysis.Workspace, documentId As DocumentId)
RaiseEvent TodoListUpdated(Me, New TodoItemsUpdatedArgs(
Tuple.Create(Me, documentId), workspace, workspace.CurrentSolution, documentId.ProjectId, documentId, ImmutableArray(Of TodoCommentData).Empty))
End Sub
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Common
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.TodoComments
Imports Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
Imports Microsoft.VisualStudio.Shell.TableManager
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Diagnostics
<[UseExportProvider]>
Public Class TodoListTableDataSourceTests
<Fact>
Public Sub TestCreation()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim provider = New TestTodoListProvider()
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Assert.Equal(manager.Identifier, StandardTables.TasksTable)
Assert.Equal(1, manager.Sources.Count())
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
AssertEx.SetEqual(table.Columns, manager.GetColumnsForSources(SpecializedCollections.SingletonEnumerable(source)))
Assert.Equal(ServicesVSResources.CSharp_VB_Todo_List_Table_Data_Source, source.DisplayName)
Assert.Equal(StandardTableDataSources.CommentTableDataSource, source.SourceTypeIdentifier)
Assert.Equal(1, manager.Sinks_TestOnly.Count())
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Assert.Equal(0, sink.Entries.Count())
Assert.Equal(1, source.NumberOfSubscription_TestOnly)
subscription.Dispose()
Assert.Equal(0, source.NumberOfSubscription_TestOnly)
End Using
End Sub
<Fact>
Public Sub TestInitialEntries()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim provider = New TestTodoListProvider(CreateItem(documentId))
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Assert.Equal(1, sink.Entries.Count)
End Using
End Sub
<Fact>
Public Sub TestEntryChanged()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim provider = New TestTodoListProvider()
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
provider.Items = New TodoCommentData() {CreateItem(documentId)}
provider.RaiseTodoListUpdated(workspace)
Assert.Equal(1, sink.Entries.Count)
provider.Items = Array.Empty(Of TodoCommentData)()
provider.RaiseClearTodoListUpdated(workspace, documentId)
Assert.Equal(0, sink.Entries.Count)
End Using
End Sub
<Fact>
Public Sub TestEntry()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
Assert.Equal(1, snapshot.Count)
Dim filename = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
Assert.Equal(item.OriginalFilePath, filename)
Dim text = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Text, text))
Assert.Equal(item.Message, text)
Dim line = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Line, line))
Assert.Equal(item.MappedLine, line)
Dim column = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Column, column))
Assert.Equal(item.MappedColumn, column)
End Using
End Sub
<Fact>
Public Sub TestSnapshotEntry()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim snapshot1 = factory.GetCurrentSnapshot()
factory.OnRefreshed()
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(snapshot1.VersionNumber + 1, snapshot2.VersionNumber)
Assert.Equal(1, snapshot1.Count)
Dim filename = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
Assert.Equal(item.OriginalFilePath, filename)
Dim text = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Text, text))
Assert.Equal(item.Message, text)
Dim line = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Line, line))
Assert.Equal(item.MappedLine, line)
Dim column = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Column, column))
Assert.Equal(item.MappedColumn, column)
End Using
End Sub
<Fact>
Public Sub TestSnapshotTranslateTo()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim snapshot1 = factory.GetCurrentSnapshot()
factory.OnRefreshed()
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(0, snapshot1.IndexOf(0, snapshot2))
End Using
End Sub
<Fact>
Public Sub TestSnapshotTranslateTo2()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim snapshot1 = factory.GetCurrentSnapshot()
provider.Items = New TodoCommentData() {
New TodoCommentData(priority:=1, message:="test2", documentId:=documentId, mappedLine:=11, originalLine:=11, mappedColumn:=21, originalColumn:=21, mappedFilePath:=Nothing, originalFilePath:="test2"),
New TodoCommentData(priority:=0, message:="test", documentId:=documentId, mappedLine:=11, originalLine:=11, mappedColumn:=21, originalColumn:=21, mappedFilePath:=Nothing, originalFilePath:="test1")
}
provider.RaiseTodoListUpdated(workspace)
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(1, snapshot1.IndexOf(0, snapshot2))
End Using
End Sub
<Fact>
Public Sub TestSnapshotTranslateTo3()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim snapshot1 = factory.GetCurrentSnapshot()
provider.Items = New TodoCommentData() {
New TodoCommentData(priority:=1, message:="test2", documentId:=documentId, mappedLine:=11, originalLine:=11, mappedColumn:=21, originalColumn:=21, mappedFilePath:=Nothing, originalFilePath:="test2"),
New TodoCommentData(priority:=0, message:="test3", documentId:=documentId, mappedLine:=11, originalLine:=11, mappedColumn:=21, originalColumn:=21, mappedFilePath:=Nothing, originalFilePath:="test3")
}
provider.RaiseTodoListUpdated(workspace)
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(-1, snapshot1.IndexOf(0, snapshot2))
End Using
End Sub
<Fact>
Public Sub TestInvalidEntry()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
Assert.Equal(1, snapshot.Count)
Dim temp = Nothing
Assert.False(snapshot.TryGetValue(-1, StandardTableKeyNames.DocumentName, temp))
Assert.False(snapshot.TryGetValue(1, StandardTableKeyNames.DocumentName, temp))
Assert.False(snapshot.TryGetValue(0, "Test", temp))
End Using
End Sub
<Fact>
Public Sub TestAggregatedEntries()
Dim markup = <Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="Proj1">
<Document FilePath="test1"><![CDATA[// TODO hello]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="Proj1" LinkFilePath="test1"/>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(markup)
Dim projects = workspace.CurrentSolution.Projects.ToArray()
Dim item1 = CreateItem(projects(0).DocumentIds.First())
Dim item2 = CreateItem(projects(1).DocumentIds.First())
Dim provider = New TestTodoListProvider()
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTableWorkspaceEventListener.VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.Items = New TodoCommentData() {item1, item2}
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoTableItem, TodoItemsUpdatedArgs))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
Assert.Equal(1, snapshot.Count)
Dim filename As Object = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
Assert.Equal("test1", filename)
Dim projectname As Object = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.ProjectName, projectname))
Assert.Equal("Proj1, Proj2", projectname)
Dim projectnames As Object = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.ProjectName + "s", projectnames))
Assert.Equal(2, DirectCast(projectnames, String()).Length)
Dim projectguid As Object = Nothing
Assert.False(snapshot.TryGetValue(0, StandardTableKeyNames.ProjectGuid, projectguid))
End Using
End Sub
Private Function CreateItem(documentId As DocumentId) As TodoCommentData
Return New TodoCommentData(
priority:=0,
message:="test",
documentId:=documentId,
mappedLine:=10,
originalLine:=10,
mappedColumn:=20,
originalColumn:=20,
mappedFilePath:=Nothing,
originalFilePath:="test1")
End Function
Private Class TestTodoListProvider
Implements ITodoListProvider
Public Items As TodoCommentData()
Public Sub New(ParamArray items As TodoCommentData())
Me.Items = items
End Sub
Public Event TodoListUpdated As EventHandler(Of TodoItemsUpdatedArgs) Implements ITodoListProvider.TodoListUpdated
Public Function GetTodoItems(workspace As Workspace, documentId As DocumentId, cancellationToken As CancellationToken) As ImmutableArray(Of TodoCommentData) Implements ITodoListProvider.GetTodoItems
Assert.NotNull(workspace)
Assert.NotNull(documentId)
Return Items.Where(Function(t) t.DocumentId Is documentId).ToImmutableArrayOrEmpty()
End Function
Public Sub RaiseTodoListUpdated(workspace As Workspace)
Dim map = Items.ToLookup(Function(t) t.DocumentId)
For Each group In map
RaiseEvent TodoListUpdated(Me, New TodoItemsUpdatedArgs(
Tuple.Create(Me, group.Key), workspace, workspace.CurrentSolution, group.Key.ProjectId, group.Key, group.ToImmutableArrayOrEmpty()))
Next
End Sub
Public Sub RaiseClearTodoListUpdated(workspace As Microsoft.CodeAnalysis.Workspace, documentId As DocumentId)
RaiseEvent TodoListUpdated(Me, New TodoItemsUpdatedArgs(
Tuple.Create(Me, documentId), workspace, workspace.CurrentSolution, documentId.ProjectId, documentId, ImmutableArray(Of TodoCommentData).Empty))
End Sub
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Features/CSharp/Portable/SignatureHelp/GenericNameSignatureHelpProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp
{
[ExportSignatureHelpProvider("GenericNameSignatureHelpProvider", LanguageNames.CSharp), Shared]
internal partial class GenericNameSignatureHelpProvider : AbstractCSharpSignatureHelpProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GenericNameSignatureHelpProvider()
{
}
public override bool IsTriggerCharacter(char ch)
=> ch == '<' || ch == ',';
public override bool IsRetriggerCharacter(char ch)
=> ch == '>';
protected virtual bool TryGetGenericIdentifier(
SyntaxNode root, int position,
ISyntaxFactsService syntaxFacts,
SignatureHelpTriggerReason triggerReason,
CancellationToken cancellationToken,
out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken)
{
if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out GenericNameSyntax name))
{
genericIdentifier = name.Identifier;
lessThanToken = name.TypeArgumentList.LessThanToken;
return true;
}
genericIdentifier = default;
lessThanToken = default;
return false;
}
private bool IsTriggerToken(SyntaxToken token)
{
return !token.IsKind(SyntaxKind.None) &&
token.ValueText.Length == 1 &&
IsTriggerCharacter(token.ValueText[0]) &&
token.Parent is TypeArgumentListSyntax &&
token.Parent.Parent is GenericNameSyntax;
}
private bool IsArgumentListToken(GenericNameSyntax node, SyntaxToken token)
{
return node.TypeArgumentList != null &&
node.TypeArgumentList.Span.Contains(token.SpanStart) &&
token != node.TypeArgumentList.GreaterThanToken;
}
protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (!TryGetGenericIdentifier(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken,
out var genericIdentifier, out var lessThanToken))
{
return null;
}
if (!(genericIdentifier.Parent is SimpleNameSyntax simpleName))
{
return null;
}
var beforeDotExpression = simpleName.IsRightSideOfDot() ? simpleName.GetLeftSideOfDot() : null;
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(simpleName, cancellationToken).ConfigureAwait(false);
var leftSymbol = beforeDotExpression == null
? null
: semanticModel.GetSymbolInfo(beforeDotExpression, cancellationToken).GetAnySymbol() as INamespaceOrTypeSymbol;
var leftType = beforeDotExpression == null
? null
: semanticModel.GetTypeInfo(beforeDotExpression, cancellationToken).Type as INamespaceOrTypeSymbol;
var leftContainer = leftSymbol ?? leftType;
var isBaseAccess = beforeDotExpression is BaseExpressionSyntax;
var namespacesOrTypesOnly = SyntaxFacts.IsInNamespaceOrTypeContext(simpleName);
var includeExtensions = leftSymbol == null && leftType != null;
var name = genericIdentifier.ValueText;
var symbols = isBaseAccess
? semanticModel.LookupBaseMembers(position, name)
: namespacesOrTypesOnly
? semanticModel.LookupNamespacesAndTypes(position, leftContainer, name)
: semanticModel.LookupSymbols(position, leftContainer, name, includeExtensions);
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
if (within == null)
{
return null;
}
var accessibleSymbols =
symbols.WhereAsArray(s => s.GetArity() > 0)
.WhereAsArray(s => s is INamedTypeSymbol || s is IMethodSymbol)
.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)
.Sort(semanticModel, genericIdentifier.SpanStart);
if (!accessibleSymbols.Any())
{
return null;
}
var anonymousTypeDisplayService = document.GetRequiredLanguageService<IAnonymousTypeDisplayService>();
var documentationCommentFormattingService = document.GetRequiredLanguageService<IDocumentationCommentFormattingService>();
var textSpan = GetTextSpan(genericIdentifier, lessThanToken);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
return CreateSignatureHelpItems(accessibleSymbols.Select(s =>
Convert(s, lessThanToken, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService)).ToList(),
textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem: null);
}
public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken)
{
if (!TryGetGenericIdentifier(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken,
out var genericIdentifier, out _))
{
return null;
}
if (genericIdentifier.TryParseGenericName(cancellationToken, out var genericName))
{
// Because we synthesized the generic name, it will have an index starting at 0
// instead of at the actual position it's at in the text. Because of this, we need to
// offset the position we are checking accordingly.
var offset = genericIdentifier.SpanStart - genericName.SpanStart;
position -= offset;
return SignatureHelpUtilities.GetSignatureHelpState(genericName.TypeArgumentList, position);
}
return null;
}
protected virtual TextSpan GetTextSpan(SyntaxToken genericIdentifier, SyntaxToken lessThanToken)
{
Contract.ThrowIfFalse(lessThanToken.Parent is TypeArgumentListSyntax && lessThanToken.Parent.Parent is GenericNameSyntax);
return SignatureHelpUtilities.GetSignatureHelpSpan(((GenericNameSyntax)lessThanToken.Parent.Parent).TypeArgumentList);
}
private static SignatureHelpItem Convert(
ISymbol symbol,
SyntaxToken lessThanToken,
SemanticModel semanticModel,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
IDocumentationCommentFormattingService documentationCommentFormattingService)
{
var position = lessThanToken.SpanStart;
SignatureHelpItem item;
if (symbol is INamedTypeSymbol namedType)
{
item = CreateItem(
symbol, semanticModel, position,
anonymousTypeDisplayService,
false,
symbol.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService),
GetPreambleParts(namedType, semanticModel, position),
GetSeparatorParts(),
GetPostambleParts(),
namedType.TypeParameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList());
}
else
{
var method = (IMethodSymbol)symbol;
item = CreateItem(
symbol, semanticModel, position,
anonymousTypeDisplayService,
false,
c => symbol.GetDocumentationParts(semanticModel, position, documentationCommentFormattingService, c),
GetPreambleParts(method, semanticModel, position),
GetSeparatorParts(),
GetPostambleParts(method, semanticModel, position),
method.TypeParameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList());
}
return item;
}
private static readonly SymbolDisplayFormat s_minimallyQualifiedFormat =
SymbolDisplayFormat.MinimallyQualifiedFormat.WithGenericsOptions(
SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeVariance);
private static SignatureHelpSymbolParameter Convert(
ITypeParameterSymbol parameter,
SemanticModel semanticModel,
int position,
IDocumentationCommentFormattingService formatter)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
isOptional: false,
documentationFactory: parameter.GetDocumentationPartsFactory(semanticModel, position, formatter),
displayParts: parameter.ToMinimalDisplayParts(semanticModel, position, s_minimallyQualifiedFormat),
selectedDisplayParts: GetSelectedDisplayParts(parameter, semanticModel, position));
}
private static IList<SymbolDisplayPart> GetSelectedDisplayParts(
ITypeParameterSymbol typeParam,
SemanticModel semanticModel,
int position)
{
var parts = new List<SymbolDisplayPart>();
if (TypeParameterHasConstraints(typeParam))
{
parts.Add(Space());
parts.Add(Keyword(SyntaxKind.WhereKeyword));
parts.Add(Space());
parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.TypeParameterName, typeParam, typeParam.Name));
parts.Add(Space());
parts.Add(Punctuation(SyntaxKind.ColonToken));
parts.Add(Space());
var needComma = false;
// class/struct constraint must be first
if (typeParam.HasReferenceTypeConstraint)
{
parts.Add(Keyword(SyntaxKind.ClassKeyword));
needComma = true;
}
else if (typeParam.HasUnmanagedTypeConstraint)
{
parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "unmanaged"));
needComma = true;
}
else if (typeParam.HasValueTypeConstraint)
{
parts.Add(Keyword(SyntaxKind.StructKeyword));
needComma = true;
}
foreach (var baseType in typeParam.ConstraintTypes)
{
if (needComma)
{
parts.Add(Punctuation(SyntaxKind.CommaToken));
parts.Add(Space());
}
parts.AddRange(baseType.ToMinimalDisplayParts(semanticModel, position));
needComma = true;
}
// ctor constraint must be last
if (typeParam.HasConstructorConstraint)
{
if (needComma)
{
parts.Add(Punctuation(SyntaxKind.CommaToken));
parts.Add(Space());
}
parts.Add(Keyword(SyntaxKind.NewKeyword));
parts.Add(Punctuation(SyntaxKind.OpenParenToken));
parts.Add(Punctuation(SyntaxKind.CloseParenToken));
}
}
return parts;
}
private static bool TypeParameterHasConstraints(ITypeParameterSymbol typeParam)
{
return !typeParam.ConstraintTypes.IsDefaultOrEmpty || typeParam.HasConstructorConstraint ||
typeParam.HasReferenceTypeConstraint || typeParam.HasValueTypeConstraint;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp
{
[ExportSignatureHelpProvider("GenericNameSignatureHelpProvider", LanguageNames.CSharp), Shared]
internal partial class GenericNameSignatureHelpProvider : AbstractCSharpSignatureHelpProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GenericNameSignatureHelpProvider()
{
}
public override bool IsTriggerCharacter(char ch)
=> ch == '<' || ch == ',';
public override bool IsRetriggerCharacter(char ch)
=> ch == '>';
protected virtual bool TryGetGenericIdentifier(
SyntaxNode root, int position,
ISyntaxFactsService syntaxFacts,
SignatureHelpTriggerReason triggerReason,
CancellationToken cancellationToken,
out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken)
{
if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out GenericNameSyntax name))
{
genericIdentifier = name.Identifier;
lessThanToken = name.TypeArgumentList.LessThanToken;
return true;
}
genericIdentifier = default;
lessThanToken = default;
return false;
}
private bool IsTriggerToken(SyntaxToken token)
{
return !token.IsKind(SyntaxKind.None) &&
token.ValueText.Length == 1 &&
IsTriggerCharacter(token.ValueText[0]) &&
token.Parent is TypeArgumentListSyntax &&
token.Parent.Parent is GenericNameSyntax;
}
private bool IsArgumentListToken(GenericNameSyntax node, SyntaxToken token)
{
return node.TypeArgumentList != null &&
node.TypeArgumentList.Span.Contains(token.SpanStart) &&
token != node.TypeArgumentList.GreaterThanToken;
}
protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (!TryGetGenericIdentifier(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken,
out var genericIdentifier, out var lessThanToken))
{
return null;
}
if (!(genericIdentifier.Parent is SimpleNameSyntax simpleName))
{
return null;
}
var beforeDotExpression = simpleName.IsRightSideOfDot() ? simpleName.GetLeftSideOfDot() : null;
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(simpleName, cancellationToken).ConfigureAwait(false);
var leftSymbol = beforeDotExpression == null
? null
: semanticModel.GetSymbolInfo(beforeDotExpression, cancellationToken).GetAnySymbol() as INamespaceOrTypeSymbol;
var leftType = beforeDotExpression == null
? null
: semanticModel.GetTypeInfo(beforeDotExpression, cancellationToken).Type as INamespaceOrTypeSymbol;
var leftContainer = leftSymbol ?? leftType;
var isBaseAccess = beforeDotExpression is BaseExpressionSyntax;
var namespacesOrTypesOnly = SyntaxFacts.IsInNamespaceOrTypeContext(simpleName);
var includeExtensions = leftSymbol == null && leftType != null;
var name = genericIdentifier.ValueText;
var symbols = isBaseAccess
? semanticModel.LookupBaseMembers(position, name)
: namespacesOrTypesOnly
? semanticModel.LookupNamespacesAndTypes(position, leftContainer, name)
: semanticModel.LookupSymbols(position, leftContainer, name, includeExtensions);
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
if (within == null)
{
return null;
}
var accessibleSymbols =
symbols.WhereAsArray(s => s.GetArity() > 0)
.WhereAsArray(s => s is INamedTypeSymbol || s is IMethodSymbol)
.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)
.Sort(semanticModel, genericIdentifier.SpanStart);
if (!accessibleSymbols.Any())
{
return null;
}
var anonymousTypeDisplayService = document.GetRequiredLanguageService<IAnonymousTypeDisplayService>();
var documentationCommentFormattingService = document.GetRequiredLanguageService<IDocumentationCommentFormattingService>();
var textSpan = GetTextSpan(genericIdentifier, lessThanToken);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
return CreateSignatureHelpItems(accessibleSymbols.Select(s =>
Convert(s, lessThanToken, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService)).ToList(),
textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem: null);
}
public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken)
{
if (!TryGetGenericIdentifier(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken,
out var genericIdentifier, out _))
{
return null;
}
if (genericIdentifier.TryParseGenericName(cancellationToken, out var genericName))
{
// Because we synthesized the generic name, it will have an index starting at 0
// instead of at the actual position it's at in the text. Because of this, we need to
// offset the position we are checking accordingly.
var offset = genericIdentifier.SpanStart - genericName.SpanStart;
position -= offset;
return SignatureHelpUtilities.GetSignatureHelpState(genericName.TypeArgumentList, position);
}
return null;
}
protected virtual TextSpan GetTextSpan(SyntaxToken genericIdentifier, SyntaxToken lessThanToken)
{
Contract.ThrowIfFalse(lessThanToken.Parent is TypeArgumentListSyntax && lessThanToken.Parent.Parent is GenericNameSyntax);
return SignatureHelpUtilities.GetSignatureHelpSpan(((GenericNameSyntax)lessThanToken.Parent.Parent).TypeArgumentList);
}
private static SignatureHelpItem Convert(
ISymbol symbol,
SyntaxToken lessThanToken,
SemanticModel semanticModel,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
IDocumentationCommentFormattingService documentationCommentFormattingService)
{
var position = lessThanToken.SpanStart;
SignatureHelpItem item;
if (symbol is INamedTypeSymbol namedType)
{
item = CreateItem(
symbol, semanticModel, position,
anonymousTypeDisplayService,
false,
symbol.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService),
GetPreambleParts(namedType, semanticModel, position),
GetSeparatorParts(),
GetPostambleParts(),
namedType.TypeParameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList());
}
else
{
var method = (IMethodSymbol)symbol;
item = CreateItem(
symbol, semanticModel, position,
anonymousTypeDisplayService,
false,
c => symbol.GetDocumentationParts(semanticModel, position, documentationCommentFormattingService, c),
GetPreambleParts(method, semanticModel, position),
GetSeparatorParts(),
GetPostambleParts(method, semanticModel, position),
method.TypeParameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList());
}
return item;
}
private static readonly SymbolDisplayFormat s_minimallyQualifiedFormat =
SymbolDisplayFormat.MinimallyQualifiedFormat.WithGenericsOptions(
SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeVariance);
private static SignatureHelpSymbolParameter Convert(
ITypeParameterSymbol parameter,
SemanticModel semanticModel,
int position,
IDocumentationCommentFormattingService formatter)
{
return new SignatureHelpSymbolParameter(
parameter.Name,
isOptional: false,
documentationFactory: parameter.GetDocumentationPartsFactory(semanticModel, position, formatter),
displayParts: parameter.ToMinimalDisplayParts(semanticModel, position, s_minimallyQualifiedFormat),
selectedDisplayParts: GetSelectedDisplayParts(parameter, semanticModel, position));
}
private static IList<SymbolDisplayPart> GetSelectedDisplayParts(
ITypeParameterSymbol typeParam,
SemanticModel semanticModel,
int position)
{
var parts = new List<SymbolDisplayPart>();
if (TypeParameterHasConstraints(typeParam))
{
parts.Add(Space());
parts.Add(Keyword(SyntaxKind.WhereKeyword));
parts.Add(Space());
parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.TypeParameterName, typeParam, typeParam.Name));
parts.Add(Space());
parts.Add(Punctuation(SyntaxKind.ColonToken));
parts.Add(Space());
var needComma = false;
// class/struct constraint must be first
if (typeParam.HasReferenceTypeConstraint)
{
parts.Add(Keyword(SyntaxKind.ClassKeyword));
needComma = true;
}
else if (typeParam.HasUnmanagedTypeConstraint)
{
parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "unmanaged"));
needComma = true;
}
else if (typeParam.HasValueTypeConstraint)
{
parts.Add(Keyword(SyntaxKind.StructKeyword));
needComma = true;
}
foreach (var baseType in typeParam.ConstraintTypes)
{
if (needComma)
{
parts.Add(Punctuation(SyntaxKind.CommaToken));
parts.Add(Space());
}
parts.AddRange(baseType.ToMinimalDisplayParts(semanticModel, position));
needComma = true;
}
// ctor constraint must be last
if (typeParam.HasConstructorConstraint)
{
if (needComma)
{
parts.Add(Punctuation(SyntaxKind.CommaToken));
parts.Add(Space());
}
parts.Add(Keyword(SyntaxKind.NewKeyword));
parts.Add(Punctuation(SyntaxKind.OpenParenToken));
parts.Add(Punctuation(SyntaxKind.CloseParenToken));
}
}
return parts;
}
private static bool TypeParameterHasConstraints(ITypeParameterSymbol typeParam)
{
return !typeParam.ConstraintTypes.IsDefaultOrEmpty || typeParam.HasConstructorConstraint ||
typeParam.HasReferenceTypeConstraint || typeParam.HasValueTypeConstraint;
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.SingleStatementCodeGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private partial class CSharpCodeGenerator
{
public class SingleStatementCodeGenerator : CSharpCodeGenerator
{
public SingleStatementCodeGenerator(
InsertionPoint insertionPoint,
SelectionResult selectionResult,
AnalyzerResult analyzerResult,
OptionSet options,
bool localFunction)
: base(insertionPoint, selectionResult, analyzerResult, options, localFunction)
{
}
public static bool IsExtractMethodOnSingleStatement(SelectionResult code)
{
var result = (CSharpSelectionResult)code;
var firstStatement = result.GetFirstStatement();
var lastStatement = result.GetLastStatement();
return firstStatement == lastStatement || firstStatement.Span.Contains(lastStatement.Span);
}
protected override SyntaxToken CreateMethodName() => GenerateMethodNameForStatementGenerators();
protected override ImmutableArray<StatementSyntax> GetInitialStatementsForMethodDefinitions()
{
Contract.ThrowIfFalse(IsExtractMethodOnSingleStatement(CSharpSelectionResult));
return ImmutableArray.Create(CSharpSelectionResult.GetFirstStatement());
}
protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken)
{
var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken);
if (callSiteContainer != null)
{
return callSiteContainer;
}
else
{
var firstStatement = CSharpSelectionResult.GetFirstStatement();
return firstStatement.Parent;
}
}
protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite()
=> CSharpSelectionResult.GetFirstStatement();
protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite()
{
// it is a single statement case. either first statement is same as last statement or
// last statement belongs (embedded statement) to the first statement.
return CSharpSelectionResult.GetFirstStatement();
}
protected override Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken)
{
var statement = GetStatementContainingInvocationToExtractedMethodWorker();
return Task.FromResult<SyntaxNode>(statement.WithAdditionalAnnotations(CallSiteAnnotation));
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private partial class CSharpCodeGenerator
{
public class SingleStatementCodeGenerator : CSharpCodeGenerator
{
public SingleStatementCodeGenerator(
InsertionPoint insertionPoint,
SelectionResult selectionResult,
AnalyzerResult analyzerResult,
OptionSet options,
bool localFunction)
: base(insertionPoint, selectionResult, analyzerResult, options, localFunction)
{
}
public static bool IsExtractMethodOnSingleStatement(SelectionResult code)
{
var result = (CSharpSelectionResult)code;
var firstStatement = result.GetFirstStatement();
var lastStatement = result.GetLastStatement();
return firstStatement == lastStatement || firstStatement.Span.Contains(lastStatement.Span);
}
protected override SyntaxToken CreateMethodName() => GenerateMethodNameForStatementGenerators();
protected override ImmutableArray<StatementSyntax> GetInitialStatementsForMethodDefinitions()
{
Contract.ThrowIfFalse(IsExtractMethodOnSingleStatement(CSharpSelectionResult));
return ImmutableArray.Create(CSharpSelectionResult.GetFirstStatement());
}
protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken)
{
var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken);
if (callSiteContainer != null)
{
return callSiteContainer;
}
else
{
var firstStatement = CSharpSelectionResult.GetFirstStatement();
return firstStatement.Parent;
}
}
protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite()
=> CSharpSelectionResult.GetFirstStatement();
protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite()
{
// it is a single statement case. either first statement is same as last statement or
// last statement belongs (embedded statement) to the first statement.
return CSharpSelectionResult.GetFirstStatement();
}
protected override Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken)
{
var statement = GetStatementContainingInvocationToExtractedMethodWorker();
return Task.FromResult<SyntaxNode>(statement.WithAdditionalAnnotations(CallSiteAnnotation));
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/EditorFeatures/Core/Implementation/Formatting/FormatCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Formatting
{
[Export]
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(PredefinedCommandHandlerNames.FormatDocument)]
[Order(After = PredefinedCommandHandlerNames.Rename)]
[Order(Before = PredefinedCompletionNames.CompletionCommandHandler)]
internal partial class FormatCommandHandler :
ICommandHandler<FormatDocumentCommandArgs>,
ICommandHandler<FormatSelectionCommandArgs>,
IChainedCommandHandler<PasteCommandArgs>,
IChainedCommandHandler<TypeCharCommandArgs>,
IChainedCommandHandler<ReturnKeyCommandArgs>
{
private readonly ITextUndoHistoryRegistry _undoHistoryRegistry;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
public string DisplayName => EditorFeaturesResources.Automatic_Formatting;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FormatCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
_undoHistoryRegistry = undoHistoryRegistry;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
private void Format(ITextView textView, Document document, TextSpan? selectionOpt, CancellationToken cancellationToken)
{
var formattingService = document.GetRequiredLanguageService<IFormattingInteractionService>();
using (Logger.LogBlock(FunctionId.CommandHandler_FormatCommand, KeyValueLogMessage.Create(LogType.UserAction, m => m["Span"] = selectionOpt?.Length ?? -1), cancellationToken))
using (var transaction = CreateEditTransaction(textView, EditorFeaturesResources.Formatting))
{
var changes = formattingService.GetFormattingChangesAsync(
document, selectionOpt, documentOptions: null, cancellationToken).WaitAndGetResult(cancellationToken);
if (changes.IsEmpty)
{
return;
}
ApplyChanges(document, changes, selectionOpt, cancellationToken);
transaction.Complete();
}
}
private static void ApplyChanges(Document document, IList<TextChange> changes, TextSpan? selectionOpt, CancellationToken cancellationToken)
{
if (selectionOpt.HasValue)
{
var ruleFactory = document.Project.Solution.Workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
changes = ruleFactory.FilterFormattedChanges(document, selectionOpt.Value, changes).ToList();
if (changes.Count == 0)
{
return;
}
}
using (Logger.LogBlock(FunctionId.Formatting_ApplyResultToBuffer, cancellationToken))
{
document.Project.Solution.Workspace.ApplyTextChanges(document.Id, changes, cancellationToken);
}
}
private static bool CanExecuteCommand(ITextBuffer buffer)
=> buffer.CanApplyChangeDocumentToWorkspace();
private static CommandState GetCommandState(ITextBuffer buffer)
=> CanExecuteCommand(buffer) ? CommandState.Available : CommandState.Unspecified;
public void ExecuteReturnOrTypeCommand(EditorCommandArgs args, Action nextHandler, CancellationToken cancellationToken)
{
// run next handler first so that editor has chance to put the return into the buffer first.
nextHandler();
if (cancellationToken.IsCancellationRequested)
{
return;
}
try
{
ExecuteReturnOrTypeCommandWorker(args, cancellationToken);
}
catch (OperationCanceledException)
{
// According to Editor command handler API guidelines, it's best if we return early if cancellation
// is requested instead of throwing. Otherwise, we could end up in an invalid state due to already
// calling nextHandler().
}
}
private void ExecuteReturnOrTypeCommandWorker(EditorCommandArgs args, CancellationToken cancellationToken)
{
var textView = args.TextView;
var subjectBuffer = args.SubjectBuffer;
if (!CanExecuteCommand(subjectBuffer))
{
return;
}
var caretPosition = textView.GetCaretPoint(args.SubjectBuffer);
if (!caretPosition.HasValue)
{
return;
}
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
var service = document.GetLanguageService<IFormattingInteractionService>();
if (service == null)
{
return;
}
IList<TextChange>? textChanges;
// save current caret position
if (args is ReturnKeyCommandArgs)
{
if (!service.SupportsFormatOnReturn)
{
return;
}
textChanges = service.GetFormattingChangesOnReturnAsync(
document, caretPosition.Value, documentOptions: null, cancellationToken).WaitAndGetResult(cancellationToken);
}
else if (args is TypeCharCommandArgs typeCharArgs)
{
if (!service.SupportsFormattingOnTypedCharacter(document, typeCharArgs.TypedChar))
{
return;
}
textChanges = service.GetFormattingChangesAsync(
document, typeCharArgs.TypedChar, caretPosition.Value, documentOptions: null, cancellationToken).WaitAndGetResult(cancellationToken);
}
else
{
throw ExceptionUtilities.UnexpectedValue(args);
}
if (textChanges == null || textChanges.Count == 0)
{
return;
}
using (var transaction = CreateEditTransaction(textView, EditorFeaturesResources.Automatic_Formatting))
{
transaction.MergePolicy = AutomaticCodeChangeMergePolicy.Instance;
document.Project.Solution.Workspace.ApplyTextChanges(document.Id, textChanges, cancellationToken);
transaction.Complete();
}
// get new caret position after formatting
var newCaretPositionMarker = args.TextView.GetCaretPoint(args.SubjectBuffer);
if (!newCaretPositionMarker.HasValue)
{
return;
}
var snapshotAfterFormatting = args.SubjectBuffer.CurrentSnapshot;
var oldCaretPosition = caretPosition.Value.TranslateTo(snapshotAfterFormatting, PointTrackingMode.Negative);
var newCaretPosition = newCaretPositionMarker.Value.TranslateTo(snapshotAfterFormatting, PointTrackingMode.Negative);
if (oldCaretPosition.Position == newCaretPosition.Position)
{
return;
}
// caret has moved to wrong position, move it back to correct position
args.TextView.TryMoveCaretToAndEnsureVisible(oldCaretPosition);
}
private CaretPreservingEditTransaction CreateEditTransaction(ITextView view, string description)
=> new(description, view, _undoHistoryRegistry, _editorOperationsFactoryService);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Formatting
{
[Export]
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(PredefinedCommandHandlerNames.FormatDocument)]
[Order(After = PredefinedCommandHandlerNames.Rename)]
[Order(Before = PredefinedCompletionNames.CompletionCommandHandler)]
internal partial class FormatCommandHandler :
ICommandHandler<FormatDocumentCommandArgs>,
ICommandHandler<FormatSelectionCommandArgs>,
IChainedCommandHandler<PasteCommandArgs>,
IChainedCommandHandler<TypeCharCommandArgs>,
IChainedCommandHandler<ReturnKeyCommandArgs>
{
private readonly ITextUndoHistoryRegistry _undoHistoryRegistry;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
public string DisplayName => EditorFeaturesResources.Automatic_Formatting;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FormatCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
_undoHistoryRegistry = undoHistoryRegistry;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
private void Format(ITextView textView, Document document, TextSpan? selectionOpt, CancellationToken cancellationToken)
{
var formattingService = document.GetRequiredLanguageService<IFormattingInteractionService>();
using (Logger.LogBlock(FunctionId.CommandHandler_FormatCommand, KeyValueLogMessage.Create(LogType.UserAction, m => m["Span"] = selectionOpt?.Length ?? -1), cancellationToken))
using (var transaction = CreateEditTransaction(textView, EditorFeaturesResources.Formatting))
{
var changes = formattingService.GetFormattingChangesAsync(
document, selectionOpt, documentOptions: null, cancellationToken).WaitAndGetResult(cancellationToken);
if (changes.IsEmpty)
{
return;
}
ApplyChanges(document, changes, selectionOpt, cancellationToken);
transaction.Complete();
}
}
private static void ApplyChanges(Document document, IList<TextChange> changes, TextSpan? selectionOpt, CancellationToken cancellationToken)
{
if (selectionOpt.HasValue)
{
var ruleFactory = document.Project.Solution.Workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
changes = ruleFactory.FilterFormattedChanges(document, selectionOpt.Value, changes).ToList();
if (changes.Count == 0)
{
return;
}
}
using (Logger.LogBlock(FunctionId.Formatting_ApplyResultToBuffer, cancellationToken))
{
document.Project.Solution.Workspace.ApplyTextChanges(document.Id, changes, cancellationToken);
}
}
private static bool CanExecuteCommand(ITextBuffer buffer)
=> buffer.CanApplyChangeDocumentToWorkspace();
private static CommandState GetCommandState(ITextBuffer buffer)
=> CanExecuteCommand(buffer) ? CommandState.Available : CommandState.Unspecified;
public void ExecuteReturnOrTypeCommand(EditorCommandArgs args, Action nextHandler, CancellationToken cancellationToken)
{
// run next handler first so that editor has chance to put the return into the buffer first.
nextHandler();
if (cancellationToken.IsCancellationRequested)
{
return;
}
try
{
ExecuteReturnOrTypeCommandWorker(args, cancellationToken);
}
catch (OperationCanceledException)
{
// According to Editor command handler API guidelines, it's best if we return early if cancellation
// is requested instead of throwing. Otherwise, we could end up in an invalid state due to already
// calling nextHandler().
}
}
private void ExecuteReturnOrTypeCommandWorker(EditorCommandArgs args, CancellationToken cancellationToken)
{
var textView = args.TextView;
var subjectBuffer = args.SubjectBuffer;
if (!CanExecuteCommand(subjectBuffer))
{
return;
}
var caretPosition = textView.GetCaretPoint(args.SubjectBuffer);
if (!caretPosition.HasValue)
{
return;
}
var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return;
}
var service = document.GetLanguageService<IFormattingInteractionService>();
if (service == null)
{
return;
}
IList<TextChange>? textChanges;
// save current caret position
if (args is ReturnKeyCommandArgs)
{
if (!service.SupportsFormatOnReturn)
{
return;
}
textChanges = service.GetFormattingChangesOnReturnAsync(
document, caretPosition.Value, documentOptions: null, cancellationToken).WaitAndGetResult(cancellationToken);
}
else if (args is TypeCharCommandArgs typeCharArgs)
{
if (!service.SupportsFormattingOnTypedCharacter(document, typeCharArgs.TypedChar))
{
return;
}
textChanges = service.GetFormattingChangesAsync(
document, typeCharArgs.TypedChar, caretPosition.Value, documentOptions: null, cancellationToken).WaitAndGetResult(cancellationToken);
}
else
{
throw ExceptionUtilities.UnexpectedValue(args);
}
if (textChanges == null || textChanges.Count == 0)
{
return;
}
using (var transaction = CreateEditTransaction(textView, EditorFeaturesResources.Automatic_Formatting))
{
transaction.MergePolicy = AutomaticCodeChangeMergePolicy.Instance;
document.Project.Solution.Workspace.ApplyTextChanges(document.Id, textChanges, cancellationToken);
transaction.Complete();
}
// get new caret position after formatting
var newCaretPositionMarker = args.TextView.GetCaretPoint(args.SubjectBuffer);
if (!newCaretPositionMarker.HasValue)
{
return;
}
var snapshotAfterFormatting = args.SubjectBuffer.CurrentSnapshot;
var oldCaretPosition = caretPosition.Value.TranslateTo(snapshotAfterFormatting, PointTrackingMode.Negative);
var newCaretPosition = newCaretPositionMarker.Value.TranslateTo(snapshotAfterFormatting, PointTrackingMode.Negative);
if (oldCaretPosition.Position == newCaretPosition.Position)
{
return;
}
// caret has moved to wrong position, move it back to correct position
args.TextView.TryMoveCaretToAndEnsureVisible(oldCaretPosition);
}
private CaretPreservingEditTransaction CreateEditTransaction(ITextView view, string description)
=> new(description, view, _undoHistoryRegistry, _editorOperationsFactoryService);
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Compilers/VisualBasic/Portable/Symbols/Source/CustomEventAccessorSymbol.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend NotInheritable Class CustomEventAccessorSymbol
Inherits SourceNonPropertyAccessorMethodSymbol
Private ReadOnly _event As SourceEventSymbol
Private ReadOnly _name As String
Private _lazyExplicitImplementations As ImmutableArray(Of MethodSymbol) ' lazily populated with explicit implementations
Friend Sub New(container As SourceMemberContainerTypeSymbol,
[event] As SourceEventSymbol,
name As String,
flags As SourceMemberFlags,
syntaxRef As SyntaxReference,
location As Location)
MyBase.New(container, flags, syntaxRef, locations:=ImmutableArray.Create(location))
_event = [event]
_name = name
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property MetadataName As String
Get
' Event symbols aren't affected if the output kind is winmd, mark false
' (N.B., events only emits helpers named add_ and remove_, not set_)
Return Binder.GetAccessorName(_event.MetadataName, Me.MethodKind, isWinMd:=False)
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
' Raise is always private
If Me.MethodKind = MethodKind.EventRaise Then
Return Accessibility.Private
End If
Return _event.DeclaredAccessibility
End Get
End Property
Protected Overrides Function GetParameters(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol)
Dim type = DirectCast(Me.ContainingType, SourceMemberContainerTypeSymbol)
Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, type)
binder = New LocationSpecificBinder(BindingLocation.EventAccessorSignature, Me, binder)
Return BindParameters(Me.Locations.FirstOrDefault, binder, BlockSyntax.BlockStatement.ParameterList, diagBag)
End Function
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return _event
End Get
End Property
Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean
Get
Return _event.ShadowsExplicitly
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
If _lazyExplicitImplementations.IsDefault Then
ImmutableInterlocked.InterlockedCompareExchange(
_lazyExplicitImplementations,
_event.GetAccessorImplementations(Me.MethodKind),
Nothing)
End If
Return _lazyExplicitImplementations
End Get
End Property
Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol
Get
' custom event methods do not override
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
' custom event methods do not have explicit returns and never implement or override
Return ImmutableArray(Of CustomModifier).Empty
End Get
End Property
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
' Event accessors can never be an extension method.
Return False
End Get
End Property
Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean
Get
' Event accessors can never be an extension method.
Return False
End Get
End Property
Protected Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
Return OneOrMany.Create(AttributeDeclarationSyntaxList)
End Function
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
Return Nothing
End Function
''' <remarks>
''' We're going to ignore SourceMemberFlags.MethodIsSub and override IsSub explicitly. We do this because
''' the flags have to be set at construction time, but IsSub depends on IsWindowsRuntimeEvent, which depends
''' on interface implementations, which we don't want to bind until the member list is complete. (It's probably
''' okay now (2012/12/17), but it would be very fragile to take a dependency on the exact mechanism by which
''' interface members are looked up.)
''' </remarks>
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return Not (Me.MethodKind = MethodKind.EventAdd AndAlso _event.IsWindowsRuntimeEvent)
End Get
End Property
''' <summary>
''' Bind and validate parameters declared on the accessor.
''' </summary>
Private Function BindParameters(location As Location,
binder As Binder,
parameterListOpt As ParameterListSyntax,
diagnostics As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol)
Dim parameterListSyntax = If(parameterListOpt Is Nothing, Nothing, parameterListOpt.Parameters)
Dim nParameters = parameterListSyntax.Count
Dim paramBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance(nParameters)
' Bind all parameters (even though we know how many to expect),
' to ensure all diagnostics are generated and ensure parameter symbols are available for binding the method body.
binder.DecodeParameterList(
Me,
False,
SourceMemberFlags.None,
parameterListSyntax,
paramBuilder,
If(Me.MethodKind = MethodKind.EventRaise,
s_checkRaiseParameterModifierCallback,
s_checkAddRemoveParameterModifierCallback),
diagnostics)
Dim parameters = paramBuilder.ToImmutableAndFree()
If Me.MethodKind = MethodKind.EventRaise Then
' Dev10 does something weird here - it checks for method conversion, but does it
' backwards - it allows delegate Invoke to be more specific than signature of Raise.
' Example: delegate may take int, but Raise may take long argument.
'
' For backwards compatibility we will do the same.
'
' NOTE: no change in raise event shape for WinRT events.
Dim eventType = TryCast(_event.Type, NamedTypeSymbol)
If eventType IsNot Nothing AndAlso
Not eventType.IsErrorType Then
Dim delInvoke = eventType.DelegateInvokeMethod
' If delegate is a function method we should already have diagnostics about that
If delInvoke IsNot Nothing AndAlso delInvoke.IsSub Then
Dim useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics)
Dim conversion = Conversions.ClassifyMethodConversionForEventRaise(
delInvoke,
parameters,
useSiteInfo)
If Not diagnostics.Add(location, useSiteInfo) AndAlso
(Not Conversions.IsDelegateRelaxationSupportedFor(conversion) OrElse
(binder.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingMethodConversion(conversion, False))) Then
diagnostics.Add(ERRID.ERR_RaiseEventShapeMismatch1, location, eventType)
End If
End If
End If
Else
If parameters.Length <> 1 Then
diagnostics.Add(ERRID.ERR_EventAddRemoveHasOnlyOneParam, location)
Else
Dim eventType = _event.Type
Debug.Assert(eventType IsNot Nothing)
Dim parameterType = parameters(0).Type
Debug.Assert(parameterType IsNot Nothing)
If Me.MethodKind = MethodKind.EventAdd Then
If Not eventType.IsErrorType AndAlso Not TypeSymbol.Equals(eventType, parameterType, TypeCompareKind.ConsiderEverything) Then
Dim errid As ERRID = If(_event.IsWindowsRuntimeEvent, ERRID.ERR_AddParamWrongForWinRT, ERRID.ERR_AddRemoveParamNotEventType)
diagnostics.Add(errid, location)
End If
Else
Debug.Assert(Me.MethodKind = MethodKind.EventRemove)
If _event.ExplicitInterfaceImplementations.Any() Then
' Reporting diagnostics when this type is missing will only ever result in cascading, so don't bother.
Dim registrationTokenType As NamedTypeSymbol =
binder.Compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken)
Dim firstImplementedEvent As EventSymbol = _event.ExplicitInterfaceImplementations(0)
If Not registrationTokenType.IsErrorType AndAlso firstImplementedEvent.IsWindowsRuntimeEvent <> (TypeSymbol.Equals(parameterType, registrationTokenType, TypeCompareKind.ConsiderEverything)) Then
diagnostics.Add(ERRID.ERR_EventImplRemoveHandlerParamWrong, location, _event.Name, firstImplementedEvent.Name, firstImplementedEvent.ContainingType)
End If
ElseIf _event.IsWindowsRuntimeEvent Then
' Reporting diagnostics when this type is missing will only ever result in cascading, so don't bother.
Dim registrationTokenType As NamedTypeSymbol =
binder.Compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken)
If Not registrationTokenType.IsErrorType AndAlso Not TypeSymbol.Equals(parameterType, registrationTokenType, TypeCompareKind.ConsiderEverything) Then
diagnostics.Add(ERRID.ERR_RemoveParamWrongForWinRT, location)
End If
Else
If Not eventType.IsErrorType AndAlso Not TypeSymbol.Equals(eventType, parameterType, TypeCompareKind.ConsiderEverything) Then
diagnostics.Add(ERRID.ERR_AddRemoveParamNotEventType, location)
End If
End If
End If
End If
End If
Return parameters
End Function
Private Shared ReadOnly s_checkAddRemoveParameterModifierCallback As Binder.CheckParameterModifierDelegate = AddressOf CheckAddRemoveParameterModifier
Private Shared ReadOnly s_checkRaiseParameterModifierCallback As Binder.CheckParameterModifierDelegate = AddressOf CheckEventMethodParameterModifier
' applicable to all event methods
Private Shared Function CheckEventMethodParameterModifier(container As Symbol, token As SyntaxToken, flag As SourceParameterFlags, diagnostics As BindingDiagnosticBag) As SourceParameterFlags
If (flag And SourceParameterFlags.Optional) <> 0 Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_EventMethodOptionalParamIllegal1, location, token.ToString())
flag = flag And (Not SourceParameterFlags.Optional)
End If
If (flag And SourceParameterFlags.ParamArray) <> 0 Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_EventMethodOptionalParamIllegal1, location, token.ToString())
flag = flag And (Not SourceParameterFlags.ParamArray)
End If
Return flag
End Function
' additional rules for Add and Remove
Private Shared Function CheckAddRemoveParameterModifier(container As Symbol, token As SyntaxToken, flag As SourceParameterFlags, diagnostics As BindingDiagnosticBag) As SourceParameterFlags
If (flag And SourceParameterFlags.ByRef) <> 0 Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_EventAddRemoveByrefParamIllegal, location, token.ToString())
flag = flag And (Not SourceParameterFlags.ByRef)
End If
Return CheckEventMethodParameterModifier(container, token, flag, diagnostics)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Friend NotInheritable Class CustomEventAccessorSymbol
Inherits SourceNonPropertyAccessorMethodSymbol
Private ReadOnly _event As SourceEventSymbol
Private ReadOnly _name As String
Private _lazyExplicitImplementations As ImmutableArray(Of MethodSymbol) ' lazily populated with explicit implementations
Friend Sub New(container As SourceMemberContainerTypeSymbol,
[event] As SourceEventSymbol,
name As String,
flags As SourceMemberFlags,
syntaxRef As SyntaxReference,
location As Location)
MyBase.New(container, flags, syntaxRef, locations:=ImmutableArray.Create(location))
_event = [event]
_name = name
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property MetadataName As String
Get
' Event symbols aren't affected if the output kind is winmd, mark false
' (N.B., events only emits helpers named add_ and remove_, not set_)
Return Binder.GetAccessorName(_event.MetadataName, Me.MethodKind, isWinMd:=False)
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
' Raise is always private
If Me.MethodKind = MethodKind.EventRaise Then
Return Accessibility.Private
End If
Return _event.DeclaredAccessibility
End Get
End Property
Protected Overrides Function GetParameters(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol)
Dim type = DirectCast(Me.ContainingType, SourceMemberContainerTypeSymbol)
Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, type)
binder = New LocationSpecificBinder(BindingLocation.EventAccessorSignature, Me, binder)
Return BindParameters(Me.Locations.FirstOrDefault, binder, BlockSyntax.BlockStatement.ParameterList, diagBag)
End Function
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return _event
End Get
End Property
Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean
Get
Return _event.ShadowsExplicitly
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
If _lazyExplicitImplementations.IsDefault Then
ImmutableInterlocked.InterlockedCompareExchange(
_lazyExplicitImplementations,
_event.GetAccessorImplementations(Me.MethodKind),
Nothing)
End If
Return _lazyExplicitImplementations
End Get
End Property
Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol
Get
' custom event methods do not override
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
' custom event methods do not have explicit returns and never implement or override
Return ImmutableArray(Of CustomModifier).Empty
End Get
End Property
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
' Event accessors can never be an extension method.
Return False
End Get
End Property
Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean
Get
' Event accessors can never be an extension method.
Return False
End Get
End Property
Protected Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
Return OneOrMany.Create(AttributeDeclarationSyntaxList)
End Function
Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax))
Return Nothing
End Function
''' <remarks>
''' We're going to ignore SourceMemberFlags.MethodIsSub and override IsSub explicitly. We do this because
''' the flags have to be set at construction time, but IsSub depends on IsWindowsRuntimeEvent, which depends
''' on interface implementations, which we don't want to bind until the member list is complete. (It's probably
''' okay now (2012/12/17), but it would be very fragile to take a dependency on the exact mechanism by which
''' interface members are looked up.)
''' </remarks>
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return Not (Me.MethodKind = MethodKind.EventAdd AndAlso _event.IsWindowsRuntimeEvent)
End Get
End Property
''' <summary>
''' Bind and validate parameters declared on the accessor.
''' </summary>
Private Function BindParameters(location As Location,
binder As Binder,
parameterListOpt As ParameterListSyntax,
diagnostics As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol)
Dim parameterListSyntax = If(parameterListOpt Is Nothing, Nothing, parameterListOpt.Parameters)
Dim nParameters = parameterListSyntax.Count
Dim paramBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance(nParameters)
' Bind all parameters (even though we know how many to expect),
' to ensure all diagnostics are generated and ensure parameter symbols are available for binding the method body.
binder.DecodeParameterList(
Me,
False,
SourceMemberFlags.None,
parameterListSyntax,
paramBuilder,
If(Me.MethodKind = MethodKind.EventRaise,
s_checkRaiseParameterModifierCallback,
s_checkAddRemoveParameterModifierCallback),
diagnostics)
Dim parameters = paramBuilder.ToImmutableAndFree()
If Me.MethodKind = MethodKind.EventRaise Then
' Dev10 does something weird here - it checks for method conversion, but does it
' backwards - it allows delegate Invoke to be more specific than signature of Raise.
' Example: delegate may take int, but Raise may take long argument.
'
' For backwards compatibility we will do the same.
'
' NOTE: no change in raise event shape for WinRT events.
Dim eventType = TryCast(_event.Type, NamedTypeSymbol)
If eventType IsNot Nothing AndAlso
Not eventType.IsErrorType Then
Dim delInvoke = eventType.DelegateInvokeMethod
' If delegate is a function method we should already have diagnostics about that
If delInvoke IsNot Nothing AndAlso delInvoke.IsSub Then
Dim useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics)
Dim conversion = Conversions.ClassifyMethodConversionForEventRaise(
delInvoke,
parameters,
useSiteInfo)
If Not diagnostics.Add(location, useSiteInfo) AndAlso
(Not Conversions.IsDelegateRelaxationSupportedFor(conversion) OrElse
(binder.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingMethodConversion(conversion, False))) Then
diagnostics.Add(ERRID.ERR_RaiseEventShapeMismatch1, location, eventType)
End If
End If
End If
Else
If parameters.Length <> 1 Then
diagnostics.Add(ERRID.ERR_EventAddRemoveHasOnlyOneParam, location)
Else
Dim eventType = _event.Type
Debug.Assert(eventType IsNot Nothing)
Dim parameterType = parameters(0).Type
Debug.Assert(parameterType IsNot Nothing)
If Me.MethodKind = MethodKind.EventAdd Then
If Not eventType.IsErrorType AndAlso Not TypeSymbol.Equals(eventType, parameterType, TypeCompareKind.ConsiderEverything) Then
Dim errid As ERRID = If(_event.IsWindowsRuntimeEvent, ERRID.ERR_AddParamWrongForWinRT, ERRID.ERR_AddRemoveParamNotEventType)
diagnostics.Add(errid, location)
End If
Else
Debug.Assert(Me.MethodKind = MethodKind.EventRemove)
If _event.ExplicitInterfaceImplementations.Any() Then
' Reporting diagnostics when this type is missing will only ever result in cascading, so don't bother.
Dim registrationTokenType As NamedTypeSymbol =
binder.Compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken)
Dim firstImplementedEvent As EventSymbol = _event.ExplicitInterfaceImplementations(0)
If Not registrationTokenType.IsErrorType AndAlso firstImplementedEvent.IsWindowsRuntimeEvent <> (TypeSymbol.Equals(parameterType, registrationTokenType, TypeCompareKind.ConsiderEverything)) Then
diagnostics.Add(ERRID.ERR_EventImplRemoveHandlerParamWrong, location, _event.Name, firstImplementedEvent.Name, firstImplementedEvent.ContainingType)
End If
ElseIf _event.IsWindowsRuntimeEvent Then
' Reporting diagnostics when this type is missing will only ever result in cascading, so don't bother.
Dim registrationTokenType As NamedTypeSymbol =
binder.Compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken)
If Not registrationTokenType.IsErrorType AndAlso Not TypeSymbol.Equals(parameterType, registrationTokenType, TypeCompareKind.ConsiderEverything) Then
diagnostics.Add(ERRID.ERR_RemoveParamWrongForWinRT, location)
End If
Else
If Not eventType.IsErrorType AndAlso Not TypeSymbol.Equals(eventType, parameterType, TypeCompareKind.ConsiderEverything) Then
diagnostics.Add(ERRID.ERR_AddRemoveParamNotEventType, location)
End If
End If
End If
End If
End If
Return parameters
End Function
Private Shared ReadOnly s_checkAddRemoveParameterModifierCallback As Binder.CheckParameterModifierDelegate = AddressOf CheckAddRemoveParameterModifier
Private Shared ReadOnly s_checkRaiseParameterModifierCallback As Binder.CheckParameterModifierDelegate = AddressOf CheckEventMethodParameterModifier
' applicable to all event methods
Private Shared Function CheckEventMethodParameterModifier(container As Symbol, token As SyntaxToken, flag As SourceParameterFlags, diagnostics As BindingDiagnosticBag) As SourceParameterFlags
If (flag And SourceParameterFlags.Optional) <> 0 Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_EventMethodOptionalParamIllegal1, location, token.ToString())
flag = flag And (Not SourceParameterFlags.Optional)
End If
If (flag And SourceParameterFlags.ParamArray) <> 0 Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_EventMethodOptionalParamIllegal1, location, token.ToString())
flag = flag And (Not SourceParameterFlags.ParamArray)
End If
Return flag
End Function
' additional rules for Add and Remove
Private Shared Function CheckAddRemoveParameterModifier(container As Symbol, token As SyntaxToken, flag As SourceParameterFlags, diagnostics As BindingDiagnosticBag) As SourceParameterFlags
If (flag And SourceParameterFlags.ByRef) <> 0 Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_EventAddRemoveByrefParamIllegal, location, token.ToString())
flag = flag And (Not SourceParameterFlags.ByRef)
End If
Return CheckEventMethodParameterModifier(container, token, flag, diagnostics)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerActionCounts.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics.Telemetry
{
/// <summary>
/// Contains the counts of registered actions for an analyzer.
/// </summary>
internal class AnalyzerActionCounts
{
internal static readonly AnalyzerActionCounts Empty = new AnalyzerActionCounts(in AnalyzerActions.Empty);
internal AnalyzerActionCounts(in AnalyzerActions analyzerActions) :
this(
analyzerActions.CompilationStartActionsCount,
analyzerActions.CompilationEndActionsCount,
analyzerActions.CompilationActionsCount,
analyzerActions.SyntaxTreeActionsCount,
analyzerActions.AdditionalFileActionsCount,
analyzerActions.SemanticModelActionsCount,
analyzerActions.SymbolActionsCount,
analyzerActions.SymbolStartActionsCount,
analyzerActions.SymbolEndActionsCount,
analyzerActions.SyntaxNodeActionsCount,
analyzerActions.CodeBlockStartActionsCount,
analyzerActions.CodeBlockEndActionsCount,
analyzerActions.CodeBlockActionsCount,
analyzerActions.OperationActionsCount,
analyzerActions.OperationBlockStartActionsCount,
analyzerActions.OperationBlockEndActionsCount,
analyzerActions.OperationBlockActionsCount,
analyzerActions.Concurrent)
{
}
internal AnalyzerActionCounts(
int compilationStartActionsCount,
int compilationEndActionsCount,
int compilationActionsCount,
int syntaxTreeActionsCount,
int additionalFileActionsCount,
int semanticModelActionsCount,
int symbolActionsCount,
int symbolStartActionsCount,
int symbolEndActionsCount,
int syntaxNodeActionsCount,
int codeBlockStartActionsCount,
int codeBlockEndActionsCount,
int codeBlockActionsCount,
int operationActionsCount,
int operationBlockStartActionsCount,
int operationBlockEndActionsCount,
int operationBlockActionsCount,
bool concurrent)
{
CompilationStartActionsCount = compilationStartActionsCount;
CompilationEndActionsCount = compilationEndActionsCount;
CompilationActionsCount = compilationActionsCount;
SyntaxTreeActionsCount = syntaxTreeActionsCount;
AdditionalFileActionsCount = additionalFileActionsCount;
SemanticModelActionsCount = semanticModelActionsCount;
SymbolActionsCount = symbolActionsCount;
SymbolStartActionsCount = symbolStartActionsCount;
SymbolEndActionsCount = symbolEndActionsCount;
SyntaxNodeActionsCount = syntaxNodeActionsCount;
CodeBlockStartActionsCount = codeBlockStartActionsCount;
CodeBlockEndActionsCount = codeBlockEndActionsCount;
CodeBlockActionsCount = codeBlockActionsCount;
OperationActionsCount = operationActionsCount;
OperationBlockStartActionsCount = operationBlockStartActionsCount;
OperationBlockEndActionsCount = operationBlockEndActionsCount;
OperationBlockActionsCount = operationBlockActionsCount;
Concurrent = concurrent;
HasAnyExecutableCodeActions = CodeBlockActionsCount > 0 ||
CodeBlockStartActionsCount > 0 ||
SyntaxNodeActionsCount > 0 ||
OperationActionsCount > 0 ||
OperationBlockActionsCount > 0 ||
OperationBlockStartActionsCount > 0 ||
SymbolStartActionsCount > 0;
}
/// <summary>
/// Count of registered compilation start actions.
/// </summary>
public int CompilationStartActionsCount { get; }
/// <summary>
/// Count of registered compilation end actions.
/// </summary>
public int CompilationEndActionsCount { get; }
/// <summary>
/// Count of registered compilation actions.
/// </summary>
public int CompilationActionsCount { get; }
/// <summary>
/// Count of registered syntax tree actions.
/// </summary>
public int SyntaxTreeActionsCount { get; }
/// <summary>
/// Count of registered additional file actions.
/// </summary>
public int AdditionalFileActionsCount { get; }
/// <summary>
/// Count of registered semantic model actions.
/// </summary>
public int SemanticModelActionsCount { get; }
/// <summary>
/// Count of registered symbol actions.
/// </summary>
public int SymbolActionsCount { get; }
/// <summary>
/// Count of registered symbol start actions.
/// </summary>
public int SymbolStartActionsCount { get; }
/// <summary>
/// Count of registered symbol end actions.
/// </summary>
public int SymbolEndActionsCount { get; }
/// <summary>
/// Count of registered syntax node actions.
/// </summary>
public int SyntaxNodeActionsCount { get; }
/// <summary>
/// Count of code block start actions.
/// </summary>
public int CodeBlockStartActionsCount { get; }
/// <summary>
/// Count of code block end actions.
/// </summary>
public int CodeBlockEndActionsCount { get; }
/// <summary>
/// Count of code block actions.
/// </summary>
public int CodeBlockActionsCount { get; }
/// <summary>
/// Count of Operation actions.
/// </summary>
public int OperationActionsCount { get; }
/// <summary>
/// Count of Operation block start actions.
/// </summary>
public int OperationBlockStartActionsCount { get; }
/// <summary>
/// Count of Operation block end actions.
/// </summary>
public int OperationBlockEndActionsCount { get; }
/// <summary>
/// Count of Operation block actions.
/// </summary>
public int OperationBlockActionsCount { get; }
/// <summary>
/// Returns true if there are any actions that need to run on executable code.
/// </summary>
public bool HasAnyExecutableCodeActions { get; }
/// <summary>
/// Gets a value indicating whether the analyzer supports concurrent execution.
/// </summary>
public bool Concurrent { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Diagnostics.Telemetry
{
/// <summary>
/// Contains the counts of registered actions for an analyzer.
/// </summary>
internal class AnalyzerActionCounts
{
internal static readonly AnalyzerActionCounts Empty = new AnalyzerActionCounts(in AnalyzerActions.Empty);
internal AnalyzerActionCounts(in AnalyzerActions analyzerActions) :
this(
analyzerActions.CompilationStartActionsCount,
analyzerActions.CompilationEndActionsCount,
analyzerActions.CompilationActionsCount,
analyzerActions.SyntaxTreeActionsCount,
analyzerActions.AdditionalFileActionsCount,
analyzerActions.SemanticModelActionsCount,
analyzerActions.SymbolActionsCount,
analyzerActions.SymbolStartActionsCount,
analyzerActions.SymbolEndActionsCount,
analyzerActions.SyntaxNodeActionsCount,
analyzerActions.CodeBlockStartActionsCount,
analyzerActions.CodeBlockEndActionsCount,
analyzerActions.CodeBlockActionsCount,
analyzerActions.OperationActionsCount,
analyzerActions.OperationBlockStartActionsCount,
analyzerActions.OperationBlockEndActionsCount,
analyzerActions.OperationBlockActionsCount,
analyzerActions.Concurrent)
{
}
internal AnalyzerActionCounts(
int compilationStartActionsCount,
int compilationEndActionsCount,
int compilationActionsCount,
int syntaxTreeActionsCount,
int additionalFileActionsCount,
int semanticModelActionsCount,
int symbolActionsCount,
int symbolStartActionsCount,
int symbolEndActionsCount,
int syntaxNodeActionsCount,
int codeBlockStartActionsCount,
int codeBlockEndActionsCount,
int codeBlockActionsCount,
int operationActionsCount,
int operationBlockStartActionsCount,
int operationBlockEndActionsCount,
int operationBlockActionsCount,
bool concurrent)
{
CompilationStartActionsCount = compilationStartActionsCount;
CompilationEndActionsCount = compilationEndActionsCount;
CompilationActionsCount = compilationActionsCount;
SyntaxTreeActionsCount = syntaxTreeActionsCount;
AdditionalFileActionsCount = additionalFileActionsCount;
SemanticModelActionsCount = semanticModelActionsCount;
SymbolActionsCount = symbolActionsCount;
SymbolStartActionsCount = symbolStartActionsCount;
SymbolEndActionsCount = symbolEndActionsCount;
SyntaxNodeActionsCount = syntaxNodeActionsCount;
CodeBlockStartActionsCount = codeBlockStartActionsCount;
CodeBlockEndActionsCount = codeBlockEndActionsCount;
CodeBlockActionsCount = codeBlockActionsCount;
OperationActionsCount = operationActionsCount;
OperationBlockStartActionsCount = operationBlockStartActionsCount;
OperationBlockEndActionsCount = operationBlockEndActionsCount;
OperationBlockActionsCount = operationBlockActionsCount;
Concurrent = concurrent;
HasAnyExecutableCodeActions = CodeBlockActionsCount > 0 ||
CodeBlockStartActionsCount > 0 ||
SyntaxNodeActionsCount > 0 ||
OperationActionsCount > 0 ||
OperationBlockActionsCount > 0 ||
OperationBlockStartActionsCount > 0 ||
SymbolStartActionsCount > 0;
}
/// <summary>
/// Count of registered compilation start actions.
/// </summary>
public int CompilationStartActionsCount { get; }
/// <summary>
/// Count of registered compilation end actions.
/// </summary>
public int CompilationEndActionsCount { get; }
/// <summary>
/// Count of registered compilation actions.
/// </summary>
public int CompilationActionsCount { get; }
/// <summary>
/// Count of registered syntax tree actions.
/// </summary>
public int SyntaxTreeActionsCount { get; }
/// <summary>
/// Count of registered additional file actions.
/// </summary>
public int AdditionalFileActionsCount { get; }
/// <summary>
/// Count of registered semantic model actions.
/// </summary>
public int SemanticModelActionsCount { get; }
/// <summary>
/// Count of registered symbol actions.
/// </summary>
public int SymbolActionsCount { get; }
/// <summary>
/// Count of registered symbol start actions.
/// </summary>
public int SymbolStartActionsCount { get; }
/// <summary>
/// Count of registered symbol end actions.
/// </summary>
public int SymbolEndActionsCount { get; }
/// <summary>
/// Count of registered syntax node actions.
/// </summary>
public int SyntaxNodeActionsCount { get; }
/// <summary>
/// Count of code block start actions.
/// </summary>
public int CodeBlockStartActionsCount { get; }
/// <summary>
/// Count of code block end actions.
/// </summary>
public int CodeBlockEndActionsCount { get; }
/// <summary>
/// Count of code block actions.
/// </summary>
public int CodeBlockActionsCount { get; }
/// <summary>
/// Count of Operation actions.
/// </summary>
public int OperationActionsCount { get; }
/// <summary>
/// Count of Operation block start actions.
/// </summary>
public int OperationBlockStartActionsCount { get; }
/// <summary>
/// Count of Operation block end actions.
/// </summary>
public int OperationBlockEndActionsCount { get; }
/// <summary>
/// Count of Operation block actions.
/// </summary>
public int OperationBlockActionsCount { get; }
/// <summary>
/// Returns true if there are any actions that need to run on executable code.
/// </summary>
public bool HasAnyExecutableCodeActions { get; }
/// <summary>
/// Gets a value indicating whether the analyzer supports concurrent execution.
/// </summary>
public bool Concurrent { get; }
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Compilers/Test/Core/PDB/DeterministicBuildCompilationTestHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Cci;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Roslyn.Test.Utilities.PDB
{
internal static partial class DeterministicBuildCompilationTestHelpers
{
public static void VerifyPdbOption<T>(this ImmutableDictionary<string, string> pdbOptions, string pdbName, T expectedValue, Func<T, bool> isDefault = null, Func<T, string> toString = null)
{
bool expectedIsDefault = (isDefault != null) ? isDefault(expectedValue) : EqualityComparer<T>.Default.Equals(expectedValue, default);
var expectedValueString = expectedIsDefault ? null : (toString != null) ? toString(expectedValue) : expectedValue.ToString();
pdbOptions.TryGetValue(pdbName, out var actualValueString);
Assert.Equal(expectedValueString, actualValueString);
}
public static IEnumerable<EmitOptions> GetEmitOptions()
{
var emitOptions = new EmitOptions(
debugInformationFormat: DebugInformationFormat.Embedded,
pdbChecksumAlgorithm: HashAlgorithmName.SHA256,
defaultSourceFileEncoding: Encoding.UTF32);
yield return emitOptions;
yield return emitOptions.WithDefaultSourceFileEncoding(Encoding.ASCII);
yield return emitOptions.WithDefaultSourceFileEncoding(null).WithFallbackSourceFileEncoding(Encoding.Unicode);
yield return emitOptions.WithFallbackSourceFileEncoding(Encoding.Unicode).WithDefaultSourceFileEncoding(Encoding.ASCII);
}
internal static void AssertCommonOptions(EmitOptions emitOptions, CompilationOptions compilationOptions, Compilation compilation, ImmutableDictionary<string, string> pdbOptions)
{
pdbOptions.VerifyPdbOption("version", 2);
pdbOptions.VerifyPdbOption("fallback-encoding", emitOptions.FallbackSourceFileEncoding, toString: v => v.WebName);
pdbOptions.VerifyPdbOption("default-encoding", emitOptions.DefaultSourceFileEncoding, toString: v => v.WebName);
int portabilityPolicy = 0;
if (compilationOptions.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer)
{
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0;
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0;
}
pdbOptions.VerifyPdbOption("portability-policy", portabilityPolicy);
var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
Assert.Equal(compilerVersion.ToString(), pdbOptions["compiler-version"]);
var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
Assert.Equal(runtimeVersion, pdbOptions[CompilationOptionNames.RuntimeVersion]);
pdbOptions.VerifyPdbOption(
"optimization",
(compilationOptions.OptimizationLevel, compilationOptions.DebugPlusMode),
toString: v => v.OptimizationLevel.ToPdbSerializedString(v.DebugPlusMode));
Assert.Equal(compilation.Language, pdbOptions["language"]);
}
public static void VerifyReferenceInfo(TestMetadataReferenceInfo[] references, TargetFramework targetFramework, BlobReader metadataReferenceReader)
{
var frameworkReferences = TargetFrameworkUtil.GetReferences(targetFramework);
var count = 0;
while (metadataReferenceReader.RemainingBytes > 0)
{
var info = ParseMetadataReferenceInfo(ref metadataReferenceReader);
if (frameworkReferences.Any(x => x.GetModuleVersionId() == info.Mvid))
{
count++;
continue;
}
var testReference = references.Single(x => x.MetadataReferenceInfo.Mvid == info.Mvid);
testReference.MetadataReferenceInfo.AssertEqual(info);
count++;
}
Assert.Equal(references.Length + frameworkReferences.Length, count);
}
public static BlobReader GetSingleBlob(Guid infoGuid, MetadataReader pdbReader)
{
return (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == infoGuid
select pdbReader.GetBlobReader(cdi.Value)).Single();
}
public static MetadataReferenceInfo ParseMetadataReferenceInfo(ref BlobReader blobReader)
{
// Order of information
// File name (null terminated string): A.exe
// Extern Alias (null terminated string): a1,a2,a3
// EmbedInteropTypes/MetadataImageKind (byte)
// COFF header Timestamp field (4 byte int)
// COFF header SizeOfImage field (4 byte int)
// MVID (Guid, 24 bytes)
var terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var name = blobReader.ReadUTF8(terminatorIndex);
// Skip the null terminator
blobReader.ReadByte();
terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var externAliases = blobReader.ReadUTF8(terminatorIndex);
blobReader.ReadByte();
var embedInteropTypesAndKind = blobReader.ReadByte();
var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10;
var kind = (embedInteropTypesAndKind & 0b1) == 0b1
? MetadataImageKind.Assembly
: MetadataImageKind.Module;
var timestamp = blobReader.ReadInt32();
var imageSize = blobReader.ReadInt32();
var mvid = blobReader.ReadGuid();
return new MetadataReferenceInfo(
timestamp,
imageSize,
name,
mvid,
string.IsNullOrEmpty(externAliases)
? ImmutableArray<string>.Empty
: externAliases.Split(',').ToImmutableArray(),
kind,
embedInteropTypes);
}
public static ImmutableDictionary<string, string> ParseCompilationOptions(BlobReader blobReader)
{
// Compiler flag bytes are UTF-8 null-terminated key-value pairs
string key = null;
Dictionary<string, string> kvp = new Dictionary<string, string>();
for (; ; )
{
var nullIndex = blobReader.IndexOf(0);
if (nullIndex == -1)
{
break;
}
var value = blobReader.ReadUTF8(nullIndex);
// Skip the null terminator
blobReader.ReadByte();
if (key is null)
{
key = value;
}
else
{
kvp[key] = value;
key = null;
}
}
Assert.Null(key);
Assert.Equal(0, blobReader.RemainingBytes);
return kvp.ToImmutableDictionary();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Cci;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Roslyn.Test.Utilities.PDB
{
internal static partial class DeterministicBuildCompilationTestHelpers
{
public static void VerifyPdbOption<T>(this ImmutableDictionary<string, string> pdbOptions, string pdbName, T expectedValue, Func<T, bool> isDefault = null, Func<T, string> toString = null)
{
bool expectedIsDefault = (isDefault != null) ? isDefault(expectedValue) : EqualityComparer<T>.Default.Equals(expectedValue, default);
var expectedValueString = expectedIsDefault ? null : (toString != null) ? toString(expectedValue) : expectedValue.ToString();
pdbOptions.TryGetValue(pdbName, out var actualValueString);
Assert.Equal(expectedValueString, actualValueString);
}
public static IEnumerable<EmitOptions> GetEmitOptions()
{
var emitOptions = new EmitOptions(
debugInformationFormat: DebugInformationFormat.Embedded,
pdbChecksumAlgorithm: HashAlgorithmName.SHA256,
defaultSourceFileEncoding: Encoding.UTF32);
yield return emitOptions;
yield return emitOptions.WithDefaultSourceFileEncoding(Encoding.ASCII);
yield return emitOptions.WithDefaultSourceFileEncoding(null).WithFallbackSourceFileEncoding(Encoding.Unicode);
yield return emitOptions.WithFallbackSourceFileEncoding(Encoding.Unicode).WithDefaultSourceFileEncoding(Encoding.ASCII);
}
internal static void AssertCommonOptions(EmitOptions emitOptions, CompilationOptions compilationOptions, Compilation compilation, ImmutableDictionary<string, string> pdbOptions)
{
pdbOptions.VerifyPdbOption("version", 2);
pdbOptions.VerifyPdbOption("fallback-encoding", emitOptions.FallbackSourceFileEncoding, toString: v => v.WebName);
pdbOptions.VerifyPdbOption("default-encoding", emitOptions.DefaultSourceFileEncoding, toString: v => v.WebName);
int portabilityPolicy = 0;
if (compilationOptions.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer)
{
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0;
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0;
}
pdbOptions.VerifyPdbOption("portability-policy", portabilityPolicy);
var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
Assert.Equal(compilerVersion.ToString(), pdbOptions["compiler-version"]);
var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
Assert.Equal(runtimeVersion, pdbOptions[CompilationOptionNames.RuntimeVersion]);
pdbOptions.VerifyPdbOption(
"optimization",
(compilationOptions.OptimizationLevel, compilationOptions.DebugPlusMode),
toString: v => v.OptimizationLevel.ToPdbSerializedString(v.DebugPlusMode));
Assert.Equal(compilation.Language, pdbOptions["language"]);
}
public static void VerifyReferenceInfo(TestMetadataReferenceInfo[] references, TargetFramework targetFramework, BlobReader metadataReferenceReader)
{
var frameworkReferences = TargetFrameworkUtil.GetReferences(targetFramework);
var count = 0;
while (metadataReferenceReader.RemainingBytes > 0)
{
var info = ParseMetadataReferenceInfo(ref metadataReferenceReader);
if (frameworkReferences.Any(x => x.GetModuleVersionId() == info.Mvid))
{
count++;
continue;
}
var testReference = references.Single(x => x.MetadataReferenceInfo.Mvid == info.Mvid);
testReference.MetadataReferenceInfo.AssertEqual(info);
count++;
}
Assert.Equal(references.Length + frameworkReferences.Length, count);
}
public static BlobReader GetSingleBlob(Guid infoGuid, MetadataReader pdbReader)
{
return (from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == infoGuid
select pdbReader.GetBlobReader(cdi.Value)).Single();
}
public static MetadataReferenceInfo ParseMetadataReferenceInfo(ref BlobReader blobReader)
{
// Order of information
// File name (null terminated string): A.exe
// Extern Alias (null terminated string): a1,a2,a3
// EmbedInteropTypes/MetadataImageKind (byte)
// COFF header Timestamp field (4 byte int)
// COFF header SizeOfImage field (4 byte int)
// MVID (Guid, 24 bytes)
var terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var name = blobReader.ReadUTF8(terminatorIndex);
// Skip the null terminator
blobReader.ReadByte();
terminatorIndex = blobReader.IndexOf(0);
Assert.NotEqual(-1, terminatorIndex);
var externAliases = blobReader.ReadUTF8(terminatorIndex);
blobReader.ReadByte();
var embedInteropTypesAndKind = blobReader.ReadByte();
var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10;
var kind = (embedInteropTypesAndKind & 0b1) == 0b1
? MetadataImageKind.Assembly
: MetadataImageKind.Module;
var timestamp = blobReader.ReadInt32();
var imageSize = blobReader.ReadInt32();
var mvid = blobReader.ReadGuid();
return new MetadataReferenceInfo(
timestamp,
imageSize,
name,
mvid,
string.IsNullOrEmpty(externAliases)
? ImmutableArray<string>.Empty
: externAliases.Split(',').ToImmutableArray(),
kind,
embedInteropTypes);
}
public static ImmutableDictionary<string, string> ParseCompilationOptions(BlobReader blobReader)
{
// Compiler flag bytes are UTF-8 null-terminated key-value pairs
string key = null;
Dictionary<string, string> kvp = new Dictionary<string, string>();
for (; ; )
{
var nullIndex = blobReader.IndexOf(0);
if (nullIndex == -1)
{
break;
}
var value = blobReader.ReadUTF8(nullIndex);
// Skip the null terminator
blobReader.ReadByte();
if (key is null)
{
key = value;
}
else
{
kvp[key] = value;
key = null;
}
}
Assert.Null(key);
Assert.Equal(0, blobReader.RemainingBytes);
return kvp.ToImmutableDictionary();
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceParameterCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.IntroduceVariable;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.IntroduceParameter), Shared]
internal partial class CSharpIntroduceParameterCodeRefactoringProvider : AbstractIntroduceParameterService<
ExpressionSyntax,
InvocationExpressionSyntax,
ObjectCreationExpressionSyntax,
IdentifierNameSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpIntroduceParameterCodeRefactoringProvider()
{
}
protected override SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol)
{
return ExpressionGenerator.GenerateExpression(parameterSymbol.Type, parameterSymbol.ExplicitDefaultValue, canUseFieldReference: true);
}
protected override SyntaxNode? GetLocalDeclarationFromDeclarator(SyntaxNode variableDecl)
{
return variableDecl.Parent?.Parent as LocalDeclarationStatementSyntax;
}
protected override bool IsDestructor(IMethodSymbol methodSymbol)
{
return false;
}
protected override SyntaxNode UpdateArgumentListSyntax(SyntaxNode argumentList, SeparatedSyntaxList<SyntaxNode> arguments)
=> ((ArgumentListSyntax)argumentList).WithArguments(arguments);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.IntroduceVariable;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.IntroduceParameter), Shared]
internal partial class CSharpIntroduceParameterCodeRefactoringProvider : AbstractIntroduceParameterService<
ExpressionSyntax,
InvocationExpressionSyntax,
ObjectCreationExpressionSyntax,
IdentifierNameSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpIntroduceParameterCodeRefactoringProvider()
{
}
protected override SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol)
{
return ExpressionGenerator.GenerateExpression(parameterSymbol.Type, parameterSymbol.ExplicitDefaultValue, canUseFieldReference: true);
}
protected override SyntaxNode? GetLocalDeclarationFromDeclarator(SyntaxNode variableDecl)
{
return variableDecl.Parent?.Parent as LocalDeclarationStatementSyntax;
}
protected override bool IsDestructor(IMethodSymbol methodSymbol)
{
return false;
}
protected override SyntaxNode UpdateArgumentListSyntax(SyntaxNode argumentList, SeparatedSyntaxList<SyntaxNode> arguments)
=> ((ArgumentListSyntax)argumentList).WithArguments(arguments);
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/VisualStudio/VisualBasic/Impl/Snippets/SnippetFunctions/SnippetFunctionClassName.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets.SnippetFunctions
Friend NotInheritable Class SnippetFunctionClassName
Inherits AbstractSnippetFunctionClassName
Public Sub New(snippetExpansionClient As SnippetExpansionClient, subjectBuffer As ITextBuffer, fieldName As String)
MyBase.New(snippetExpansionClient, subjectBuffer, fieldName)
End Sub
Protected Overrides Function GetContainingClassName(document As Document, subjectBufferFieldSpan As SnapshotSpan, cancellationToken As CancellationToken, ByRef value As String, ByRef hasDefaultValue As Integer) As Integer
Dim syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken)
Dim typeBlock = syntaxTree.FindTokenOnLeftOfPosition(subjectBufferFieldSpan.Start.Position, cancellationToken).GetAncestor(Of TypeBlockSyntax)
If typeBlock IsNot Nothing AndAlso
Not String.IsNullOrWhiteSpace(typeBlock.GetNameToken().ValueText) Then
value = typeBlock.GetNameToken().ValueText
hasDefaultValue = 1
End If
Return VSConstants.S_OK
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Shared.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets.SnippetFunctions
Friend NotInheritable Class SnippetFunctionClassName
Inherits AbstractSnippetFunctionClassName
Public Sub New(snippetExpansionClient As SnippetExpansionClient, subjectBuffer As ITextBuffer, fieldName As String)
MyBase.New(snippetExpansionClient, subjectBuffer, fieldName)
End Sub
Protected Overrides Function GetContainingClassName(document As Document, subjectBufferFieldSpan As SnapshotSpan, cancellationToken As CancellationToken, ByRef value As String, ByRef hasDefaultValue As Integer) As Integer
Dim syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken)
Dim typeBlock = syntaxTree.FindTokenOnLeftOfPosition(subjectBufferFieldSpan.Start.Position, cancellationToken).GetAncestor(Of TypeBlockSyntax)
If typeBlock IsNot Nothing AndAlso
Not String.IsNullOrWhiteSpace(typeBlock.GetNameToken().ValueText) Then
value = typeBlock.GetNameToken().ValueText
hasDefaultValue = 1
End If
Return VSConstants.S_OK
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/BestIndex.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 BestIndexKind
{
None,
Best,
Ambiguous
}
internal struct BestIndex
{
internal readonly BestIndexKind Kind;
internal readonly int Best;
internal readonly int Ambiguous1;
internal readonly int Ambiguous2;
public static BestIndex None() { return new BestIndex(BestIndexKind.None, 0, 0, 0); }
public static BestIndex HasBest(int best) { return new BestIndex(BestIndexKind.Best, best, 0, 0); }
public static BestIndex IsAmbiguous(int ambig1, int ambig2) { return new BestIndex(BestIndexKind.Ambiguous, 0, ambig1, ambig2); }
private BestIndex(BestIndexKind kind, int best, int ambig1, int ambig2)
{
this.Kind = kind;
this.Best = best;
this.Ambiguous1 = ambig1;
this.Ambiguous2 = ambig2;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 BestIndexKind
{
None,
Best,
Ambiguous
}
internal struct BestIndex
{
internal readonly BestIndexKind Kind;
internal readonly int Best;
internal readonly int Ambiguous1;
internal readonly int Ambiguous2;
public static BestIndex None() { return new BestIndex(BestIndexKind.None, 0, 0, 0); }
public static BestIndex HasBest(int best) { return new BestIndex(BestIndexKind.Best, best, 0, 0); }
public static BestIndex IsAmbiguous(int ambig1, int ambig2) { return new BestIndex(BestIndexKind.Ambiguous, 0, ambig1, ambig2); }
private BestIndex(BestIndexKind kind, int best, int ambig1, int ambig2)
{
this.Kind = kind;
this.Best = best;
this.Ambiguous1 = ambig1;
this.Ambiguous2 = ambig2;
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.DiagnosticsChangedEventSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class DiagnosticsChangedEventSource : AbstractTaggerEventSource
{
private readonly ITextBuffer _subjectBuffer;
private readonly IDiagnosticService _service;
public DiagnosticsChangedEventSource(ITextBuffer subjectBuffer, IDiagnosticService service)
{
_subjectBuffer = subjectBuffer;
_service = service;
}
private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs e)
{
var document = _subjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
if (document != null && document.Project.Solution.Workspace == e.Workspace && document.Id == e.DocumentId)
{
this.RaiseChanged();
}
}
public override void Connect()
=> _service.DiagnosticsUpdated += OnDiagnosticsUpdated;
public override void Disconnect()
=> _service.DiagnosticsUpdated -= OnDiagnosticsUpdated;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class DiagnosticsChangedEventSource : AbstractTaggerEventSource
{
private readonly ITextBuffer _subjectBuffer;
private readonly IDiagnosticService _service;
public DiagnosticsChangedEventSource(ITextBuffer subjectBuffer, IDiagnosticService service)
{
_subjectBuffer = subjectBuffer;
_service = service;
}
private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs e)
{
var document = _subjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
if (document != null && document.Project.Solution.Workspace == e.Workspace && document.Id == e.DocumentId)
{
this.RaiseChanged();
}
}
public override void Connect()
=> _service.DiagnosticsUpdated += OnDiagnosticsUpdated;
public override void Disconnect()
=> _service.DiagnosticsUpdated -= OnDiagnosticsUpdated;
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/EditorFeatures/DiagnosticsTestUtilities/SplitComments/AbstractSplitCommentCommandHandlerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral;
using Microsoft.CodeAnalysis.Editor.Implementation.SplitComment;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Formatting.FormattingOptions;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SplitComment
{
public abstract class AbstractSplitCommentCommandHandlerTests
{
protected abstract TestWorkspace CreateWorkspace(string markup);
/// <summary>
/// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033
/// Most tests will continue to verifyUndo, but select tests will skip it due to
/// this known test infrastructure issue. This bug does not represent a product
/// failure.
/// </summary>
private void TestWorker(
string inputMarkup,
string? expectedOutputMarkup,
Action callback,
bool enabled,
bool useTabs)
{
if (useTabs)
{
// Make sure the tests seem well formed (i.e. no one accidentally replaced the tabs in them with spaces.
Assert.True(inputMarkup.Contains("\t"));
if (expectedOutputMarkup != null)
Assert.True(expectedOutputMarkup.Contains("\t"));
}
using var workspace = this.CreateWorkspace(inputMarkup);
var language = workspace.Projects.Single().Language;
workspace.SetOptions(
workspace.Options.WithChangedOption(FormattingOptions.UseTabs, language, useTabs)
.WithChangedOption(SplitCommentOptions.Enabled, language, enabled));
var document = workspace.Documents.Single();
var view = document.GetTextView();
var originalSnapshot = view.TextBuffer.CurrentSnapshot;
var originalSelections = document.SelectedSpans;
var snapshotSpans = new List<SnapshotSpan>();
foreach (var selection in originalSelections)
snapshotSpans.Add(new SnapshotSpan(originalSnapshot, new Span(selection.Start, selection.Length)));
view.SetMultiSelection(snapshotSpans);
var undoHistoryRegistry = workspace.GetService<ITextUndoHistoryRegistry>();
var commandHandler = workspace.ExportProvider.GetCommandHandler<SplitCommentCommandHandler>(nameof(SplitCommentCommandHandler));
if (!commandHandler.ExecuteCommand(new ReturnKeyCommandArgs(view, view.TextBuffer), TestCommandExecutionContext.Create()))
{
callback();
}
if (expectedOutputMarkup != null)
{
MarkupTestFile.GetSpans(expectedOutputMarkup,
out var expectedOutput, out ImmutableArray<TextSpan> expectedSpans);
Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.AsText().ToString());
// Ensure that after undo we go back to where we were to begin with.
var history = undoHistoryRegistry.GetHistory(document.GetTextBuffer());
history.Undo(count: originalSelections.Count);
var currentSnapshot = document.GetTextBuffer().CurrentSnapshot;
Assert.Equal(originalSnapshot.GetText(), currentSnapshot.GetText());
}
}
/// <summary>
/// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033
/// Most tests will continue to verifyUndo, but select tests will skip it due to
/// this known test infrastructure issue. This bug does not represent a product
/// failure.
/// </summary>
protected void TestHandled(string inputMarkup, string expectedOutputMarkup, bool enabled = true, bool useTabs = false)
{
TestWorker(
inputMarkup, expectedOutputMarkup,
callback: () =>
{
Assert.True(false, "Should not reach here.");
}, enabled, useTabs);
}
protected void TestNotHandled(string inputMarkup, bool enabled = true, bool useTabs = false)
{
var notHandled = false;
TestWorker(
inputMarkup, null,
callback: () =>
{
notHandled = true;
}, enabled, useTabs);
Assert.True(notHandled);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral;
using Microsoft.CodeAnalysis.Editor.Implementation.SplitComment;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Formatting.FormattingOptions;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SplitComment
{
public abstract class AbstractSplitCommentCommandHandlerTests
{
protected abstract TestWorkspace CreateWorkspace(string markup);
/// <summary>
/// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033
/// Most tests will continue to verifyUndo, but select tests will skip it due to
/// this known test infrastructure issue. This bug does not represent a product
/// failure.
/// </summary>
private void TestWorker(
string inputMarkup,
string? expectedOutputMarkup,
Action callback,
bool enabled,
bool useTabs)
{
if (useTabs)
{
// Make sure the tests seem well formed (i.e. no one accidentally replaced the tabs in them with spaces.
Assert.True(inputMarkup.Contains("\t"));
if (expectedOutputMarkup != null)
Assert.True(expectedOutputMarkup.Contains("\t"));
}
using var workspace = this.CreateWorkspace(inputMarkup);
var language = workspace.Projects.Single().Language;
workspace.SetOptions(
workspace.Options.WithChangedOption(FormattingOptions.UseTabs, language, useTabs)
.WithChangedOption(SplitCommentOptions.Enabled, language, enabled));
var document = workspace.Documents.Single();
var view = document.GetTextView();
var originalSnapshot = view.TextBuffer.CurrentSnapshot;
var originalSelections = document.SelectedSpans;
var snapshotSpans = new List<SnapshotSpan>();
foreach (var selection in originalSelections)
snapshotSpans.Add(new SnapshotSpan(originalSnapshot, new Span(selection.Start, selection.Length)));
view.SetMultiSelection(snapshotSpans);
var undoHistoryRegistry = workspace.GetService<ITextUndoHistoryRegistry>();
var commandHandler = workspace.ExportProvider.GetCommandHandler<SplitCommentCommandHandler>(nameof(SplitCommentCommandHandler));
if (!commandHandler.ExecuteCommand(new ReturnKeyCommandArgs(view, view.TextBuffer), TestCommandExecutionContext.Create()))
{
callback();
}
if (expectedOutputMarkup != null)
{
MarkupTestFile.GetSpans(expectedOutputMarkup,
out var expectedOutput, out ImmutableArray<TextSpan> expectedSpans);
Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.AsText().ToString());
// Ensure that after undo we go back to where we were to begin with.
var history = undoHistoryRegistry.GetHistory(document.GetTextBuffer());
history.Undo(count: originalSelections.Count);
var currentSnapshot = document.GetTextBuffer().CurrentSnapshot;
Assert.Equal(originalSnapshot.GetText(), currentSnapshot.GetText());
}
}
/// <summary>
/// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033
/// Most tests will continue to verifyUndo, but select tests will skip it due to
/// this known test infrastructure issue. This bug does not represent a product
/// failure.
/// </summary>
protected void TestHandled(string inputMarkup, string expectedOutputMarkup, bool enabled = true, bool useTabs = false)
{
TestWorker(
inputMarkup, expectedOutputMarkup,
callback: () =>
{
Assert.True(false, "Should not reach here.");
}, enabled, useTabs);
}
protected void TestNotHandled(string inputMarkup, bool enabled = true, bool useTabs = false)
{
var notHandled = false;
TestWorker(
inputMarkup, null,
callback: () =>
{
notHandled = true;
}, enabled, useTabs);
Assert.True(notHandled);
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/EditorFeatures/CSharpTest/KeywordHighlighting/ReturnStatementHighlighterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class ReturnStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(ReturnStatementHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda()
{
await TestAsync(
@"static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
{|Cursor:[|return|]|} Double.NaN;
}
else
{
[|return|] r * r * Math.PI;
}
};
return calcArea(radius);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda_NotOnReturnValue()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
return {|Cursor:Double.NaN|};
}
else
{
return r * r * Math.PI;
}
};
return calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda_OnSemicolon()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
[|return|] Double.NaN;{|Cursor:|}
}
else
{
[|return|] r * r * Math.PI;
}
};
return calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda_SecondOccurence()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
[|return|] Double.NaN;
}
else
{
{|Cursor:[|return|]|} r * r * Math.PI;
}
};
return calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda_SecondOccurence_NotOnReturnValue()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
return Double.NaN;
}
else
{
return {|Cursor:r * r * Math.PI|};
}
};
return calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda_SecondOccurence_OnSemicolon()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
[|return|] Double.NaN;
}
else
{
[|return|] r * r * Math.PI;{|Cursor:|}
}
};
return calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInMethodWithLambda()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
return Double.NaN;
}
else
{
return r * r * Math.PI;
}
};
{|Cursor:[|return|]|} calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInMethodWithLambda_NotOnReturnValue()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
return Double.NaN;
}
else
{
return r * r * Math.PI;
}
};
return {|Cursor:calcArea(radius)|};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInMethodWithLambda_OnSemicolon()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
return Double.NaN;
}
else
{
return r * r * Math.PI;
}
};
[|return|] calcArea(radius);{|Cursor:|}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInConstructor()
{
await TestAsync(
@"class C
{
C()
{
{|Cursor:[|return|]|};
[|return|];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInDestructor()
{
await TestAsync(
@"class C
{
~C()
{
{|Cursor:[|return|]|};
[|return|];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInOperator()
{
await TestAsync(
@"class C
{
public static string operator +(C a)
{
{|Cursor:[|return|]|} null;
[|return|] null;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInConversionOperator()
{
await TestAsync(
@"class C
{
public static explicit operator string(C a)
{
{|Cursor:[|return|]|} null;
[|return|] null;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInGetter()
{
await TestAsync(
@"class C
{
int P
{
get
{
{|Cursor:[|return|]|} 0;
[|return|] 0;
}
set
{
return;
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInSetter()
{
await TestAsync(
@"class C
{
int P
{
get
{
return 0;
return 0;
}
set
{
{|Cursor:[|return|]|};
[|return|];
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInInit()
{
await TestAsync(
@"class C
{
int P
{
get
{
return 0;
return 0;
}
init
{
{|Cursor:[|return|]|};
[|return|];
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInAdder()
{
await TestAsync(
@"class C
{
event EventHandler E
{
add
{
{|Cursor:[|return|]|};
[|return|];
}
remove
{
return;
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInRemover()
{
await TestAsync(
@"class C
{
event EventHandler E
{
add
{
return;
return;
}
remove
{
{|Cursor:[|return|]|};
[|return|];
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLocalFunction()
{
await TestAsync(
@"class C
{
void M()
{
void F()
{
{|Cursor:[|return|]|};
[|return|];
}
return;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInSimpleLambda()
{
await TestAsync(
@"class C
{
void M()
{
Action<string> f = s =>
{
{|Cursor:[|return|]|};
[|return|];
};
return;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInParenthesizedLambda()
{
await TestAsync(
@"class C
{
void M()
{
Action<string> f = (s) =>
{
{|Cursor:[|return|]|};
[|return|];
};
return;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInAnonymousMethod()
{
await TestAsync(
@"class C
{
void M()
{
Action<string> f = delegate
{
{|Cursor:[|return|]|};
[|return|];
};
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.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class ReturnStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(ReturnStatementHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda()
{
await TestAsync(
@"static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
{|Cursor:[|return|]|} Double.NaN;
}
else
{
[|return|] r * r * Math.PI;
}
};
return calcArea(radius);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda_NotOnReturnValue()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
return {|Cursor:Double.NaN|};
}
else
{
return r * r * Math.PI;
}
};
return calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda_OnSemicolon()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
[|return|] Double.NaN;{|Cursor:|}
}
else
{
[|return|] r * r * Math.PI;
}
};
return calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda_SecondOccurence()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
[|return|] Double.NaN;
}
else
{
{|Cursor:[|return|]|} r * r * Math.PI;
}
};
return calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda_SecondOccurence_NotOnReturnValue()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
return Double.NaN;
}
else
{
return {|Cursor:r * r * Math.PI|};
}
};
return calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLambda_SecondOccurence_OnSemicolon()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
[|return|] Double.NaN;
}
else
{
[|return|] r * r * Math.PI;{|Cursor:|}
}
};
return calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInMethodWithLambda()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
return Double.NaN;
}
else
{
return r * r * Math.PI;
}
};
{|Cursor:[|return|]|} calcArea(radius);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInMethodWithLambda_NotOnReturnValue()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
return Double.NaN;
}
else
{
return r * r * Math.PI;
}
};
return {|Cursor:calcArea(radius)|};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInMethodWithLambda_OnSemicolon()
{
await TestAsync(
@"class C
{
static double CalculateArea(double radius)
{
Func<double, double> f = r => {
if (Double.IsNan(r))
{
return Double.NaN;
}
else
{
return r * r * Math.PI;
}
};
[|return|] calcArea(radius);{|Cursor:|}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInConstructor()
{
await TestAsync(
@"class C
{
C()
{
{|Cursor:[|return|]|};
[|return|];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInDestructor()
{
await TestAsync(
@"class C
{
~C()
{
{|Cursor:[|return|]|};
[|return|];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInOperator()
{
await TestAsync(
@"class C
{
public static string operator +(C a)
{
{|Cursor:[|return|]|} null;
[|return|] null;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInConversionOperator()
{
await TestAsync(
@"class C
{
public static explicit operator string(C a)
{
{|Cursor:[|return|]|} null;
[|return|] null;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInGetter()
{
await TestAsync(
@"class C
{
int P
{
get
{
{|Cursor:[|return|]|} 0;
[|return|] 0;
}
set
{
return;
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInSetter()
{
await TestAsync(
@"class C
{
int P
{
get
{
return 0;
return 0;
}
set
{
{|Cursor:[|return|]|};
[|return|];
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInInit()
{
await TestAsync(
@"class C
{
int P
{
get
{
return 0;
return 0;
}
init
{
{|Cursor:[|return|]|};
[|return|];
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInAdder()
{
await TestAsync(
@"class C
{
event EventHandler E
{
add
{
{|Cursor:[|return|]|};
[|return|];
}
remove
{
return;
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInRemover()
{
await TestAsync(
@"class C
{
event EventHandler E
{
add
{
return;
return;
}
remove
{
{|Cursor:[|return|]|};
[|return|];
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInLocalFunction()
{
await TestAsync(
@"class C
{
void M()
{
void F()
{
{|Cursor:[|return|]|};
[|return|];
}
return;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInSimpleLambda()
{
await TestAsync(
@"class C
{
void M()
{
Action<string> f = s =>
{
{|Cursor:[|return|]|};
[|return|];
};
return;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInParenthesizedLambda()
{
await TestAsync(
@"class C
{
void M()
{
Action<string> f = (s) =>
{
{|Cursor:[|return|]|};
[|return|];
};
return;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestInAnonymousMethod()
{
await TestAsync(
@"class C
{
void M()
{
Action<string> f = delegate
{
{|Cursor:[|return|]|};
[|return|];
};
return;
}
}");
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Features/VisualBasic/Portable/UseNamedArguments/VisualBasicUseNamedArgumentsCodeRefactoringProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.UseNamedArguments
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UseNamedArguments
<ExtensionOrder(After:=PredefinedCodeRefactoringProviderNames.IntroduceVariable)>
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.UseNamedArguments), [Shared]>
Friend Class VisualBasicUseNamedArgumentsCodeRefactoringProvider
Inherits AbstractUseNamedArgumentsCodeRefactoringProvider
Private Class ArgumentAnalyzer
Inherits Analyzer(Of ArgumentSyntax, SimpleArgumentSyntax, ArgumentListSyntax)
Protected Overrides Function IsPositionalArgument(argument As SimpleArgumentSyntax) As Boolean
Return argument.NameColonEquals Is Nothing
End Function
Protected Overrides Function GetArguments(argumentList As ArgumentListSyntax) As SeparatedSyntaxList(Of ArgumentSyntax)
Return argumentList.Arguments
End Function
Protected Overrides Function GetReceiver(argument As SyntaxNode) As SyntaxNode
If argument.Parent.IsParentKind(SyntaxKind.Attribute) Then
Return Nothing
End If
Return argument.Parent.Parent
End Function
Protected Overrides Function WithName(argument As SimpleArgumentSyntax, name As String) As SimpleArgumentSyntax
Return argument.WithNameColonEquals(SyntaxFactory.NameColonEquals(name.ToIdentifierName()))
End Function
Protected Overrides Function WithArguments(argumentList As ArgumentListSyntax, namedArguments As IEnumerable(Of ArgumentSyntax), separators As IEnumerable(Of SyntaxToken)) As ArgumentListSyntax
Return argumentList.WithArguments(SyntaxFactory.SeparatedList(namedArguments, separators))
End Function
Protected Overrides Function IsLegalToAddNamedArguments(parameters As ImmutableArray(Of IParameterSymbol), argumentCount As Integer) As Boolean
Return Not parameters.LastOrDefault().IsParams OrElse parameters.Length > argumentCount
End Function
Protected Overrides Function SupportsNonTrailingNamedArguments(options As ParseOptions) As Boolean
Return DirectCast(options, VisualBasicParseOptions).LanguageVersion >= LanguageVersion.VisualBasic15_5
End Function
Protected Overrides Function IsImplicitIndexOrRangeIndexer(parameters As ImmutableArray(Of IParameterSymbol), argument As ArgumentSyntax, semanticModel As SemanticModel) As Boolean
Return False
End Function
End Class
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
MyBase.New(New ArgumentAnalyzer(), attributeArgumentAnalyzer:=Nothing)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.UseNamedArguments
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UseNamedArguments
<ExtensionOrder(After:=PredefinedCodeRefactoringProviderNames.IntroduceVariable)>
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.UseNamedArguments), [Shared]>
Friend Class VisualBasicUseNamedArgumentsCodeRefactoringProvider
Inherits AbstractUseNamedArgumentsCodeRefactoringProvider
Private Class ArgumentAnalyzer
Inherits Analyzer(Of ArgumentSyntax, SimpleArgumentSyntax, ArgumentListSyntax)
Protected Overrides Function IsPositionalArgument(argument As SimpleArgumentSyntax) As Boolean
Return argument.NameColonEquals Is Nothing
End Function
Protected Overrides Function GetArguments(argumentList As ArgumentListSyntax) As SeparatedSyntaxList(Of ArgumentSyntax)
Return argumentList.Arguments
End Function
Protected Overrides Function GetReceiver(argument As SyntaxNode) As SyntaxNode
If argument.Parent.IsParentKind(SyntaxKind.Attribute) Then
Return Nothing
End If
Return argument.Parent.Parent
End Function
Protected Overrides Function WithName(argument As SimpleArgumentSyntax, name As String) As SimpleArgumentSyntax
Return argument.WithNameColonEquals(SyntaxFactory.NameColonEquals(name.ToIdentifierName()))
End Function
Protected Overrides Function WithArguments(argumentList As ArgumentListSyntax, namedArguments As IEnumerable(Of ArgumentSyntax), separators As IEnumerable(Of SyntaxToken)) As ArgumentListSyntax
Return argumentList.WithArguments(SyntaxFactory.SeparatedList(namedArguments, separators))
End Function
Protected Overrides Function IsLegalToAddNamedArguments(parameters As ImmutableArray(Of IParameterSymbol), argumentCount As Integer) As Boolean
Return Not parameters.LastOrDefault().IsParams OrElse parameters.Length > argumentCount
End Function
Protected Overrides Function SupportsNonTrailingNamedArguments(options As ParseOptions) As Boolean
Return DirectCast(options, VisualBasicParseOptions).LanguageVersion >= LanguageVersion.VisualBasic15_5
End Function
Protected Overrides Function IsImplicitIndexOrRangeIndexer(parameters As ImmutableArray(Of IParameterSymbol), argument As ArgumentSyntax, semanticModel As SemanticModel) As Boolean
Return False
End Function
End Class
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
MyBase.New(New ArgumentAnalyzer(), attributeArgumentAnalyzer:=Nothing)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Dependencies/Collections/Internal/SegmentedArraySegment`1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Collections.Internal
{
internal readonly struct SegmentedArraySegment<T>
{
public SegmentedArray<T> Array { get; }
public int Start { get; }
public int Length { get; }
public SegmentedArraySegment(SegmentedArray<T> array, int start, int length)
{
Array = array;
Start = start;
Length = length;
}
public ref T this[int index]
{
get
{
if ((uint)index >= (uint)Length)
ThrowHelper.ThrowIndexOutOfRangeException();
return ref Array[index + Start];
}
}
public SegmentedArraySegment<T> Slice(int start)
{
if ((uint)start >= (uint)Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new SegmentedArraySegment<T>(Array, Start + start, Length - start);
}
public SegmentedArraySegment<T> Slice(int start, int length)
{
// Since start and length are both 32-bit, their sum can be computed across a 64-bit domain
// without loss of fidelity. The cast to uint before the cast to ulong ensures that the
// extension from 32- to 64-bit is zero-extending rather than sign-extending. The end result
// of this is that if either input is negative or if the input sum overflows past Int32.MaxValue,
// that information is captured correctly in the comparison against the backing _length field.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new SegmentedArraySegment<T>(Array, Start + start, length);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Collections.Internal
{
internal readonly struct SegmentedArraySegment<T>
{
public SegmentedArray<T> Array { get; }
public int Start { get; }
public int Length { get; }
public SegmentedArraySegment(SegmentedArray<T> array, int start, int length)
{
Array = array;
Start = start;
Length = length;
}
public ref T this[int index]
{
get
{
if ((uint)index >= (uint)Length)
ThrowHelper.ThrowIndexOutOfRangeException();
return ref Array[index + Start];
}
}
public SegmentedArraySegment<T> Slice(int start)
{
if ((uint)start >= (uint)Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new SegmentedArraySegment<T>(Array, Start + start, Length - start);
}
public SegmentedArraySegment<T> Slice(int start, int length)
{
// Since start and length are both 32-bit, their sum can be computed across a 64-bit domain
// without loss of fidelity. The cast to uint before the cast to ulong ensures that the
// extension from 32- to 64-bit is zero-extending rather than sign-extending. The end result
// of this is that if either input is negative or if the input sum overflows past Int32.MaxValue,
// that information is captured correctly in the comparison against the backing _length field.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new SegmentedArraySegment<T>(Array, Start + start, length);
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Analyzers/CSharp/Tests/UseImplicitOrExplicitType/UseExplicitTypeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle;
using Microsoft.CodeAnalysis.CSharp.TypeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType
{
public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public UseExplicitTypeTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider());
private readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent);
private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion);
private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion);
private readonly CodeStyleOption2<bool> offWithWarning = new CodeStyleOption2<bool>(false, NotificationOption2.Warning);
private readonly CodeStyleOption2<bool> offWithError = new CodeStyleOption2<bool>(false, NotificationOption2.Error);
// specify all options explicitly to override defaults.
private OptionsCollection ExplicitTypeEverywhere() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeExceptWhereApparent() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeForBuiltInTypesOnly() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, onWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeEnforcements() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithWarning },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeSilentEnforcement() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithSilent },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent },
};
#region Error Cases
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldDeclaration()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
[|var|] _myfield = 5;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldLikeEvents()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
public event [|var|] _myevent;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnAnonymousMethodExpression()
{
var before =
@"using System;
class Program
{
void Method()
{
[|var|] comparer = delegate (string value) {
return value != ""0"";
};
}
}";
var after =
@"using System;
class Program
{
void Method()
{
Func<string, bool> comparer = delegate (string value) {
return value != ""0"";
};
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnLambdaExpression()
{
var before =
@"using System;
class Program
{
void Method()
{
[|var|] x = (int y) => y * y;
}
}";
var after =
@"using System;
class Program
{
void Method()
{
Func<int, int> x = (int y) => y * y;
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithMultipleDeclarators()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = 5, y = x;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithoutInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotDuringConflicts()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] p = new var();
}
class var
{
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotIfAlreadyExplicitlyTyped()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|Program|] p = new Program();
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task NotIfRefTypeAlreadyExplicitlyTyped()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
struct Program
{
void Method()
{
ref [|Program|] p = Ref();
}
ref Program Ref() => throw null;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnRHS()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
var c = new [|var|]();
}
}
class var
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorSymbol()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new Goo();
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorConvertedType_ForEachVariableStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M()
{
// Error CS1061: 'KeyValuePair<int, int>' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'KeyValuePair<int, int>' could be found (are you missing a using directive or an assembly reference?)
// Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'KeyValuePair<int, int>', with 2 out parameters and a void return type.
foreach ([|var|] (key, value) in new Dictionary<int, int>())
{
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorConvertedType_AssignmentExpressionStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M(C c)
{
// 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?)
// Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type.
[|var|] (key, value) = c;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
#endregion
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = new Program[0];
}
}";
var after = @"
class Program
{
void Method()
{
Program[] x = new Program[0];
}
}";
// The type is apparent and not intrinsic
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayTypeWithIntrinsicType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = new int[0];
}
}";
var after = @"
class Program
{
void Method()
{
int[] x = new int[0];
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InNullableIntrinsicType()
{
var before = @"
class Program
{
void Method(int? x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(int? x)
{
int? y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")]
public async Task InNativeIntIntrinsicType()
{
var before = @"
class Program
{
void Method(nint x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(nint x)
{
nint y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")]
public async Task InNativeUnsignedIntIntrinsicType()
{
var before = @"
class Program
{
void Method(nuint x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(nuint x)
{
nuint y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task WithRefIntrinsicType()
{
var before = @"
class Program
{
void Method()
{
ref [|var|] y = Ref();
}
ref int Ref() => throw null;
}";
var after = @"
class Program
{
void Method()
{
ref int y = Ref();
}
ref int Ref() => throw null;
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task WithRefIntrinsicTypeInForeach()
{
var before = @"
class E
{
public ref int Current => throw null;
public bool MoveNext() => throw null;
public E GetEnumerator() => throw null;
void M()
{
foreach (ref [|var|] x in this) { }
}
}";
var after = @"
class E
{
public ref int Current => throw null;
public bool MoveNext() => throw null;
public E GetEnumerator() => throw null;
void M()
{
foreach (ref int x in this) { }
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayOfNullableIntrinsicType()
{
var before = @"
class Program
{
void Method(int?[] x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(int?[] x)
{
int?[] y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InNullableCustomType()
{
var before = @"
struct Program
{
void Method(Program? x)
{
[|var|] y = x;
}
}";
var after = @"
struct Program
{
void Method(Program? x)
{
Program? y = x;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
[|var|] y = x;
y = null;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
Program? y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
[|var|] y = x;
y = null;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
Program y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType()
{
var before = @"
class Program
{
void Method(Program x)
{
#nullable enable
[|var|] y = x;
y = null;
}
}";
var after = @"
class Program
{
void Method(Program x)
{
#nullable enable
Program? y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_OutVar()
{
var before = @"
#nullable enable
class Program
{
void Method(out Program? x)
{
Method(out [|var|] y1);
throw null!;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(out Program? x)
{
Method(out Program? y1);
throw null!;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_OutVar()
{
var before = @"
#nullable enable
class Program
{
void Method(out Program x)
{
Method(out [|var|] y1);
throw null!;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(out Program x)
{
Method(out Program? y1);
throw null!;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_OutVar()
{
var before = @"
class Program
{
void Method(out Program x)
{
Method(out [|var|] y1);
throw null;
}
}";
var after = @"
class Program
{
void Method(out Program x)
{
Method(out Program y1);
throw null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40925"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
[WorkItem(40925, "https://github.com/dotnet/roslyn/issues/40925")]
public async Task NullableTypeAndNotNullableType_VarDeconstruction()
{
var before = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program? x, Program2 x2)
{
[|var|] (y1, y2) = (x, x2);
}
}";
var after = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program? x, Program2 x2)
{
(Program? y1, Program2? y2) = (x, x2);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_VarDeconstruction()
{
var before = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program x, Program2 x2)
{
#nullable disable
[|var|] (y1, y2) = (x, x2);
}
}";
var after = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program x, Program2 x2)
{
#nullable disable
(Program y1, Program2 y2) = (x, x2);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_Deconstruction()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
(Program y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_Deconstruction()
{
var before = @"
class Program
{
void Method(Program x)
{
#nullable enable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
class Program
{
void Method(Program x)
{
#nullable enable
(Program? y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_Deconstruction()
{
var before = @"
class Program
{
void Method(Program? x)
{
#nullable enable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
class Program
{
void Method(Program? x)
{
#nullable enable
(Program? y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_Foreach()
{
var before = @"
#nullable enable
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable disable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
#nullable enable
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable disable
foreach ([|Program|] y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_Foreach()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach (Program? y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_Foreach()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach (Program? y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37491"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_ForeachVarDeconstruction()
{
// Semantic model doesn't yet handle var deconstruction foreach
// https://github.com/dotnet/roslyn/issues/37491
// https://github.com/dotnet/roslyn/issues/35010
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ([|var|] (y1, y2) in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ((Program? y1, Program? y2) in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_ForeachDeconstruction()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach (([|var|] y1, var y2) in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ((Program? y1, var y2) in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InPointerTypeWithIntrinsicType()
{
var before = @"
unsafe class Program
{
void Method(int* y)
{
[|var|] x = y;
}
}";
var after = @"
unsafe class Program
{
void Method(int* y)
{
int* x = y;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InPointerTypeWithCustomType()
{
var before = @"
unsafe class Program
{
void Method(Program* y)
{
[|var|] x = y;
}
}";
var after = @"
unsafe class Program
{
void Method(Program* y)
{
Program* x = y;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23893, "https://github.com/dotnet/roslyn/issues/23893")]
public async Task InOutParameter()
{
var before = @"
class Program
{
void Method(out int x)
{
Method(out [|var|] x);
}
}";
var after = @"
class Program
{
void Method(out int x)
{
Method(out int x);
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDynamic()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|dynamic|] x = 1;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnForEachVarWithAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5).Select(i => new { Value = i });
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarParens()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, string y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
([|var|] x, var y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, var y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, (y, z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, (int y, Program z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnBadlyFormattedNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|](x,(y,z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, (int y, Program z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnForeachNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
foreach ([|var|] (x, (y, z)) in new[] { new Program() } { }
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
foreach ((int x, (int y, Program z)) in new[] { new Program() } { }
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnNestedDeconstructionVarWithTrivia()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
/*before*/[|var|]/*after*/ (/*x1*/x/*x2*/, /*yz1*/(/*y1*/y/*y2*/, /*z1*/z/*z2*/)/*yz2*/) /*end*/ = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
/*before*//*after*/(/*x1*/int x/*x2*/, /*yz1*/(/*y1*/int y/*y2*/, /*z1*/Program z/*z2*/)/*yz2*/) /*end*/ = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarWithDiscard()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, _) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, string _) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarWithErrorType()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, y) = new Program();
}
void Deconstruct(out int i, out Error s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, Error y) = new Program();
}
void Deconstruct(out int i, out Error s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnForEachVarWithExplicitType()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}",
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach (int value in values)
{
Console.WriteLine(value.Value);
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new { Amount = 108, Message = ""Hello"" };
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnArrayOfAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } };
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Method()
{
var products = new List<Product>();
[|var|] productQuery = from prod in products
select new { prod.Color, prod.Price };
}
}
class Product
{
public ConsoleColor Color { get; set; }
public int Price { get; set; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = ""hello"";
}
}",
@"using System;
class C
{
static void M()
{
string s = ""hello"";
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnIntrinsicType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}",
@"using System;
class C
{
static void M()
{
int s = 5;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnFrameworkType()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
static void M()
{
[|var|] c = new List<int>();
}
}",
@"using System.Collections.Generic;
class C
{
static void M()
{
List<int> c = new List<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnUserDefinedType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
[|var|] c = new C();
}
}",
@"using System;
class C
{
void M()
{
C c = new C();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnGenericType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C<T>
{
static void M()
{
[|var|] c = new C<int>();
}
}",
@"using System;
class C<T>
{
static void M()
{
C<int> c = new C<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new int[4] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new int[4] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new[] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}",
@"using System;
class C
{
static void M()
{
int[][] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] cc = new Customer { City = ""Chennai"" };
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
class C
{
static void M()
{
Customer cc = new Customer { City = ""Chennai"" };
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] digits = new List<int> { 1, 2, 3 };
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<int> digits = new List<int> { 1, 2, 3 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] cs = new List<Customer>
{
new Customer { City = ""Chennai"" }
};
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<Customer> cs = new List<Customer>
{
new Customer { City = ""Chennai"" }
};
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
for ([|var|] i = 0; i < 5; i++)
{
}
}
}",
@"using System;
class C
{
static void M()
{
for (int i = 0; i < 5; i++)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForeachStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach ([|var|] item in l)
{
}
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach (int item in l)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnQueryExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
[|var|] expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
IEnumerable<Customer> expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInUsingStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
using ([|var|] r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}",
@"using System;
class C
{
static void M()
{
using (Res r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnInterpolatedString()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] s = $""Hello, {name}""
}
}",
@"using System;
class Program
{
void Method()
{
string s = $""Hello, {name}""
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnExplicitConversion()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
double x = 1234.7;
[|var|] a = (int)x;
}
}",
@"using System;
class C
{
static void M()
{
double x = 1234.7;
int a = (int)x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnConditionalAccessExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
C obj = new C();
[|var|] anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}",
@"using System;
class C
{
static void M()
{
C obj = new C();
C anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInCheckedExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
[|var|] intNumber = checked((int)number1);
}
}",
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
int intNumber = checked((int)number1);
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInAwaitExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|var|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
string text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInNumericType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = 1;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
int text = 1;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInCharType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = GetChar();
}
public char GetChar() => 'c';
}",
@"using System;
class C
{
public void ProcessRead()
{
char text = GetChar();
}
public char GetChar() => 'c';
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_string()
{
// though string isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = string.Empty;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
string text = string.Empty;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_object()
{
// object isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
[|var|] text = j;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
object text = j;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelSilent()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeSilentEnforcement(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Hidden);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelInfo()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Info);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task SuggestExplicitTypeNotificationLevelWarning()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { new C() }; // type not apparent and not intrinsic
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelError()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Error);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int, string) s = (1, ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, b: ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string b) s = (a: 1, b: ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string) s = (a: 1, ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20437, "https://github.com/dotnet/roslyn/issues/20437")]
public async Task SuggestExplicitTypeOnDeclarationExpressionSyntax()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
DateTime.TryParse(string.Empty, [|out var|] date);
}
}",
@"using System;
class C
{
static void M()
{
DateTime.TryParse(string.Empty, out DateTime date);
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames1()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|String|] test = new String(' ', 4);
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames2()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
foreach ([|String|] test in new String[] { ""test1"", ""test2"" })
{
}
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames3()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
[|Int32[]|] array = new[] { 1, 2, 3 };
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames4()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
[|Int32[][]|] a = new Int32[][]
{
new[] { 1, 2 },
new[] { 3, 4 }
};
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames5()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Main()
{
[|IEnumerable<Int32>|] a = new List<Int32> { 1, 2 }.Where(x => x > 1);
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames6()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
String name = ""name"";
[|String|] s = $""Hello, {name}""
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames7()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
Object name = ""name"";
[|String|] s = (String) name;
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames8()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|String|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return String.Empty;
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames9()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
String number = ""12"";
Int32.TryParse(name, out [|Int32|] number)
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames10()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
for ([|Int32|] i = 0; i < 5; i++)
{
}
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames11()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Main()
{
[|List<Int32>|] a = new List<Int32> { 1, 2 };
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")]
public async Task NoSuggestionOnForeachCollectionExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Method(List<int> var)
{
foreach (int value in [|var|])
{
Console.WriteLine(value.Value);
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnConstVar()
{
// This error case is handled by a separate code fix (UseExplicitTypeForConst).
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
const [|var|] v = 0;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task WithNormalFuncSynthesizedLambdaType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = (int i) => i.ToString();
}
}";
var after = @"
class Program
{
void Method()
{
System.Func<int, string> x = (int i) => i.ToString();
}
}";
// The type is not apparent and not intrinsic
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task WithAnonymousSynthesizedLambdaType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = (ref int i) => i.ToString();
}
}";
// The type is apparent and not intrinsic
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeEverywhere()));
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent()));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle;
using Microsoft.CodeAnalysis.CSharp.TypeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType
{
public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public UseExplicitTypeTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider());
private readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent);
private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion);
private readonly CodeStyleOption2<bool> offWithInfo = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion);
private readonly CodeStyleOption2<bool> offWithWarning = new CodeStyleOption2<bool>(false, NotificationOption2.Warning);
private readonly CodeStyleOption2<bool> offWithError = new CodeStyleOption2<bool>(false, NotificationOption2.Error);
// specify all options explicitly to override defaults.
private OptionsCollection ExplicitTypeEverywhere() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeExceptWhereApparent() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeForBuiltInTypesOnly() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, onWithInfo },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeEnforcements() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithWarning },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithError },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithInfo },
};
private OptionsCollection ExplicitTypeSilentEnforcement() =>
new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.VarElsewhere, offWithSilent },
{ CSharpCodeStyleOptions.VarWhenTypeIsApparent, offWithSilent },
{ CSharpCodeStyleOptions.VarForBuiltInTypes, offWithSilent },
};
#region Error Cases
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldDeclaration()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
[|var|] _myfield = 5;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldLikeEvents()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
public event [|var|] _myevent;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnAnonymousMethodExpression()
{
var before =
@"using System;
class Program
{
void Method()
{
[|var|] comparer = delegate (string value) {
return value != ""0"";
};
}
}";
var after =
@"using System;
class Program
{
void Method()
{
Func<string, bool> comparer = delegate (string value) {
return value != ""0"";
};
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnLambdaExpression()
{
var before =
@"using System;
class Program
{
void Method()
{
[|var|] x = (int y) => y * y;
}
}";
var after =
@"using System;
class Program
{
void Method()
{
Func<int, int> x = (int y) => y * y;
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithMultipleDeclarators()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = 5, y = x;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithoutInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotDuringConflicts()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] p = new var();
}
class var
{
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotIfAlreadyExplicitlyTyped()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|Program|] p = new Program();
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task NotIfRefTypeAlreadyExplicitlyTyped()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
struct Program
{
void Method()
{
ref [|Program|] p = Ref();
}
ref Program Ref() => throw null;
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnRHS()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
var c = new [|var|]();
}
}
class var
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorSymbol()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new Goo();
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorConvertedType_ForEachVariableStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M()
{
// Error CS1061: 'KeyValuePair<int, int>' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'KeyValuePair<int, int>' could be found (are you missing a using directive or an assembly reference?)
// Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'KeyValuePair<int, int>', with 2 out parameters and a void return type.
foreach ([|var|] (key, value) in new Dictionary<int, int>())
{
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WorkItem(29718, "https://github.com/dotnet/roslyn/issues/29718")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorConvertedType_AssignmentExpressionStatement()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M(C c)
{
// 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?)
// Error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type.
[|var|] (key, value) = c;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
#endregion
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = new Program[0];
}
}";
var after = @"
class Program
{
void Method()
{
Program[] x = new Program[0];
}
}";
// The type is apparent and not intrinsic
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayTypeWithIntrinsicType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = new int[0];
}
}";
var after = @"
class Program
{
void Method()
{
int[] x = new int[0];
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InNullableIntrinsicType()
{
var before = @"
class Program
{
void Method(int? x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(int? x)
{
int? y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")]
public async Task InNativeIntIntrinsicType()
{
var before = @"
class Program
{
void Method(nint x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(nint x)
{
nint y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")]
public async Task InNativeUnsignedIntIntrinsicType()
{
var before = @"
class Program
{
void Method(nuint x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(nuint x)
{
nuint y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task WithRefIntrinsicType()
{
var before = @"
class Program
{
void Method()
{
ref [|var|] y = Ref();
}
ref int Ref() => throw null;
}";
var after = @"
class Program
{
void Method()
{
ref int y = Ref();
}
ref int Ref() => throw null;
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(27221, "https://github.com/dotnet/roslyn/issues/27221")]
public async Task WithRefIntrinsicTypeInForeach()
{
var before = @"
class E
{
public ref int Current => throw null;
public bool MoveNext() => throw null;
public E GetEnumerator() => throw null;
void M()
{
foreach (ref [|var|] x in this) { }
}
}";
var after = @"
class E
{
public ref int Current => throw null;
public bool MoveNext() => throw null;
public E GetEnumerator() => throw null;
void M()
{
foreach (ref int x in this) { }
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InArrayOfNullableIntrinsicType()
{
var before = @"
class Program
{
void Method(int?[] x)
{
[|var|] y = x;
}
}";
var after = @"
class Program
{
void Method(int?[] x)
{
int?[] y = x;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InNullableCustomType()
{
var before = @"
struct Program
{
void Method(Program? x)
{
[|var|] y = x;
}
}";
var after = @"
struct Program
{
void Method(Program? x)
{
Program? y = x;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
[|var|] y = x;
y = null;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
Program? y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
[|var|] y = x;
y = null;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
Program y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType()
{
var before = @"
class Program
{
void Method(Program x)
{
#nullable enable
[|var|] y = x;
y = null;
}
}";
var after = @"
class Program
{
void Method(Program x)
{
#nullable enable
Program? y = x;
y = null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_OutVar()
{
var before = @"
#nullable enable
class Program
{
void Method(out Program? x)
{
Method(out [|var|] y1);
throw null!;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(out Program? x)
{
Method(out Program? y1);
throw null!;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_OutVar()
{
var before = @"
#nullable enable
class Program
{
void Method(out Program x)
{
Method(out [|var|] y1);
throw null!;
}
}";
var after = @"
#nullable enable
class Program
{
void Method(out Program x)
{
Method(out Program? y1);
throw null!;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_OutVar()
{
var before = @"
class Program
{
void Method(out Program x)
{
Method(out [|var|] y1);
throw null;
}
}";
var after = @"
class Program
{
void Method(out Program x)
{
Method(out Program y1);
throw null;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40925"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
[WorkItem(40925, "https://github.com/dotnet/roslyn/issues/40925")]
public async Task NullableTypeAndNotNullableType_VarDeconstruction()
{
var before = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program? x, Program2 x2)
{
[|var|] (y1, y2) = (x, x2);
}
}";
var after = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program? x, Program2 x2)
{
(Program? y1, Program2? y2) = (x, x2);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_VarDeconstruction()
{
var before = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program x, Program2 x2)
{
#nullable disable
[|var|] (y1, y2) = (x, x2);
}
}";
var after = @"
#nullable enable
class Program2 { }
class Program
{
void Method(Program x, Program2 x2)
{
#nullable disable
(Program y1, Program2 y2) = (x, x2);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_Deconstruction()
{
var before = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
#nullable enable
class Program
{
void Method(Program x)
{
#nullable disable
(Program y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_Deconstruction()
{
var before = @"
class Program
{
void Method(Program x)
{
#nullable enable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
class Program
{
void Method(Program x)
{
#nullable enable
(Program? y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_Deconstruction()
{
var before = @"
class Program
{
void Method(Program? x)
{
#nullable enable
([|var|] y1, Program y2) = (x, x);
}
}";
var after = @"
class Program
{
void Method(Program? x)
{
#nullable enable
(Program? y1, Program y2) = (x, x);
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task ObliviousType_Foreach()
{
var before = @"
#nullable enable
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable disable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
#nullable enable
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable disable
foreach ([|Program|] y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_Foreach()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach (Program? y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NullableType_Foreach()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach ([|var|] y in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<Program> x)
{
#nullable enable
foreach (Program? y in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37491"), Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_ForeachVarDeconstruction()
{
// Semantic model doesn't yet handle var deconstruction foreach
// https://github.com/dotnet/roslyn/issues/37491
// https://github.com/dotnet/roslyn/issues/35010
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ([|var|] (y1, y2) in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ((Program? y1, Program? y2) in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")]
public async Task NotNullableType_ForeachDeconstruction()
{
var before = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach (([|var|] y1, var y2) in x)
{
}
}
}";
var after = @"
class Program
{
void Method(System.Collections.Generic.IEnumerable<(Program, Program)> x)
{
#nullable enable
foreach ((Program? y1, var y2) in x)
{
}
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InPointerTypeWithIntrinsicType()
{
var before = @"
unsafe class Program
{
void Method(int* y)
{
[|var|] x = y;
}
}";
var after = @"
unsafe class Program
{
void Method(int* y)
{
int* x = y;
}
}";
// The type is intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent()); // preference for builtin types dominates
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task InPointerTypeWithCustomType()
{
var before = @"
unsafe class Program
{
void Method(Program* y)
{
[|var|] x = y;
}
}";
var after = @"
unsafe class Program
{
void Method(Program* y)
{
Program* x = y;
}
}";
// The type is not intrinsic and not apparent
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23893, "https://github.com/dotnet/roslyn/issues/23893")]
public async Task InOutParameter()
{
var before = @"
class Program
{
void Method(out int x)
{
Method(out [|var|] x);
}
}";
var after = @"
class Program
{
void Method(out int x)
{
Method(out int x);
}
}";
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeForBuiltInTypesOnly());
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDynamic()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|dynamic|] x = 1;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnForEachVarWithAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5).Select(i => new { Value = i });
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarParens()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, string y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
([|var|] x, var y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, var y) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, (y, z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, (int y, Program z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnBadlyFormattedNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|](x,(y,z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, (int y, Program z)) = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnForeachNestedDeconstructionVar()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
foreach ([|var|] (x, (y, z)) in new[] { new Program() } { }
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
foreach ((int x, (int y, Program z)) in new[] { new Program() } { }
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnNestedDeconstructionVarWithTrivia()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
/*before*/[|var|]/*after*/ (/*x1*/x/*x2*/, /*yz1*/(/*y1*/y/*y2*/, /*z1*/z/*z2*/)/*yz2*/) /*end*/ = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
/*before*//*after*/(/*x1*/int x/*x2*/, /*yz1*/(/*y1*/int y/*y2*/, /*z1*/Program z/*z2*/)/*yz2*/) /*end*/ = new Program();
}
void Deconstruct(out int i, out Program s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarWithDiscard()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, _) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", @"using System;
class Program
{
void M()
{
(int x, string _) = new Program();
}
void Deconstruct(out int i, out string s) { i = 1; s = ""hello""; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23752, "https://github.com/dotnet/roslyn/issues/23752")]
public async Task OnDeconstructionVarWithErrorType()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void M()
{
[|var|] (x, y) = new Program();
}
void Deconstruct(out int i, out Error s) { i = 1; s = null; }
}", @"using System;
class Program
{
void M()
{
(int x, Error y) = new Program();
}
void Deconstruct(out int i, out Error s) { i = 1; s = null; }
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnForEachVarWithExplicitType()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}",
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach (int value in values)
{
Console.WriteLine(value.Value);
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new { Amount = 108, Message = ""Hello"" };
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnArrayOfAnonymousType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } };
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Method()
{
var products = new List<Product>();
[|var|] productQuery = from prod in products
select new { prod.Color, prod.Price };
}
}
class Product
{
public ConsoleColor Color { get; set; }
public int Price { get; set; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = ""hello"";
}
}",
@"using System;
class C
{
static void M()
{
string s = ""hello"";
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnIntrinsicType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}",
@"using System;
class C
{
static void M()
{
int s = 5;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnFrameworkType()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
static void M()
{
[|var|] c = new List<int>();
}
}",
@"using System.Collections.Generic;
class C
{
static void M()
{
List<int> c = new List<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnUserDefinedType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
[|var|] c = new C();
}
}",
@"using System;
class C
{
void M()
{
C c = new C();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnGenericType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C<T>
{
static void M()
{
[|var|] c = new C<int>();
}
}",
@"using System;
class C<T>
{
static void M()
{
C<int> c = new C<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new int[4] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new int[4] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new[] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}",
@"using System;
class C
{
static void M()
{
int[][] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
[|var|] cc = new Customer { City = ""Chennai"" };
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
class C
{
static void M()
{
Customer cc = new Customer { City = ""Chennai"" };
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] digits = new List<int> { 1, 2, 3 };
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<int> digits = new List<int> { 1, 2, 3 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] cs = new List<Customer>
{
new Customer { City = ""Chennai"" }
};
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<Customer> cs = new List<Customer>
{
new Customer { City = ""Chennai"" }
};
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
for ([|var|] i = 0; i < 5; i++)
{
}
}
}",
@"using System;
class C
{
static void M()
{
for (int i = 0; i < 5; i++)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForeachStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach ([|var|] item in l)
{
}
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach (int item in l)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnQueryExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
[|var|] expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
IEnumerable<Customer> expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInUsingStatement()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
using ([|var|] r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}",
@"using System;
class C
{
static void M()
{
using (Res r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnInterpolatedString()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|var|] s = $""Hello, {name}""
}
}",
@"using System;
class Program
{
void Method()
{
string s = $""Hello, {name}""
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnExplicitConversion()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
double x = 1234.7;
[|var|] a = (int)x;
}
}",
@"using System;
class C
{
static void M()
{
double x = 1234.7;
int a = (int)x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnConditionalAccessExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
C obj = new C();
[|var|] anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}",
@"using System;
class C
{
static void M()
{
C obj = new C();
C anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInCheckedExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
[|var|] intNumber = checked((int)number1);
}
}",
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
int intNumber = checked((int)number1);
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInAwaitExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|var|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
string text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInNumericType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = 1;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
int text = 1;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInCharType()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = GetChar();
}
public char GetChar() => 'c';
}",
@"using System;
class C
{
public void ProcessRead()
{
char text = GetChar();
}
public char GetChar() => 'c';
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_string()
{
// though string isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = string.Empty;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
string text = string.Empty;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_object()
{
// object isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestInRegularAndScriptAsync(
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
[|var|] text = j;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
object text = j;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelSilent()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeSilentEnforcement(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Hidden);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelInfo()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Info);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task SuggestExplicitTypeNotificationLevelWarning()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { new C() }; // type not apparent and not intrinsic
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeNotificationLevelError()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticInfoAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Error);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int, string) s = (1, ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, b: ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string b) s = (a: 1, b: ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName()
{
await TestInRegularAndScriptAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string) s = (a: 1, ""hello"");
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20437, "https://github.com/dotnet/roslyn/issues/20437")]
public async Task SuggestExplicitTypeOnDeclarationExpressionSyntax()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
static void M()
{
DateTime.TryParse(string.Empty, [|out var|] date);
}
}",
@"using System;
class C
{
static void M()
{
DateTime.TryParse(string.Empty, out DateTime date);
}
}",
options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames1()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|String|] test = new String(' ', 4);
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames2()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
foreach ([|String|] test in new String[] { ""test1"", ""test2"" })
{
}
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames3()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
[|Int32[]|] array = new[] { 1, 2, 3 };
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames4()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
[|Int32[][]|] a = new Int32[][]
{
new[] { 1, 2 },
new[] { 3, 4 }
};
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames5()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Main()
{
[|IEnumerable<Int32>|] a = new List<Int32> { 1, 2 }.Where(x => x > 1);
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames6()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
String name = ""name"";
[|String|] s = $""Hello, {name}""
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames7()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
Object name = ""name"";
[|String|] s = (String) name;
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames8()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|String|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return String.Empty;
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames9()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
String number = ""12"";
Int32.TryParse(name, out [|Int32|] number)
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames10()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Main()
{
for ([|Int32|] i = 0; i < 5; i++)
{
}
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(20244, "https://github.com/dotnet/roslyn/issues/20244")]
public async Task ExplicitTypeOnPredefinedTypesByTheirMetadataNames11()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Main()
{
[|List<Int32>|] a = new List<Int32> { 1, 2 };
}
}", new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")]
public async Task NoSuggestionOnForeachCollectionExpression()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
class Program
{
void Method(List<int> var)
{
foreach (int value in [|var|])
{
Console.WriteLine(value.Value);
}
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnConstVar()
{
// This error case is handled by a separate code fix (UseExplicitTypeForConst).
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
const [|var|] v = 0;
}
}", new TestParameters(options: ExplicitTypeEverywhere()));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task WithNormalFuncSynthesizedLambdaType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = (int i) => i.ToString();
}
}";
var after = @"
class Program
{
void Method()
{
System.Func<int, string> x = (int i) => i.ToString();
}
}";
// The type is not apparent and not intrinsic
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeEverywhere());
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestInRegularAndScriptAsync(before, after, options: ExplicitTypeExceptWhereApparent());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
[WorkItem(23907, "https://github.com/dotnet/roslyn/issues/23907")]
public async Task WithAnonymousSynthesizedLambdaType()
{
var before = @"
class Program
{
void Method()
{
[|var|] x = (ref int i) => i.ToString();
}
}";
// The type is apparent and not intrinsic
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeEverywhere()));
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeForBuiltInTypesOnly()));
await TestMissingInRegularAndScriptAsync(before, new TestParameters(options: ExplicitTypeExceptWhereApparent()));
}
}
}
| -1 |
dotnet/roslyn | 55,464 | Background import | Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | sharwell | 2021-08-06T14:23:05Z | 2021-08-06T18:45:28Z | e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028 | dee05dddc4c7bc9d051484a1df18a006ab1752e1 | Background import. Moves remaining initialization in `AbstractCreateServicesOnTextViewConnection` to the thread pool.
Follow-up to #55448 | ./src/Features/VisualBasic/Portable/EditAndContinue/BreakpointSpans.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Text
Imports System.Threading
Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue
Friend Module BreakpointSpans
Friend Function TryGetBreakpointSpan(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken, <Out> ByRef breakpointSpan As TextSpan) As Boolean
Dim source = tree.GetText(cancellationToken)
' If the line is entirely whitespace, then don't set any breakpoint there.
Dim line = source.Lines.GetLineFromPosition(position)
If IsBlank(line) Then
breakpointSpan = Nothing
Return False
End If
' If the user is asking for breakpoint in an inactive region, then just create a line
' breakpoint there.
If tree.IsInInactiveRegion(position, cancellationToken) Then
breakpointSpan = Nothing
Return True
End If
Dim root = tree.GetRoot(cancellationToken)
Return TryGetEnclosingBreakpointSpan(root, position, minLength:=0, breakpointSpan)
End Function
Private Function IsBlank(line As TextLine) As Boolean
Dim text = line.ToString()
For i = 0 To text.Length - 1
If Not SyntaxFacts.IsWhitespace(text(i)) Then
Return False
End If
Next
Return True
End Function
''' <summary>
''' Given a syntax token determines a text span delimited by the closest applicable sequence points
''' encompassing the token.
''' </summary>
''' <remarks>
''' If the span exists it Is possible To place a breakpoint at the given position.
''' </remarks>
''' <param name="minLength">
''' In case there are multiple breakpoint spans starting at the given <paramref name="position"/>,
''' <paramref name="minLength"/> can be used to disambiguate between them.
''' The inner-most available span whose length is at least <paramref name="minLength"/> is returned.
''' </param>
Public Function TryGetEnclosingBreakpointSpan(root As SyntaxNode, position As Integer, minLength As Integer, <Out> ByRef span As TextSpan) As Boolean
Dim node = root.FindToken(position).Parent
Dim candidate As TextSpan? = Nothing
While node IsNot Nothing
Dim breakpointSpan = TryCreateSpanForNode(node, position)
If breakpointSpan.HasValue Then
If breakpointSpan.Value = New TextSpan() Then
Exit While
End If
' the new breakpoint span doesn't alight with the previously found breakpoint span, return the previous one:
If candidate.HasValue AndAlso breakpointSpan.Value.Start <> candidate.Value.Start Then
span = candidate.Value
Return True
End If
' The span length meets the requirement:
If breakpointSpan.Value.Length >= minLength Then
span = breakpointSpan.Value
Return True
End If
candidate = breakpointSpan
End If
node = node.Parent
End While
span = candidate.GetValueOrDefault()
Return candidate.HasValue
End Function
Private Function CreateSpan(node As SyntaxNode) As TextSpan
Return TextSpan.FromBounds(node.SpanStart, node.Span.End)
End Function
Private Function TryCreateSpan(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode)) As TextSpan?
If list.Count = 0 Then
Return Nothing
End If
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Private Function TryCreateSpanForNode(node As SyntaxNode, position As Integer) As TextSpan?
Select Case node.Kind
Case SyntaxKind.VariableDeclarator,
SyntaxKind.ModifiedIdentifier
' Handled by parent field or local variable declaration.
Return Nothing
Case SyntaxKind.FieldDeclaration
Dim fieldDeclaration = DirectCast(node, FieldDeclarationSyntax)
Return TryCreateSpanForVariableDeclaration(fieldDeclaration.Modifiers, fieldDeclaration.Declarators, position)
Case SyntaxKind.LocalDeclarationStatement
Dim localDeclaration = DirectCast(node, LocalDeclarationStatementSyntax)
Return TryCreateSpanForVariableDeclaration(localDeclaration.Modifiers, localDeclaration.Declarators, position)
Case SyntaxKind.PropertyStatement
Return TryCreateSpanForPropertyStatement(DirectCast(node, PropertyStatementSyntax))
' Statements that are not executable yet marked with sequence points
Case SyntaxKind.IfStatement,
SyntaxKind.ElseIfStatement,
SyntaxKind.ElseStatement,
SyntaxKind.EndIfStatement,
SyntaxKind.UsingStatement,
SyntaxKind.EndUsingStatement,
SyntaxKind.SyncLockStatement,
SyntaxKind.EndSyncLockStatement,
SyntaxKind.WithStatement,
SyntaxKind.EndWithStatement,
SyntaxKind.SimpleDoStatement, SyntaxKind.DoWhileStatement, SyntaxKind.DoUntilStatement,
SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement,
SyntaxKind.WhileStatement,
SyntaxKind.EndWhileStatement,
SyntaxKind.ForStatement,
SyntaxKind.ForEachStatement,
SyntaxKind.NextStatement,
SyntaxKind.SelectStatement,
SyntaxKind.CaseStatement,
SyntaxKind.CaseElseStatement,
SyntaxKind.EndSelectStatement,
SyntaxKind.TryStatement,
SyntaxKind.CatchStatement,
SyntaxKind.FinallyStatement,
SyntaxKind.EndTryStatement,
SyntaxKind.EndSubStatement,
SyntaxKind.EndFunctionStatement,
SyntaxKind.EndOperatorStatement,
SyntaxKind.EndGetStatement,
SyntaxKind.EndSetStatement,
SyntaxKind.EndAddHandlerStatement,
SyntaxKind.EndRemoveHandlerStatement,
SyntaxKind.EndRaiseEventStatement,
SyntaxKind.FunctionLambdaHeader,
SyntaxKind.SubLambdaHeader
Return CreateSpan(node)
Case SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return CreateSpanForMethodBase(DirectCast(node, MethodBaseSyntax))
Case SyntaxKind.SingleLineIfStatement
Dim asSingleLine = DirectCast(node, SingleLineIfStatementSyntax)
If position >= asSingleLine.IfKeyword.SpanStart AndAlso position < asSingleLine.ThenKeyword.Span.End Then
Return TextSpan.FromBounds(asSingleLine.IfKeyword.SpanStart, asSingleLine.ThenKeyword.Span.End)
Else
Return CreateSpan(node)
End If
Case SyntaxKind.SingleLineElseClause
Dim asSingleLineElse = DirectCast(node, SingleLineElseClauseSyntax)
Return asSingleLineElse.ElseKeyword.Span
Case SyntaxKind.FunctionAggregation
Return TryCreateSpanForFunctionAggregation(DirectCast(node, FunctionAggregationSyntax))
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return CreateSpan(node)
Case SyntaxKind.SelectClause
Return TryCreateSpanForSelectClause(DirectCast(node, SelectClauseSyntax))
Case SyntaxKind.WhereClause
Return TryCreateSpanForWhereClause(DirectCast(node, WhereClauseSyntax))
Case SyntaxKind.CollectionRangeVariable
Return TryCreateSpanForCollectionRangeVariable(DirectCast(node, CollectionRangeVariableSyntax))
Case SyntaxKind.LetClause
Return TryCreateSpanForLetClause(DirectCast(node, LetClauseSyntax), position)
Case SyntaxKind.GroupByClause
Return TryCreateSpanForGroupByClause(DirectCast(node, GroupByClauseSyntax), position)
Case SyntaxKind.SkipWhileClause,
SyntaxKind.TakeWhileClause
Return TryCreateSpanForPartitionWhileClauseSyntax(DirectCast(node, PartitionWhileClauseSyntax))
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Return TryCreateSpanForOrderingSyntax(DirectCast(node, OrderingSyntax))
Case SyntaxKind.OrderByClause
Return TryCreateSpanForOrderByClause(DirectCast(node, OrderByClauseSyntax), position)
Case SyntaxKind.FromClause
Return TryCreateSpanForFromClause(DirectCast(node, FromClauseSyntax), position)
Case Else
Dim executableStatement = TryCast(node, ExecutableStatementSyntax)
If executableStatement IsNot Nothing Then
Return CreateSpan(node)
End If
Dim expression = TryCast(node, ExpressionSyntax)
If expression IsNot Nothing Then
Return TryCreateSpanForExpression(expression)
End If
Return Nothing
End Select
End Function
Private Function CreateSpanForMethodBase(methodBase As MethodBaseSyntax) As TextSpan
If methodBase.Modifiers.Count = 0 Then
Return TextSpan.FromBounds(methodBase.DeclarationKeyword.SpanStart, methodBase.Span.End)
End If
Return TextSpan.FromBounds(methodBase.Modifiers.First().SpanStart, methodBase.Span.End)
End Function
Private Function TryCreateSpanForPropertyStatement(node As PropertyStatementSyntax) As TextSpan?
If node.Parent.IsKind(SyntaxKind.PropertyBlock) Then
' not an auto-property:
Return Nothing
End If
If node.Initializer IsNot Nothing Then
Return TextSpan.FromBounds(node.Identifier.Span.Start, node.Initializer.Span.End)
End If
If node.AsClause IsNot Nothing AndAlso node.AsClause.IsKind(SyntaxKind.AsNewClause) Then
Return TextSpan.FromBounds(node.Identifier.Span.Start, node.AsClause.Span.End)
End If
Return Nothing
End Function
Private Function TryCreateSpanForVariableDeclaration(modifiers As SyntaxTokenList, declarators As SeparatedSyntaxList(Of VariableDeclaratorSyntax), position As Integer) As TextSpan?
If declarators.Count = 0 Then
Return Nothing
End If
If modifiers.Any(SyntaxKind.ConstKeyword) Then
Return New TextSpan()
End If
Dim name = FindClosestNameWithInitializer(declarators, position)
If name Is Nothing Then
Return New TextSpan()
End If
If name.ArrayBounds IsNot Nothing OrElse DirectCast(name.Parent, VariableDeclaratorSyntax).Names.Count > 1 Then
Return CreateSpan(name)
Else
Return CreateSpan(name.Parent)
End If
End Function
Private Function FindClosestNameWithInitializer(declarators As SeparatedSyntaxList(Of VariableDeclaratorSyntax), position As Integer) As ModifiedIdentifierSyntax
Return FindClosestNode(declarators, position,
Function(declarator)
If declarator.HasInitializer Then
Return declarator.Names(GetItemIndexByPosition(declarator.Names, position))
End If
Return FindClosestNode(declarator.Names, position, Function(idf)
Return If(idf.ArrayBounds IsNot Nothing, idf, Nothing)
End Function)
End Function)
End Function
Private Function FindClosestNode(Of TListNode As SyntaxNode, TResult As SyntaxNode)(nodes As SeparatedSyntaxList(Of TListNode), position As Integer, predicate As Func(Of TListNode, TResult)) As TResult
Dim d = GetItemIndexByPosition(nodes, position)
Dim i = 0
Do
Dim left = d - i
Dim right = d + i
If left < 0 AndAlso right >= nodes.Count Then
Return Nothing
End If
If left >= 0 Then
Dim result = predicate(nodes(left))
If result IsNot Nothing Then
Return result
End If
End If
If right < nodes.Count Then
Dim result = predicate(nodes(right))
If result IsNot Nothing Then
Return result
End If
End If
i += 1
Loop
End Function
Private Function GetItemIndexByPosition(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode), position As Integer) As Integer
For i = list.SeparatorCount - 1 To 0 Step -1
If position > list.GetSeparator(i).SpanStart Then
Return i + 1
End If
Next
Return 0
End Function
Private Function TryCreateSpanForFromClause(fromClause As FromClauseSyntax, position As Integer) As TextSpan?
Dim query = DirectCast(fromClause.Parent, QueryExpressionSyntax)
' If it's not the first from clause, then you can set the breakpoint on the first
' variable.
If query.Clauses.First() IsNot fromClause AndAlso fromClause.Variables.Any() Then
Return TryCreateSpanForNode(fromClause.Variables.First(), position)
End If
' If it is the first from clause, you can only set the breakpoint on the second or
' higher variable.
If query.Clauses.First() Is fromClause AndAlso fromClause.Variables.Count > 1 Then
Return TryCreateSpanForNode(fromClause.Variables(1), position)
End If
Return Nothing
End Function
Private Function TryCreateSpanForFunctionAggregation(functionAggregation As FunctionAggregationSyntax) As TextSpan?
If functionAggregation.Argument IsNot Nothing Then
Return CreateSpan(functionAggregation.Argument)
End If
Return Nothing
End Function
Private Function TryCreateSpanForOrderByClause(orderByClause As OrderByClauseSyntax, position As Integer) As TextSpan?
If orderByClause.Orderings.Any() Then
Return TryCreateSpanForNode(orderByClause.Orderings.First(), position)
End If
Return Nothing
End Function
Private Function TryCreateSpanForOrderingSyntax(orderingSyntax As OrderingSyntax) As TextSpan?
Return CreateSpan(orderingSyntax.Expression)
End Function
Private Function TryCreateSpanForPartitionWhileClauseSyntax(partitionWhileClause As PartitionWhileClauseSyntax) As TextSpan?
Return CreateSpan(partitionWhileClause.Condition)
End Function
Private Function TryCreateSpanForCollectionRangeVariable(collectionRangeVariable As CollectionRangeVariableSyntax) As TextSpan?
If collectionRangeVariable.Parent.Kind = SyntaxKind.FromClause Then
Dim fromClause = DirectCast(collectionRangeVariable.Parent, FromClauseSyntax)
Dim query = DirectCast(fromClause.Parent, QueryExpressionSyntax)
' We can break on this expression if we're not the first clause in a
' query, or if the range variable it not the first range variable in the
' list.
If query.Clauses.First() IsNot fromClause OrElse fromClause.Variables.IndexOf(collectionRangeVariable) <> 0 Then
Return CreateSpan(collectionRangeVariable.Expression)
End If
End If
Return Nothing
End Function
Private Function TryCreateSpanForWhereClause(clause As WhereClauseSyntax) As TextSpan?
Return CreateSpan(clause.Condition)
End Function
Private Function TryCreateSpanForGroupByClause(clause As GroupByClauseSyntax, position As Integer) As TextSpan?
If position < clause.ByKeyword.SpanStart Then
If clause.Items.Count = 1 Then
Return CreateSpan(clause.Items.Single.Expression)
End If
Return TryCreateSpan(clause.Items)
End If
If clause.Keys.Count = 0 Then
Return Nothing
End If
If position >= clause.Keys.First.SpanStart AndAlso position < clause.IntoKeyword.SpanStart Then
If clause.Keys.Count = 1 Then
Return CreateSpan(clause.Keys.Single.Expression)
End If
Return TryCreateSpan(clause.Keys)
End If
Return TextSpan.FromBounds(clause.Keys.First.SpanStart, clause.Span.End)
End Function
Private Function TryCreateSpanForSelectClause(clause As SelectClauseSyntax) As TextSpan?
If clause.Variables.Count = 1 Then
Return CreateSpan(clause.Variables.Single.Expression)
End If
Return TryCreateSpan(clause.Variables)
End Function
Private Function TryCreateSpanForLetClause(clause As LetClauseSyntax, position As Integer) As TextSpan?
Return clause.Variables(GetItemIndexByPosition(clause.Variables, position)).Expression.Span
End Function
Private Function TryCreateSpanForExpression(expression As ExpressionSyntax) As TextSpan?
If IsBreakableExpression(expression) Then
Return CreateSpan(expression)
End If
Return Nothing
End Function
Private Function IsBreakableExpression(expression As ExpressionSyntax) As Boolean
If expression Is Nothing OrElse expression.Parent Is Nothing Then
Return False
End If
Select Case expression.Parent.Kind
Case SyntaxKind.JoinCondition
Dim joinCondition = DirectCast(expression.Parent, JoinConditionSyntax)
Return expression Is joinCondition.Left OrElse expression Is joinCondition.Right
Case SyntaxKind.SingleLineFunctionLambdaExpression
Dim lambda = DirectCast(expression.Parent, SingleLineLambdaExpressionSyntax)
Return expression Is lambda.Body
End Select
Return False
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Text
Imports System.Threading
Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue
Friend Module BreakpointSpans
Friend Function TryGetBreakpointSpan(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken, <Out> ByRef breakpointSpan As TextSpan) As Boolean
Dim source = tree.GetText(cancellationToken)
' If the line is entirely whitespace, then don't set any breakpoint there.
Dim line = source.Lines.GetLineFromPosition(position)
If IsBlank(line) Then
breakpointSpan = Nothing
Return False
End If
' If the user is asking for breakpoint in an inactive region, then just create a line
' breakpoint there.
If tree.IsInInactiveRegion(position, cancellationToken) Then
breakpointSpan = Nothing
Return True
End If
Dim root = tree.GetRoot(cancellationToken)
Return TryGetEnclosingBreakpointSpan(root, position, minLength:=0, breakpointSpan)
End Function
Private Function IsBlank(line As TextLine) As Boolean
Dim text = line.ToString()
For i = 0 To text.Length - 1
If Not SyntaxFacts.IsWhitespace(text(i)) Then
Return False
End If
Next
Return True
End Function
''' <summary>
''' Given a syntax token determines a text span delimited by the closest applicable sequence points
''' encompassing the token.
''' </summary>
''' <remarks>
''' If the span exists it Is possible To place a breakpoint at the given position.
''' </remarks>
''' <param name="minLength">
''' In case there are multiple breakpoint spans starting at the given <paramref name="position"/>,
''' <paramref name="minLength"/> can be used to disambiguate between them.
''' The inner-most available span whose length is at least <paramref name="minLength"/> is returned.
''' </param>
Public Function TryGetEnclosingBreakpointSpan(root As SyntaxNode, position As Integer, minLength As Integer, <Out> ByRef span As TextSpan) As Boolean
Dim node = root.FindToken(position).Parent
Dim candidate As TextSpan? = Nothing
While node IsNot Nothing
Dim breakpointSpan = TryCreateSpanForNode(node, position)
If breakpointSpan.HasValue Then
If breakpointSpan.Value = New TextSpan() Then
Exit While
End If
' the new breakpoint span doesn't alight with the previously found breakpoint span, return the previous one:
If candidate.HasValue AndAlso breakpointSpan.Value.Start <> candidate.Value.Start Then
span = candidate.Value
Return True
End If
' The span length meets the requirement:
If breakpointSpan.Value.Length >= minLength Then
span = breakpointSpan.Value
Return True
End If
candidate = breakpointSpan
End If
node = node.Parent
End While
span = candidate.GetValueOrDefault()
Return candidate.HasValue
End Function
Private Function CreateSpan(node As SyntaxNode) As TextSpan
Return TextSpan.FromBounds(node.SpanStart, node.Span.End)
End Function
Private Function TryCreateSpan(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode)) As TextSpan?
If list.Count = 0 Then
Return Nothing
End If
Return TextSpan.FromBounds(list.First.SpanStart, list.Last.Span.End)
End Function
Private Function TryCreateSpanForNode(node As SyntaxNode, position As Integer) As TextSpan?
Select Case node.Kind
Case SyntaxKind.VariableDeclarator,
SyntaxKind.ModifiedIdentifier
' Handled by parent field or local variable declaration.
Return Nothing
Case SyntaxKind.FieldDeclaration
Dim fieldDeclaration = DirectCast(node, FieldDeclarationSyntax)
Return TryCreateSpanForVariableDeclaration(fieldDeclaration.Modifiers, fieldDeclaration.Declarators, position)
Case SyntaxKind.LocalDeclarationStatement
Dim localDeclaration = DirectCast(node, LocalDeclarationStatementSyntax)
Return TryCreateSpanForVariableDeclaration(localDeclaration.Modifiers, localDeclaration.Declarators, position)
Case SyntaxKind.PropertyStatement
Return TryCreateSpanForPropertyStatement(DirectCast(node, PropertyStatementSyntax))
' Statements that are not executable yet marked with sequence points
Case SyntaxKind.IfStatement,
SyntaxKind.ElseIfStatement,
SyntaxKind.ElseStatement,
SyntaxKind.EndIfStatement,
SyntaxKind.UsingStatement,
SyntaxKind.EndUsingStatement,
SyntaxKind.SyncLockStatement,
SyntaxKind.EndSyncLockStatement,
SyntaxKind.WithStatement,
SyntaxKind.EndWithStatement,
SyntaxKind.SimpleDoStatement, SyntaxKind.DoWhileStatement, SyntaxKind.DoUntilStatement,
SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement,
SyntaxKind.WhileStatement,
SyntaxKind.EndWhileStatement,
SyntaxKind.ForStatement,
SyntaxKind.ForEachStatement,
SyntaxKind.NextStatement,
SyntaxKind.SelectStatement,
SyntaxKind.CaseStatement,
SyntaxKind.CaseElseStatement,
SyntaxKind.EndSelectStatement,
SyntaxKind.TryStatement,
SyntaxKind.CatchStatement,
SyntaxKind.FinallyStatement,
SyntaxKind.EndTryStatement,
SyntaxKind.EndSubStatement,
SyntaxKind.EndFunctionStatement,
SyntaxKind.EndOperatorStatement,
SyntaxKind.EndGetStatement,
SyntaxKind.EndSetStatement,
SyntaxKind.EndAddHandlerStatement,
SyntaxKind.EndRemoveHandlerStatement,
SyntaxKind.EndRaiseEventStatement,
SyntaxKind.FunctionLambdaHeader,
SyntaxKind.SubLambdaHeader
Return CreateSpan(node)
Case SyntaxKind.SubStatement,
SyntaxKind.SubNewStatement,
SyntaxKind.FunctionStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
Return CreateSpanForMethodBase(DirectCast(node, MethodBaseSyntax))
Case SyntaxKind.SingleLineIfStatement
Dim asSingleLine = DirectCast(node, SingleLineIfStatementSyntax)
If position >= asSingleLine.IfKeyword.SpanStart AndAlso position < asSingleLine.ThenKeyword.Span.End Then
Return TextSpan.FromBounds(asSingleLine.IfKeyword.SpanStart, asSingleLine.ThenKeyword.Span.End)
Else
Return CreateSpan(node)
End If
Case SyntaxKind.SingleLineElseClause
Dim asSingleLineElse = DirectCast(node, SingleLineElseClauseSyntax)
Return asSingleLineElse.ElseKeyword.Span
Case SyntaxKind.FunctionAggregation
Return TryCreateSpanForFunctionAggregation(DirectCast(node, FunctionAggregationSyntax))
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression
Return CreateSpan(node)
Case SyntaxKind.SelectClause
Return TryCreateSpanForSelectClause(DirectCast(node, SelectClauseSyntax))
Case SyntaxKind.WhereClause
Return TryCreateSpanForWhereClause(DirectCast(node, WhereClauseSyntax))
Case SyntaxKind.CollectionRangeVariable
Return TryCreateSpanForCollectionRangeVariable(DirectCast(node, CollectionRangeVariableSyntax))
Case SyntaxKind.LetClause
Return TryCreateSpanForLetClause(DirectCast(node, LetClauseSyntax), position)
Case SyntaxKind.GroupByClause
Return TryCreateSpanForGroupByClause(DirectCast(node, GroupByClauseSyntax), position)
Case SyntaxKind.SkipWhileClause,
SyntaxKind.TakeWhileClause
Return TryCreateSpanForPartitionWhileClauseSyntax(DirectCast(node, PartitionWhileClauseSyntax))
Case SyntaxKind.AscendingOrdering,
SyntaxKind.DescendingOrdering
Return TryCreateSpanForOrderingSyntax(DirectCast(node, OrderingSyntax))
Case SyntaxKind.OrderByClause
Return TryCreateSpanForOrderByClause(DirectCast(node, OrderByClauseSyntax), position)
Case SyntaxKind.FromClause
Return TryCreateSpanForFromClause(DirectCast(node, FromClauseSyntax), position)
Case Else
Dim executableStatement = TryCast(node, ExecutableStatementSyntax)
If executableStatement IsNot Nothing Then
Return CreateSpan(node)
End If
Dim expression = TryCast(node, ExpressionSyntax)
If expression IsNot Nothing Then
Return TryCreateSpanForExpression(expression)
End If
Return Nothing
End Select
End Function
Private Function CreateSpanForMethodBase(methodBase As MethodBaseSyntax) As TextSpan
If methodBase.Modifiers.Count = 0 Then
Return TextSpan.FromBounds(methodBase.DeclarationKeyword.SpanStart, methodBase.Span.End)
End If
Return TextSpan.FromBounds(methodBase.Modifiers.First().SpanStart, methodBase.Span.End)
End Function
Private Function TryCreateSpanForPropertyStatement(node As PropertyStatementSyntax) As TextSpan?
If node.Parent.IsKind(SyntaxKind.PropertyBlock) Then
' not an auto-property:
Return Nothing
End If
If node.Initializer IsNot Nothing Then
Return TextSpan.FromBounds(node.Identifier.Span.Start, node.Initializer.Span.End)
End If
If node.AsClause IsNot Nothing AndAlso node.AsClause.IsKind(SyntaxKind.AsNewClause) Then
Return TextSpan.FromBounds(node.Identifier.Span.Start, node.AsClause.Span.End)
End If
Return Nothing
End Function
Private Function TryCreateSpanForVariableDeclaration(modifiers As SyntaxTokenList, declarators As SeparatedSyntaxList(Of VariableDeclaratorSyntax), position As Integer) As TextSpan?
If declarators.Count = 0 Then
Return Nothing
End If
If modifiers.Any(SyntaxKind.ConstKeyword) Then
Return New TextSpan()
End If
Dim name = FindClosestNameWithInitializer(declarators, position)
If name Is Nothing Then
Return New TextSpan()
End If
If name.ArrayBounds IsNot Nothing OrElse DirectCast(name.Parent, VariableDeclaratorSyntax).Names.Count > 1 Then
Return CreateSpan(name)
Else
Return CreateSpan(name.Parent)
End If
End Function
Private Function FindClosestNameWithInitializer(declarators As SeparatedSyntaxList(Of VariableDeclaratorSyntax), position As Integer) As ModifiedIdentifierSyntax
Return FindClosestNode(declarators, position,
Function(declarator)
If declarator.HasInitializer Then
Return declarator.Names(GetItemIndexByPosition(declarator.Names, position))
End If
Return FindClosestNode(declarator.Names, position, Function(idf)
Return If(idf.ArrayBounds IsNot Nothing, idf, Nothing)
End Function)
End Function)
End Function
Private Function FindClosestNode(Of TListNode As SyntaxNode, TResult As SyntaxNode)(nodes As SeparatedSyntaxList(Of TListNode), position As Integer, predicate As Func(Of TListNode, TResult)) As TResult
Dim d = GetItemIndexByPosition(nodes, position)
Dim i = 0
Do
Dim left = d - i
Dim right = d + i
If left < 0 AndAlso right >= nodes.Count Then
Return Nothing
End If
If left >= 0 Then
Dim result = predicate(nodes(left))
If result IsNot Nothing Then
Return result
End If
End If
If right < nodes.Count Then
Dim result = predicate(nodes(right))
If result IsNot Nothing Then
Return result
End If
End If
i += 1
Loop
End Function
Private Function GetItemIndexByPosition(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode), position As Integer) As Integer
For i = list.SeparatorCount - 1 To 0 Step -1
If position > list.GetSeparator(i).SpanStart Then
Return i + 1
End If
Next
Return 0
End Function
Private Function TryCreateSpanForFromClause(fromClause As FromClauseSyntax, position As Integer) As TextSpan?
Dim query = DirectCast(fromClause.Parent, QueryExpressionSyntax)
' If it's not the first from clause, then you can set the breakpoint on the first
' variable.
If query.Clauses.First() IsNot fromClause AndAlso fromClause.Variables.Any() Then
Return TryCreateSpanForNode(fromClause.Variables.First(), position)
End If
' If it is the first from clause, you can only set the breakpoint on the second or
' higher variable.
If query.Clauses.First() Is fromClause AndAlso fromClause.Variables.Count > 1 Then
Return TryCreateSpanForNode(fromClause.Variables(1), position)
End If
Return Nothing
End Function
Private Function TryCreateSpanForFunctionAggregation(functionAggregation As FunctionAggregationSyntax) As TextSpan?
If functionAggregation.Argument IsNot Nothing Then
Return CreateSpan(functionAggregation.Argument)
End If
Return Nothing
End Function
Private Function TryCreateSpanForOrderByClause(orderByClause As OrderByClauseSyntax, position As Integer) As TextSpan?
If orderByClause.Orderings.Any() Then
Return TryCreateSpanForNode(orderByClause.Orderings.First(), position)
End If
Return Nothing
End Function
Private Function TryCreateSpanForOrderingSyntax(orderingSyntax As OrderingSyntax) As TextSpan?
Return CreateSpan(orderingSyntax.Expression)
End Function
Private Function TryCreateSpanForPartitionWhileClauseSyntax(partitionWhileClause As PartitionWhileClauseSyntax) As TextSpan?
Return CreateSpan(partitionWhileClause.Condition)
End Function
Private Function TryCreateSpanForCollectionRangeVariable(collectionRangeVariable As CollectionRangeVariableSyntax) As TextSpan?
If collectionRangeVariable.Parent.Kind = SyntaxKind.FromClause Then
Dim fromClause = DirectCast(collectionRangeVariable.Parent, FromClauseSyntax)
Dim query = DirectCast(fromClause.Parent, QueryExpressionSyntax)
' We can break on this expression if we're not the first clause in a
' query, or if the range variable it not the first range variable in the
' list.
If query.Clauses.First() IsNot fromClause OrElse fromClause.Variables.IndexOf(collectionRangeVariable) <> 0 Then
Return CreateSpan(collectionRangeVariable.Expression)
End If
End If
Return Nothing
End Function
Private Function TryCreateSpanForWhereClause(clause As WhereClauseSyntax) As TextSpan?
Return CreateSpan(clause.Condition)
End Function
Private Function TryCreateSpanForGroupByClause(clause As GroupByClauseSyntax, position As Integer) As TextSpan?
If position < clause.ByKeyword.SpanStart Then
If clause.Items.Count = 1 Then
Return CreateSpan(clause.Items.Single.Expression)
End If
Return TryCreateSpan(clause.Items)
End If
If clause.Keys.Count = 0 Then
Return Nothing
End If
If position >= clause.Keys.First.SpanStart AndAlso position < clause.IntoKeyword.SpanStart Then
If clause.Keys.Count = 1 Then
Return CreateSpan(clause.Keys.Single.Expression)
End If
Return TryCreateSpan(clause.Keys)
End If
Return TextSpan.FromBounds(clause.Keys.First.SpanStart, clause.Span.End)
End Function
Private Function TryCreateSpanForSelectClause(clause As SelectClauseSyntax) As TextSpan?
If clause.Variables.Count = 1 Then
Return CreateSpan(clause.Variables.Single.Expression)
End If
Return TryCreateSpan(clause.Variables)
End Function
Private Function TryCreateSpanForLetClause(clause As LetClauseSyntax, position As Integer) As TextSpan?
Return clause.Variables(GetItemIndexByPosition(clause.Variables, position)).Expression.Span
End Function
Private Function TryCreateSpanForExpression(expression As ExpressionSyntax) As TextSpan?
If IsBreakableExpression(expression) Then
Return CreateSpan(expression)
End If
Return Nothing
End Function
Private Function IsBreakableExpression(expression As ExpressionSyntax) As Boolean
If expression Is Nothing OrElse expression.Parent Is Nothing Then
Return False
End If
Select Case expression.Parent.Kind
Case SyntaxKind.JoinCondition
Dim joinCondition = DirectCast(expression.Parent, JoinConditionSyntax)
Return expression Is joinCondition.Left OrElse expression Is joinCondition.Right
Case SyntaxKind.SingleLineFunctionLambdaExpression
Dim lambda = DirectCast(expression.Parent, SingleLineLambdaExpressionSyntax)
Return expression Is lambda.Body
End Select
Return False
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Analyzers/CSharp/CodeFixes/MisplacedUsingDirectives/MisplacedUsingDirectivesCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
#if CODE_STYLE
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#else
using Microsoft.CodeAnalysis.Options;
#endif
namespace Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives
{
/// <summary>
/// Implements a code fix for all misplaced using statements.
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MoveMisplacedUsingDirectives)]
[Shared]
internal sealed partial class MisplacedUsingDirectivesCodeFixProvider : CodeFixProvider
{
private static readonly SyntaxAnnotation s_usingPlacementCodeFixAnnotation = new SyntaxAnnotation(nameof(s_usingPlacementCodeFixAnnotation));
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public MisplacedUsingDirectivesCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.MoveMisplacedUsingDirectivesDiagnosticId);
public override FixAllProvider GetFixAllProvider()
{
// Since we work on an entire document at a time fixing all contained diagnostics, the batch fixer should not have merge conflicts.
return WellKnownFixAllProviders.BatchFixer;
}
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var cancellationToken = context.CancellationToken;
var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var compilationUnit = (CompilationUnitSyntax)syntaxRoot;
#if CODE_STYLE
var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(syntaxRoot.SyntaxTree, cancellationToken);
#else
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
#endif
// Read the preferred placement option and verify if it can be applied to this code file.
// There are cases where we will not be able to fix the diagnostic and the user will need to resolve
// it manually.
var (placement, preferPreservation) = DeterminePlacement(compilationUnit, options);
if (preferPreservation)
return;
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(
new MoveMisplacedUsingsCodeAction(token => GetTransformedDocumentAsync(document, compilationUnit, placement, token)),
diagnostic);
}
}
internal static async Task<Document> TransformDocumentIfRequiredAsync(Document document, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var compilationUnit = (CompilationUnitSyntax)syntaxRoot;
#if CODE_STYLE
var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(syntaxRoot.SyntaxTree, cancellationToken);
#else
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
#endif
var (placement, preferPreservation) = DeterminePlacement(compilationUnit, options);
if (preferPreservation)
{
return document;
}
return await GetTransformedDocumentAsync(document, compilationUnit, placement, cancellationToken).ConfigureAwait(false);
}
private static async Task<Document> GetTransformedDocumentAsync(
Document document,
CompilationUnitSyntax compilationUnit,
AddImportPlacement placement,
CancellationToken cancellationToken)
{
var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>();
// Expand usings so that they can be properly simplified after they are relocated.
var compilationUnitWithExpandedUsings = await ExpandUsingDirectivesAsync(document, compilationUnit, cancellationToken).ConfigureAwait(false);
// Remove the file header from the compilation unit so that we do not lose it when making changes to usings.
var (compilationUnitWithoutHeader, fileHeader) = RemoveFileHeader(compilationUnitWithExpandedUsings, syntaxFactsService);
// A blanket warning that this codefix may change code so that it does not compile.
var warningAnnotation = WarningAnnotation.Create(CSharpAnalyzersResources.Warning_colon_Moving_using_directives_may_change_code_meaning);
var newCompilationUnit = placement == AddImportPlacement.InsideNamespace
? MoveUsingsInsideNamespace(compilationUnitWithoutHeader, warningAnnotation)
: MoveUsingsOutsideNamespaces(compilationUnitWithoutHeader, warningAnnotation);
// Re-attach the header now that using have been moved and LeadingTrivia is no longer being altered.
var newCompilationUnitWithHeader = AddFileHeader(newCompilationUnit, fileHeader);
var newDocument = document.WithSyntaxRoot(newCompilationUnitWithHeader);
// Simplify usings now that they have been moved and are in the proper context.
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
return await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, options, cancellationToken).ConfigureAwait(false);
}
private static async Task<CompilationUnitSyntax> ExpandUsingDirectivesAsync(Document document, CompilationUnitSyntax containerNode, CancellationToken cancellationToken)
{
// Get all using directives so they can be expanded at one time.
var allUsingDirectives = containerNode
.DescendantNodes(node => node is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax)
.OfType<UsingDirectiveSyntax>();
// Create a map between the original node and the future expanded node.
var expandUsingDirectiveTasks = allUsingDirectives.ToDictionary(
usingDirective => (SyntaxNode)usingDirective,
usingDirective => ExpandUsingDirectiveAsync(document, usingDirective, cancellationToken));
// Wait for all using directives to be expanded
await Task.WhenAll(expandUsingDirectiveTasks.Values).ConfigureAwait(false);
// Replace using directives with their expanded version.
return containerNode.ReplaceNodes(
expandUsingDirectiveTasks.Keys,
(node, _) => expandUsingDirectiveTasks[node].Result);
}
private static async Task<SyntaxNode> ExpandUsingDirectiveAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var usingDirective = (UsingDirectiveSyntax)node;
var newName = await Simplifier.ExpandAsync(usingDirective.Name, document, cancellationToken: cancellationToken).ConfigureAwait(false);
return usingDirective.WithName(newName);
}
private static CompilationUnitSyntax MoveUsingsInsideNamespace(CompilationUnitSyntax compilationUnit, SyntaxAnnotation warningAnnotation)
{
// Get the compilation unit usings and set them up to format when moved.
var usingsToAdd = compilationUnit.Usings.Select(
directive => directive.WithAdditionalAnnotations(Formatter.Annotation, warningAnnotation));
// Remove usings and fix leading trivia for compilation unit.
var compilationUnitWithoutUsings = compilationUnit.WithUsings(default);
var compilationUnitWithoutBlankLine = RemoveLeadingBlankLinesFromFirstMember(compilationUnitWithoutUsings);
// Fix the leading trivia for the namespace declaration.
var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)compilationUnitWithoutBlankLine.Members[0];
var namespaceDeclarationWithBlankLine = EnsureLeadingBlankLineBeforeFirstMember(namespaceDeclaration);
// Update the namespace declaration with the usings from the compilation unit.
var newUsings = namespaceDeclarationWithBlankLine.Usings.InsertRange(0, usingsToAdd);
var namespaceDeclarationWithUsings = namespaceDeclarationWithBlankLine.WithUsings(newUsings);
// Update the compilation unit with the new namespace declaration
return compilationUnitWithoutBlankLine.ReplaceNode(namespaceDeclaration, namespaceDeclarationWithUsings);
}
private static CompilationUnitSyntax MoveUsingsOutsideNamespaces(CompilationUnitSyntax compilationUnit, SyntaxAnnotation warningAnnotation)
{
var namespaceDeclarations = compilationUnit.Members.OfType<BaseNamespaceDeclarationSyntax>();
var namespaceDeclarationMap = namespaceDeclarations.ToDictionary(
namespaceDeclaration => namespaceDeclaration, namespaceDeclaration => RemoveUsingsFromNamespace(namespaceDeclaration));
// Replace the namespace declarations in the compilation with the ones without using directives.
var compilationUnitWithReplacedNamespaces = compilationUnit.ReplaceNodes(
namespaceDeclarations, (node, _) => namespaceDeclarationMap[node].namespaceWithoutUsings);
// Get the using directives from the namespaces and set them up to format when moved.
var usingsToAdd = namespaceDeclarationMap.Values.SelectMany(result => result.usingsFromNamespace)
.Select(directive => directive.WithAdditionalAnnotations(Formatter.Annotation, warningAnnotation));
var (deduplicatedUsings, orphanedTrivia) = RemoveDuplicateUsings(compilationUnit.Usings, usingsToAdd.ToImmutableArray());
// Update the compilation unit with the usings from the namespace declaration.
var newUsings = compilationUnitWithReplacedNamespaces.Usings.AddRange(deduplicatedUsings);
var compilationUnitWithUsings = compilationUnitWithReplacedNamespaces.WithUsings(newUsings);
// Fix the leading trivia for the compilation unit.
var compilationUnitWithSeparatorLine = EnsureLeadingBlankLineBeforeFirstMember(compilationUnitWithUsings);
if (!orphanedTrivia.Any())
{
return compilationUnitWithSeparatorLine;
}
// Add leading trivia that was orphaned from removing duplicate using directives to the first member in the compilation unit.
var firstMember = compilationUnitWithSeparatorLine.Members[0];
return compilationUnitWithSeparatorLine.ReplaceNode(firstMember, firstMember.WithPrependedLeadingTrivia(orphanedTrivia));
}
private static (BaseNamespaceDeclarationSyntax namespaceWithoutUsings, IEnumerable<UsingDirectiveSyntax> usingsFromNamespace) RemoveUsingsFromNamespace(
BaseNamespaceDeclarationSyntax usingContainer)
{
var namespaceDeclarations = usingContainer.Members.OfType<BaseNamespaceDeclarationSyntax>();
var namespaceDeclarationMap = namespaceDeclarations.ToDictionary(
namespaceDeclaration => namespaceDeclaration, namespaceDeclaration => RemoveUsingsFromNamespace(namespaceDeclaration));
// Get the using directives from the namespaces.
var usingsFromNamespaces = namespaceDeclarationMap.Values.SelectMany(result => result.usingsFromNamespace);
var allUsings = usingContainer.Usings.AsEnumerable().Concat(usingsFromNamespaces);
// Replace the namespace declarations in the compilation with the ones without using directives.
var namespaceDeclarationWithReplacedNamespaces = usingContainer.ReplaceNodes(
namespaceDeclarations, (node, _) => namespaceDeclarationMap[node].namespaceWithoutUsings);
// Remove usings and fix leading trivia for namespace declaration.
var namespaceDeclarationWithoutUsings = namespaceDeclarationWithReplacedNamespaces.WithUsings(default);
var namespaceDeclarationWithoutBlankLine = RemoveLeadingBlankLinesFromFirstMember(namespaceDeclarationWithoutUsings);
return (namespaceDeclarationWithoutBlankLine, allUsings);
}
private static (IEnumerable<UsingDirectiveSyntax> deduplicatedUsings, IEnumerable<SyntaxTrivia> orphanedTrivia) RemoveDuplicateUsings(
IEnumerable<UsingDirectiveSyntax> existingUsings,
ImmutableArray<UsingDirectiveSyntax> usingsToAdd)
{
var seenUsings = existingUsings.ToList();
var deduplicatedUsingsBuilder = ImmutableArray.CreateBuilder<UsingDirectiveSyntax>();
var orphanedTrivia = Enumerable.Empty<SyntaxTrivia>();
foreach (var usingDirective in usingsToAdd)
{
// Check is the node is a duplicate.
if (seenUsings.Any(seenUsingDirective => seenUsingDirective.IsEquivalentTo(usingDirective, topLevel: false)))
{
// If there was trivia from the duplicate node, check if any of the trivia is necessary to keep.
var leadingTrivia = usingDirective.GetLeadingTrivia();
if (leadingTrivia.Any(trivia => !trivia.IsWhitespaceOrEndOfLine()))
{
// Capture the meaningful trivia so we can prepend it to the next kept node.
orphanedTrivia = orphanedTrivia.Concat(leadingTrivia);
}
}
else
{
seenUsings.Add(usingDirective);
// Add any orphaned trivia to this node.
deduplicatedUsingsBuilder.Add(usingDirective.WithPrependedLeadingTrivia(orphanedTrivia));
orphanedTrivia = Enumerable.Empty<SyntaxTrivia>();
}
}
return (deduplicatedUsingsBuilder.ToImmutable(), orphanedTrivia);
}
private static SyntaxList<MemberDeclarationSyntax> GetMembers(SyntaxNode node)
=> node switch
{
CompilationUnitSyntax compilationUnit => compilationUnit.Members,
BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Members,
_ => throw ExceptionUtilities.UnexpectedValue(node)
};
private static TSyntaxNode RemoveLeadingBlankLinesFromFirstMember<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode
{
var members = GetMembers(node);
if (members.Count == 0)
{
return node;
}
var firstMember = members.First();
var firstMemberTrivia = firstMember.GetLeadingTrivia();
// If there is no leading trivia, then return the node as it is.
if (firstMemberTrivia.Count == 0)
{
return node;
}
var newTrivia = SplitIntoLines(firstMemberTrivia)
.SkipWhile(trivia => trivia.All(t => t.IsWhitespaceOrEndOfLine()) && trivia.Last().IsKind(SyntaxKind.EndOfLineTrivia))
.SelectMany(t => t);
var newFirstMember = firstMember.WithLeadingTrivia(newTrivia);
return node.ReplaceNode(firstMember, newFirstMember);
}
private static IEnumerable<IEnumerable<SyntaxTrivia>> SplitIntoLines(SyntaxTriviaList triviaList)
{
var index = 0;
for (var i = 0; i < triviaList.Count; i++)
{
if (triviaList[i].IsEndOfLine())
{
yield return triviaList.TakeRange(index, i);
index = i + 1;
}
}
if (index < triviaList.Count)
{
yield return triviaList.TakeRange(index, triviaList.Count - 1);
}
}
private static TSyntaxNode EnsureLeadingBlankLineBeforeFirstMember<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode
{
var members = GetMembers(node);
if (members.Count == 0)
{
return node;
}
var firstMember = members.First();
var firstMemberTrivia = firstMember.GetLeadingTrivia();
// If the first member already contains a leading new line then, this will already break up the usings from these members.
if (firstMemberTrivia.Count > 0 && firstMemberTrivia.First().IsKind(SyntaxKind.EndOfLineTrivia))
{
return node;
}
var newFirstMember = firstMember.WithLeadingTrivia(firstMemberTrivia.Insert(0, SyntaxFactory.CarriageReturnLineFeed));
return node.ReplaceNode(firstMember, newFirstMember);
}
private static (AddImportPlacement placement, bool preferPreservation) DeterminePlacement(CompilationUnitSyntax compilationUnit, OptionSet options)
{
var codeStyleOption = options.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement);
var placement = codeStyleOption.Value;
var preferPreservation = codeStyleOption.Notification == NotificationOption2.None;
if (preferPreservation || placement == AddImportPlacement.OutsideNamespace)
return (placement, preferPreservation);
// Determine if we can safely apply the InsideNamespace preference.
// Do not offer a code fix when there are multiple namespaces in the source file. When there are
// nested namespaces it is not clear if inner usings can be moved outwards without causing
// collisions. Also, when moving usings inwards it is complex to determine which namespaces they
// should be moved into.
// Only move using declarations inside the namespace when
// - There are no global attributes
// - There are no type definitions outside of the single top level namespace
// - There is only a single namespace declared at the top level
var forcePreservation = compilationUnit.AttributeLists.Any()
|| compilationUnit.Members.Count > 1
|| !HasOneNamespace(compilationUnit);
return (AddImportPlacement.InsideNamespace, forcePreservation);
}
private static bool HasOneNamespace(CompilationUnitSyntax compilationUnit)
{
// Find all the NamespaceDeclarations
var allNamespaces = compilationUnit
.DescendantNodes(node => node is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax)
.OfType<BaseNamespaceDeclarationSyntax>();
// To determine if there are multiple namespaces we only need to look for at least two.
return allNamespaces.Take(2).Count() == 1;
}
private static (CompilationUnitSyntax compilationUnitWithoutHeader, ImmutableArray<SyntaxTrivia> header) RemoveFileHeader(
CompilationUnitSyntax syntaxRoot, ISyntaxFactsService syntaxFactsService)
{
var fileHeader = syntaxFactsService.GetFileBanner(syntaxRoot);
var leadingTrivia = syntaxRoot.GetLeadingTrivia();
for (var i = fileHeader.Length - 1; i >= 0; i--)
{
leadingTrivia = leadingTrivia.RemoveAt(i);
}
var newCompilationUnit = syntaxRoot.WithLeadingTrivia(leadingTrivia);
return (newCompilationUnit, fileHeader);
}
private static CompilationUnitSyntax AddFileHeader(CompilationUnitSyntax compilationUnit, ImmutableArray<SyntaxTrivia> fileHeader)
{
if (fileHeader.IsEmpty)
{
return compilationUnit;
}
// Add leading trivia to the first token.
var firstToken = compilationUnit.GetFirstToken(includeZeroWidth: true);
var newLeadingTrivia = firstToken.LeadingTrivia.InsertRange(0, fileHeader);
var newFirstToken = firstToken.WithLeadingTrivia(newLeadingTrivia);
return compilationUnit.ReplaceToken(firstToken, newFirstToken);
}
private class MoveMisplacedUsingsCodeAction : CustomCodeActions.DocumentChangeAction
{
public MoveMisplacedUsingsCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Move_misplaced_using_directives, createChangedDocument, nameof(CSharpAnalyzersResources.Move_misplaced_using_directives))
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
#if CODE_STYLE
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#else
using Microsoft.CodeAnalysis.Options;
#endif
namespace Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives
{
/// <summary>
/// Implements a code fix for all misplaced using statements.
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MoveMisplacedUsingDirectives)]
[Shared]
internal sealed partial class MisplacedUsingDirectivesCodeFixProvider : CodeFixProvider
{
private static readonly SyntaxAnnotation s_usingPlacementCodeFixAnnotation = new SyntaxAnnotation(nameof(s_usingPlacementCodeFixAnnotation));
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public MisplacedUsingDirectivesCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.MoveMisplacedUsingDirectivesDiagnosticId);
public override FixAllProvider GetFixAllProvider()
{
// Since we work on an entire document at a time fixing all contained diagnostics, the batch fixer should not have merge conflicts.
return WellKnownFixAllProviders.BatchFixer;
}
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var cancellationToken = context.CancellationToken;
var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var compilationUnit = (CompilationUnitSyntax)syntaxRoot;
#if CODE_STYLE
var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(syntaxRoot.SyntaxTree, cancellationToken);
#else
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
#endif
// Read the preferred placement option and verify if it can be applied to this code file.
// There are cases where we will not be able to fix the diagnostic and the user will need to resolve
// it manually.
var (placement, preferPreservation) = DeterminePlacement(compilationUnit, options);
if (preferPreservation)
return;
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(
new MoveMisplacedUsingsCodeAction(token => GetTransformedDocumentAsync(document, compilationUnit, GetAllUsingDirectives(compilationUnit), placement, token)),
diagnostic);
}
}
internal static async Task<Document> TransformDocumentIfRequiredAsync(Document document, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var compilationUnit = (CompilationUnitSyntax)syntaxRoot;
#if CODE_STYLE
var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(syntaxRoot.SyntaxTree, cancellationToken);
#else
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
#endif
var (placement, preferPreservation) = DeterminePlacement(compilationUnit, options);
if (preferPreservation)
{
return document;
}
// We are called from a diagnostic, but also for all new documents, so check if there are any usings at all
// otherwise there is nothing to do.
var allUsingDirectives = GetAllUsingDirectives(compilationUnit);
if (allUsingDirectives.Count == 0)
{
return document;
}
return await GetTransformedDocumentAsync(document, compilationUnit, allUsingDirectives, placement, cancellationToken).ConfigureAwait(false);
}
private static ImmutableList<UsingDirectiveSyntax> GetAllUsingDirectives(CompilationUnitSyntax compilationUnit)
{
return compilationUnit
.DescendantNodes(node => node is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax)
.OfType<UsingDirectiveSyntax>().ToImmutableList();
}
private static async Task<Document> GetTransformedDocumentAsync(
Document document,
CompilationUnitSyntax compilationUnit,
IEnumerable<UsingDirectiveSyntax> allUsingDirectives,
AddImportPlacement placement,
CancellationToken cancellationToken)
{
var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>();
// Expand usings so that they can be properly simplified after they are relocated.
var compilationUnitWithExpandedUsings = await ExpandUsingDirectivesAsync(document, compilationUnit, allUsingDirectives, cancellationToken).ConfigureAwait(false);
// Remove the file header from the compilation unit so that we do not lose it when making changes to usings.
var (compilationUnitWithoutHeader, fileHeader) = RemoveFileHeader(compilationUnitWithExpandedUsings, syntaxFactsService);
// A blanket warning that this codefix may change code so that it does not compile.
var warningAnnotation = WarningAnnotation.Create(CSharpAnalyzersResources.Warning_colon_Moving_using_directives_may_change_code_meaning);
var newCompilationUnit = placement == AddImportPlacement.InsideNamespace
? MoveUsingsInsideNamespace(compilationUnitWithoutHeader, warningAnnotation)
: MoveUsingsOutsideNamespaces(compilationUnitWithoutHeader, warningAnnotation);
// Re-attach the header now that using have been moved and LeadingTrivia is no longer being altered.
var newCompilationUnitWithHeader = AddFileHeader(newCompilationUnit, fileHeader);
var newDocument = document.WithSyntaxRoot(newCompilationUnitWithHeader);
// Simplify usings now that they have been moved and are in the proper context.
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
return await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, options, cancellationToken).ConfigureAwait(false);
}
private static async Task<CompilationUnitSyntax> ExpandUsingDirectivesAsync(Document document, CompilationUnitSyntax containerNode, IEnumerable<UsingDirectiveSyntax> allUsingDirectives, CancellationToken cancellationToken)
{
// Create a map between the original node and the future expanded node.
var expandUsingDirectiveTasks = allUsingDirectives.ToDictionary(
usingDirective => (SyntaxNode)usingDirective,
usingDirective => ExpandUsingDirectiveAsync(document, usingDirective, cancellationToken));
// Wait for all using directives to be expanded
await Task.WhenAll(expandUsingDirectiveTasks.Values).ConfigureAwait(false);
// Replace using directives with their expanded version.
return containerNode.ReplaceNodes(
expandUsingDirectiveTasks.Keys,
(node, _) => expandUsingDirectiveTasks[node].Result);
}
private static async Task<SyntaxNode> ExpandUsingDirectiveAsync(Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var usingDirective = (UsingDirectiveSyntax)node;
var newName = await Simplifier.ExpandAsync(usingDirective.Name, document, cancellationToken: cancellationToken).ConfigureAwait(false);
return usingDirective.WithName(newName);
}
private static CompilationUnitSyntax MoveUsingsInsideNamespace(CompilationUnitSyntax compilationUnit, SyntaxAnnotation warningAnnotation)
{
// Get the compilation unit usings and set them up to format when moved.
var usingsToAdd = compilationUnit.Usings.Select(
directive => directive.WithAdditionalAnnotations(Formatter.Annotation, warningAnnotation));
// Remove usings and fix leading trivia for compilation unit.
var compilationUnitWithoutUsings = compilationUnit.WithUsings(default);
var compilationUnitWithoutBlankLine = RemoveLeadingBlankLinesFromFirstMember(compilationUnitWithoutUsings);
// Fix the leading trivia for the namespace declaration.
var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)compilationUnitWithoutBlankLine.Members[0];
var namespaceDeclarationWithBlankLine = EnsureLeadingBlankLineBeforeFirstMember(namespaceDeclaration);
// Update the namespace declaration with the usings from the compilation unit.
var newUsings = namespaceDeclarationWithBlankLine.Usings.InsertRange(0, usingsToAdd);
var namespaceDeclarationWithUsings = namespaceDeclarationWithBlankLine.WithUsings(newUsings);
// Update the compilation unit with the new namespace declaration
return compilationUnitWithoutBlankLine.ReplaceNode(namespaceDeclaration, namespaceDeclarationWithUsings);
}
private static CompilationUnitSyntax MoveUsingsOutsideNamespaces(CompilationUnitSyntax compilationUnit, SyntaxAnnotation warningAnnotation)
{
var namespaceDeclarations = compilationUnit.Members.OfType<BaseNamespaceDeclarationSyntax>();
var namespaceDeclarationMap = namespaceDeclarations.ToDictionary(
namespaceDeclaration => namespaceDeclaration, namespaceDeclaration => RemoveUsingsFromNamespace(namespaceDeclaration));
// Replace the namespace declarations in the compilation with the ones without using directives.
var compilationUnitWithReplacedNamespaces = compilationUnit.ReplaceNodes(
namespaceDeclarations, (node, _) => namespaceDeclarationMap[node].namespaceWithoutUsings);
// Get the using directives from the namespaces and set them up to format when moved.
var usingsToAdd = namespaceDeclarationMap.Values.SelectMany(result => result.usingsFromNamespace)
.Select(directive => directive.WithAdditionalAnnotations(Formatter.Annotation, warningAnnotation));
var (deduplicatedUsings, orphanedTrivia) = RemoveDuplicateUsings(compilationUnit.Usings, usingsToAdd.ToImmutableArray());
// Update the compilation unit with the usings from the namespace declaration.
var newUsings = compilationUnitWithReplacedNamespaces.Usings.AddRange(deduplicatedUsings);
var compilationUnitWithUsings = compilationUnitWithReplacedNamespaces.WithUsings(newUsings);
// Fix the leading trivia for the compilation unit.
var compilationUnitWithSeparatorLine = EnsureLeadingBlankLineBeforeFirstMember(compilationUnitWithUsings);
if (!orphanedTrivia.Any())
{
return compilationUnitWithSeparatorLine;
}
// Add leading trivia that was orphaned from removing duplicate using directives to the first member in the compilation unit.
var firstMember = compilationUnitWithSeparatorLine.Members[0];
return compilationUnitWithSeparatorLine.ReplaceNode(firstMember, firstMember.WithPrependedLeadingTrivia(orphanedTrivia));
}
private static (BaseNamespaceDeclarationSyntax namespaceWithoutUsings, IEnumerable<UsingDirectiveSyntax> usingsFromNamespace) RemoveUsingsFromNamespace(
BaseNamespaceDeclarationSyntax usingContainer)
{
var namespaceDeclarations = usingContainer.Members.OfType<BaseNamespaceDeclarationSyntax>();
var namespaceDeclarationMap = namespaceDeclarations.ToDictionary(
namespaceDeclaration => namespaceDeclaration, namespaceDeclaration => RemoveUsingsFromNamespace(namespaceDeclaration));
// Get the using directives from the namespaces.
var usingsFromNamespaces = namespaceDeclarationMap.Values.SelectMany(result => result.usingsFromNamespace);
var allUsings = usingContainer.Usings.AsEnumerable().Concat(usingsFromNamespaces);
// Replace the namespace declarations in the compilation with the ones without using directives.
var namespaceDeclarationWithReplacedNamespaces = usingContainer.ReplaceNodes(
namespaceDeclarations, (node, _) => namespaceDeclarationMap[node].namespaceWithoutUsings);
// Remove usings and fix leading trivia for namespace declaration.
var namespaceDeclarationWithoutUsings = namespaceDeclarationWithReplacedNamespaces.WithUsings(default);
var namespaceDeclarationWithoutBlankLine = RemoveLeadingBlankLinesFromFirstMember(namespaceDeclarationWithoutUsings);
return (namespaceDeclarationWithoutBlankLine, allUsings);
}
private static (IEnumerable<UsingDirectiveSyntax> deduplicatedUsings, IEnumerable<SyntaxTrivia> orphanedTrivia) RemoveDuplicateUsings(
IEnumerable<UsingDirectiveSyntax> existingUsings,
ImmutableArray<UsingDirectiveSyntax> usingsToAdd)
{
var seenUsings = existingUsings.ToList();
var deduplicatedUsingsBuilder = ImmutableArray.CreateBuilder<UsingDirectiveSyntax>();
var orphanedTrivia = Enumerable.Empty<SyntaxTrivia>();
foreach (var usingDirective in usingsToAdd)
{
// Check is the node is a duplicate.
if (seenUsings.Any(seenUsingDirective => seenUsingDirective.IsEquivalentTo(usingDirective, topLevel: false)))
{
// If there was trivia from the duplicate node, check if any of the trivia is necessary to keep.
var leadingTrivia = usingDirective.GetLeadingTrivia();
if (leadingTrivia.Any(trivia => !trivia.IsWhitespaceOrEndOfLine()))
{
// Capture the meaningful trivia so we can prepend it to the next kept node.
orphanedTrivia = orphanedTrivia.Concat(leadingTrivia);
}
}
else
{
seenUsings.Add(usingDirective);
// Add any orphaned trivia to this node.
deduplicatedUsingsBuilder.Add(usingDirective.WithPrependedLeadingTrivia(orphanedTrivia));
orphanedTrivia = Enumerable.Empty<SyntaxTrivia>();
}
}
return (deduplicatedUsingsBuilder.ToImmutable(), orphanedTrivia);
}
private static SyntaxList<MemberDeclarationSyntax> GetMembers(SyntaxNode node)
=> node switch
{
CompilationUnitSyntax compilationUnit => compilationUnit.Members,
BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Members,
_ => throw ExceptionUtilities.UnexpectedValue(node)
};
private static TSyntaxNode RemoveLeadingBlankLinesFromFirstMember<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode
{
var members = GetMembers(node);
if (members.Count == 0)
{
return node;
}
var firstMember = members.First();
var firstMemberTrivia = firstMember.GetLeadingTrivia();
// If there is no leading trivia, then return the node as it is.
if (firstMemberTrivia.Count == 0)
{
return node;
}
var newTrivia = SplitIntoLines(firstMemberTrivia)
.SkipWhile(trivia => trivia.All(t => t.IsWhitespaceOrEndOfLine()) && trivia.Last().IsKind(SyntaxKind.EndOfLineTrivia))
.SelectMany(t => t);
var newFirstMember = firstMember.WithLeadingTrivia(newTrivia);
return node.ReplaceNode(firstMember, newFirstMember);
}
private static IEnumerable<IEnumerable<SyntaxTrivia>> SplitIntoLines(SyntaxTriviaList triviaList)
{
var index = 0;
for (var i = 0; i < triviaList.Count; i++)
{
if (triviaList[i].IsEndOfLine())
{
yield return triviaList.TakeRange(index, i);
index = i + 1;
}
}
if (index < triviaList.Count)
{
yield return triviaList.TakeRange(index, triviaList.Count - 1);
}
}
private static TSyntaxNode EnsureLeadingBlankLineBeforeFirstMember<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode
{
var members = GetMembers(node);
if (members.Count == 0)
{
return node;
}
var firstMember = members.First();
var firstMemberTrivia = firstMember.GetLeadingTrivia();
// If the first member already contains a leading new line then, this will already break up the usings from these members.
if (firstMemberTrivia.Count > 0 && firstMemberTrivia.First().IsKind(SyntaxKind.EndOfLineTrivia))
{
return node;
}
var newFirstMember = firstMember.WithLeadingTrivia(firstMemberTrivia.Insert(0, SyntaxFactory.CarriageReturnLineFeed));
return node.ReplaceNode(firstMember, newFirstMember);
}
private static (AddImportPlacement placement, bool preferPreservation) DeterminePlacement(CompilationUnitSyntax compilationUnit, OptionSet options)
{
var codeStyleOption = options.GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement);
var placement = codeStyleOption.Value;
var preferPreservation = codeStyleOption.Notification == NotificationOption2.None;
if (preferPreservation || placement == AddImportPlacement.OutsideNamespace)
return (placement, preferPreservation);
// Determine if we can safely apply the InsideNamespace preference.
// Do not offer a code fix when there are multiple namespaces in the source file. When there are
// nested namespaces it is not clear if inner usings can be moved outwards without causing
// collisions. Also, when moving usings inwards it is complex to determine which namespaces they
// should be moved into.
// Only move using declarations inside the namespace when
// - There are no global attributes
// - There are no type definitions outside of the single top level namespace
// - There is only a single namespace declared at the top level
var forcePreservation = compilationUnit.AttributeLists.Any()
|| compilationUnit.Members.Count > 1
|| !HasOneNamespace(compilationUnit);
return (AddImportPlacement.InsideNamespace, forcePreservation);
}
private static bool HasOneNamespace(CompilationUnitSyntax compilationUnit)
{
// Find all the NamespaceDeclarations
var allNamespaces = compilationUnit
.DescendantNodes(node => node is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax)
.OfType<BaseNamespaceDeclarationSyntax>();
// To determine if there are multiple namespaces we only need to look for at least two.
return allNamespaces.Take(2).Count() == 1;
}
private static (CompilationUnitSyntax compilationUnitWithoutHeader, ImmutableArray<SyntaxTrivia> header) RemoveFileHeader(
CompilationUnitSyntax syntaxRoot, ISyntaxFactsService syntaxFactsService)
{
var fileHeader = syntaxFactsService.GetFileBanner(syntaxRoot);
var leadingTrivia = syntaxRoot.GetLeadingTrivia();
for (var i = fileHeader.Length - 1; i >= 0; i--)
{
leadingTrivia = leadingTrivia.RemoveAt(i);
}
var newCompilationUnit = syntaxRoot.WithLeadingTrivia(leadingTrivia);
return (newCompilationUnit, fileHeader);
}
private static CompilationUnitSyntax AddFileHeader(CompilationUnitSyntax compilationUnit, ImmutableArray<SyntaxTrivia> fileHeader)
{
if (fileHeader.IsEmpty)
{
return compilationUnit;
}
// Add leading trivia to the first token.
var firstToken = compilationUnit.GetFirstToken(includeZeroWidth: true);
var newLeadingTrivia = firstToken.LeadingTrivia.InsertRange(0, fileHeader);
var newFirstToken = firstToken.WithLeadingTrivia(newLeadingTrivia);
return compilationUnit.ReplaceToken(firstToken, newFirstToken);
}
private class MoveMisplacedUsingsCodeAction : CustomCodeActions.DocumentChangeAction
{
public MoveMisplacedUsingsCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Move_misplaced_using_directives, createChangedDocument, nameof(CSharpAnalyzersResources.Move_misplaced_using_directives))
{
}
}
}
}
| 1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Analyzers/Core/CodeFixes/FileHeaders/AbstractFileHeaderCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
#if !CODE_STYLE
using Microsoft.CodeAnalysis.Formatting;
#endif
namespace Microsoft.CodeAnalysis.FileHeaders
{
internal abstract class AbstractFileHeaderCodeFixProvider : CodeFixProvider
{
protected abstract AbstractFileHeaderHelper FileHeaderHelper { get; }
protected abstract ISyntaxFacts SyntaxFacts { get; }
protected abstract ISyntaxKinds SyntaxKinds { get; }
protected abstract SyntaxTrivia EndOfLine(string text);
public override ImmutableArray<string> FixableDiagnosticIds { get; }
= ImmutableArray.Create(IDEDiagnosticIds.FileHeaderMismatch);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(
new MyCodeAction(cancellationToken => GetTransformedDocumentAsync(context.Document, cancellationToken)),
diagnostic);
}
return Task.CompletedTask;
}
private async Task<Document> GetTransformedDocumentAsync(Document document, CancellationToken cancellationToken)
=> document.WithSyntaxRoot(await GetTransformedSyntaxRootAsync(document, cancellationToken).ConfigureAwait(false));
private Task<SyntaxNode> GetTransformedSyntaxRootAsync(Document document, CancellationToken cancellationToken)
{
#if CODE_STYLE
var newLineText = Environment.NewLine;
#else
var newLineText = document.Project.Solution.Options.GetOption(FormattingOptions.NewLine, document.Project.Language);
#endif
var newLineTrivia = EndOfLine(newLineText);
return GetTransformedSyntaxRootAsync(SyntaxFacts, FileHeaderHelper, newLineTrivia, document, cancellationToken);
}
internal static async Task<SyntaxNode> GetTransformedSyntaxRootAsync(ISyntaxFacts syntaxFacts, AbstractFileHeaderHelper fileHeaderHelper, SyntaxTrivia newLineTrivia, Document document, CancellationToken cancellationToken)
{
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
if (!document.Project.AnalyzerOptions.TryGetEditorConfigOption<string>(CodeStyleOptions2.FileHeaderTemplate, tree, out var fileHeaderTemplate)
|| string.IsNullOrEmpty(fileHeaderTemplate))
{
// This exception would show up as a gold bar, but as indicated we do not believe this is reachable.
throw ExceptionUtilities.Unreachable;
}
var expectedFileHeader = fileHeaderTemplate.Replace("{fileName}", Path.GetFileName(document.FilePath));
var fileHeader = fileHeaderHelper.ParseFileHeader(root);
SyntaxNode newSyntaxRoot;
if (fileHeader.IsMissing)
{
newSyntaxRoot = AddHeader(syntaxFacts, fileHeaderHelper, newLineTrivia, root, expectedFileHeader);
}
else
{
newSyntaxRoot = ReplaceHeader(syntaxFacts, fileHeaderHelper, newLineTrivia, root, expectedFileHeader);
}
return newSyntaxRoot;
}
private static SyntaxNode ReplaceHeader(ISyntaxFacts syntaxFacts, AbstractFileHeaderHelper fileHeaderHelper, SyntaxTrivia newLineTrivia, SyntaxNode root, string expectedFileHeader)
{
// Skip single line comments, whitespace, and end of line trivia until a blank line is encountered.
var triviaList = root.GetLeadingTrivia();
// True if the current line is blank so far (empty or whitespace); otherwise, false. The first line is
// assumed to not be blank, which allows the analysis to detect a file header which follows a blank line at
// the top of the file.
var onBlankLine = false;
// The set of indexes to remove from 'triviaList'. After removing these indexes, the remaining trivia (if
// any) will be preserved in the document along with the replacement header.
var removalList = new List<int>();
// The number of spaces to indent the new header. This is expected to match the indentation of the header
// which is being replaced.
var leadingSpaces = string.Empty;
// The number of spaces found so far on the current line. This will become 'leadingSpaces' if the spaces are
// followed by a comment which is considered a header comment.
var possibleLeadingSpaces = string.Empty;
// Need to do this with index so we get the line endings correct.
for (var i = 0; i < triviaList.Count; i++)
{
var triviaLine = triviaList[i];
if (triviaLine.RawKind == syntaxFacts.SyntaxKinds.SingleLineCommentTrivia)
{
if (possibleLeadingSpaces != string.Empty)
{
// One or more spaces precedes the comment. Keep track of these spaces so we can indent the new
// header by the same amount.
leadingSpaces = possibleLeadingSpaces;
}
removalList.Add(i);
onBlankLine = false;
}
else if (triviaLine.RawKind == syntaxFacts.SyntaxKinds.WhitespaceTrivia)
{
if (leadingSpaces == string.Empty)
{
possibleLeadingSpaces = triviaLine.ToFullString();
}
removalList.Add(i);
}
else if (triviaLine.RawKind == syntaxFacts.SyntaxKinds.EndOfLineTrivia)
{
possibleLeadingSpaces = string.Empty;
removalList.Add(i);
if (onBlankLine)
{
break;
}
else
{
onBlankLine = true;
}
}
else
{
break;
}
}
// Remove copyright lines in reverse order.
for (var i = removalList.Count - 1; i >= 0; i--)
{
triviaList = triviaList.RemoveAt(removalList[i]);
}
var newHeaderTrivia = CreateNewHeader(syntaxFacts, leadingSpaces + fileHeaderHelper.CommentPrefix, expectedFileHeader, newLineTrivia.ToFullString());
// Add a blank line and any remaining preserved trivia after the header.
newHeaderTrivia = newHeaderTrivia.Add(newLineTrivia).Add(newLineTrivia).AddRange(triviaList);
// Insert header at top of the file.
return root.WithLeadingTrivia(newHeaderTrivia);
}
private static SyntaxNode AddHeader(ISyntaxFacts syntaxFacts, AbstractFileHeaderHelper fileHeaderHelper, SyntaxTrivia newLineTrivia, SyntaxNode root, string expectedFileHeader)
{
var newTrivia = CreateNewHeader(syntaxFacts, fileHeaderHelper.CommentPrefix, expectedFileHeader, newLineTrivia.ToFullString()).Add(newLineTrivia).Add(newLineTrivia);
// Skip blank lines already at the beginning of the document, since we add our own
var leadingTrivia = root.GetLeadingTrivia();
var skipCount = 0;
for (var i = 0; i < leadingTrivia.Count; i++)
{
if (leadingTrivia[i].RawKind == syntaxFacts.SyntaxKinds.EndOfLineTrivia)
{
skipCount = i + 1;
}
else if (leadingTrivia[i].RawKind != syntaxFacts.SyntaxKinds.WhitespaceTrivia)
{
break;
}
}
newTrivia = newTrivia.AddRange(leadingTrivia.Skip(skipCount));
return root.WithLeadingTrivia(newTrivia);
}
private static SyntaxTriviaList CreateNewHeader(ISyntaxFacts syntaxFacts, string prefixWithLeadingSpaces, string expectedFileHeader, string newLineText)
{
var copyrightText = GetCopyrightText(prefixWithLeadingSpaces, expectedFileHeader, newLineText);
var newHeader = copyrightText;
return syntaxFacts.ParseLeadingTrivia(newHeader);
}
private static string GetCopyrightText(string prefixWithLeadingSpaces, string copyrightText, string newLineText)
{
copyrightText = copyrightText.Replace("\r\n", "\n");
var lines = copyrightText.Split('\n');
return string.Join(newLineText, lines.Select(line =>
{
// Rewrite the lines of the header as comments without trailing whitespace.
if (string.IsNullOrEmpty(line))
{
// This is a blank line of the header. We want the prefix indicating the line is a comment, but no
// additional trailing whitespace.
return prefixWithLeadingSpaces;
}
else
{
// This is a normal line of the header. We want the prefix, followed by a single space, and then the
// text of the header line.
return prefixWithLeadingSpaces + " " + line;
}
}));
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CodeFixesResources.Add_file_header, createChangedDocument, nameof(AbstractFileHeaderCodeFixProvider))
{
}
}
public override FixAllProvider GetFixAllProvider()
=> FixAllProvider.Create(async (context, document, diagnostics) =>
{
if (diagnostics.IsEmpty)
return null;
return await this.GetTransformedDocumentAsync(document, context.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.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
#if !CODE_STYLE
using Microsoft.CodeAnalysis.Formatting;
#endif
namespace Microsoft.CodeAnalysis.FileHeaders
{
internal abstract class AbstractFileHeaderCodeFixProvider : CodeFixProvider
{
protected abstract AbstractFileHeaderHelper FileHeaderHelper { get; }
protected abstract ISyntaxFacts SyntaxFacts { get; }
protected abstract ISyntaxKinds SyntaxKinds { get; }
protected abstract SyntaxTrivia EndOfLine(string text);
public override ImmutableArray<string> FixableDiagnosticIds { get; }
= ImmutableArray.Create(IDEDiagnosticIds.FileHeaderMismatch);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(
new MyCodeAction(cancellationToken => GetTransformedDocumentAsync(context.Document, cancellationToken)),
diagnostic);
}
return Task.CompletedTask;
}
private async Task<Document> GetTransformedDocumentAsync(Document document, CancellationToken cancellationToken)
=> document.WithSyntaxRoot(await GetTransformedSyntaxRootAsync(document, cancellationToken).ConfigureAwait(false));
private Task<SyntaxNode> GetTransformedSyntaxRootAsync(Document document, CancellationToken cancellationToken)
{
#if CODE_STYLE
var newLineText = Environment.NewLine;
#else
var newLineText = document.Project.Solution.Options.GetOption(FormattingOptions.NewLine, document.Project.Language);
#endif
var newLineTrivia = EndOfLine(newLineText);
return GetTransformedSyntaxRootAsync(SyntaxFacts, FileHeaderHelper, newLineTrivia, document, fileHeaderTemplate: null, cancellationToken);
}
internal static async Task<SyntaxNode> GetTransformedSyntaxRootAsync(ISyntaxFacts syntaxFacts, AbstractFileHeaderHelper fileHeaderHelper, SyntaxTrivia newLineTrivia, Document document, string? fileHeaderTemplate, CancellationToken cancellationToken)
{
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
// If we weren't given a header lets get the one from editorconfig
if (fileHeaderTemplate is null &&
!document.Project.AnalyzerOptions.TryGetEditorConfigOption<string>(CodeStyleOptions2.FileHeaderTemplate, tree, out fileHeaderTemplate))
{
// No header supplied, no editorconfig setting, nothing to do
return root;
}
if (string.IsNullOrEmpty(fileHeaderTemplate))
{
// Header template is empty, nothing to do. This shouldn't be possible if this method is called in
// reaction to a diagnostic, but this method is also used when creating new documents so lets be defensive.
return root;
}
var expectedFileHeader = fileHeaderTemplate.Replace("{fileName}", Path.GetFileName(document.FilePath));
var fileHeader = fileHeaderHelper.ParseFileHeader(root);
SyntaxNode newSyntaxRoot;
if (fileHeader.IsMissing)
{
newSyntaxRoot = AddHeader(syntaxFacts, fileHeaderHelper, newLineTrivia, root, expectedFileHeader);
}
else
{
newSyntaxRoot = ReplaceHeader(syntaxFacts, fileHeaderHelper, newLineTrivia, root, expectedFileHeader);
}
return newSyntaxRoot;
}
private static SyntaxNode ReplaceHeader(ISyntaxFacts syntaxFacts, AbstractFileHeaderHelper fileHeaderHelper, SyntaxTrivia newLineTrivia, SyntaxNode root, string expectedFileHeader)
{
// Skip single line comments, whitespace, and end of line trivia until a blank line is encountered.
var triviaList = root.GetLeadingTrivia();
// True if the current line is blank so far (empty or whitespace); otherwise, false. The first line is
// assumed to not be blank, which allows the analysis to detect a file header which follows a blank line at
// the top of the file.
var onBlankLine = false;
// The set of indexes to remove from 'triviaList'. After removing these indexes, the remaining trivia (if
// any) will be preserved in the document along with the replacement header.
var removalList = new List<int>();
// The number of spaces to indent the new header. This is expected to match the indentation of the header
// which is being replaced.
var leadingSpaces = string.Empty;
// The number of spaces found so far on the current line. This will become 'leadingSpaces' if the spaces are
// followed by a comment which is considered a header comment.
var possibleLeadingSpaces = string.Empty;
// Need to do this with index so we get the line endings correct.
for (var i = 0; i < triviaList.Count; i++)
{
var triviaLine = triviaList[i];
if (triviaLine.RawKind == syntaxFacts.SyntaxKinds.SingleLineCommentTrivia)
{
if (possibleLeadingSpaces != string.Empty)
{
// One or more spaces precedes the comment. Keep track of these spaces so we can indent the new
// header by the same amount.
leadingSpaces = possibleLeadingSpaces;
}
removalList.Add(i);
onBlankLine = false;
}
else if (triviaLine.RawKind == syntaxFacts.SyntaxKinds.WhitespaceTrivia)
{
if (leadingSpaces == string.Empty)
{
possibleLeadingSpaces = triviaLine.ToFullString();
}
removalList.Add(i);
}
else if (triviaLine.RawKind == syntaxFacts.SyntaxKinds.EndOfLineTrivia)
{
possibleLeadingSpaces = string.Empty;
removalList.Add(i);
if (onBlankLine)
{
break;
}
else
{
onBlankLine = true;
}
}
else
{
break;
}
}
// Remove copyright lines in reverse order.
for (var i = removalList.Count - 1; i >= 0; i--)
{
triviaList = triviaList.RemoveAt(removalList[i]);
}
var newHeaderTrivia = CreateNewHeader(syntaxFacts, leadingSpaces + fileHeaderHelper.CommentPrefix, expectedFileHeader, newLineTrivia.ToFullString());
// Add a blank line and any remaining preserved trivia after the header.
newHeaderTrivia = newHeaderTrivia.Add(newLineTrivia).Add(newLineTrivia).AddRange(triviaList);
// Insert header at top of the file.
return root.WithLeadingTrivia(newHeaderTrivia);
}
private static SyntaxNode AddHeader(ISyntaxFacts syntaxFacts, AbstractFileHeaderHelper fileHeaderHelper, SyntaxTrivia newLineTrivia, SyntaxNode root, string expectedFileHeader)
{
var newTrivia = CreateNewHeader(syntaxFacts, fileHeaderHelper.CommentPrefix, expectedFileHeader, newLineTrivia.ToFullString()).Add(newLineTrivia).Add(newLineTrivia);
// Skip blank lines already at the beginning of the document, since we add our own
var leadingTrivia = root.GetLeadingTrivia();
var skipCount = 0;
for (var i = 0; i < leadingTrivia.Count; i++)
{
if (leadingTrivia[i].RawKind == syntaxFacts.SyntaxKinds.EndOfLineTrivia)
{
skipCount = i + 1;
}
else if (leadingTrivia[i].RawKind != syntaxFacts.SyntaxKinds.WhitespaceTrivia)
{
break;
}
}
newTrivia = newTrivia.AddRange(leadingTrivia.Skip(skipCount));
return root.WithLeadingTrivia(newTrivia);
}
private static SyntaxTriviaList CreateNewHeader(ISyntaxFacts syntaxFacts, string prefixWithLeadingSpaces, string expectedFileHeader, string newLineText)
{
var copyrightText = GetCopyrightText(prefixWithLeadingSpaces, expectedFileHeader, newLineText);
var newHeader = copyrightText;
return syntaxFacts.ParseLeadingTrivia(newHeader);
}
private static string GetCopyrightText(string prefixWithLeadingSpaces, string copyrightText, string newLineText)
{
copyrightText = copyrightText.Replace("\r\n", "\n");
var lines = copyrightText.Split('\n');
return string.Join(newLineText, lines.Select(line =>
{
// Rewrite the lines of the header as comments without trailing whitespace.
if (string.IsNullOrEmpty(line))
{
// This is a blank line of the header. We want the prefix indicating the line is a comment, but no
// additional trailing whitespace.
return prefixWithLeadingSpaces;
}
else
{
// This is a normal line of the header. We want the prefix, followed by a single space, and then the
// text of the header line.
return prefixWithLeadingSpaces + " " + line;
}
}));
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CodeFixesResources.Add_file_header, createChangedDocument, nameof(AbstractFileHeaderCodeFixProvider))
{
}
}
public override FixAllProvider GetFixAllProvider()
=> FixAllProvider.Create(async (context, document, diagnostics) =>
{
if (diagnostics.IsEmpty)
return null;
return await this.GetTransformedDocumentAsync(document, context.CancellationToken).ConfigureAwait(false);
});
}
}
| 1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/CSharpTest/Diagnostics/GenerateType/GenerateTypeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.GenerateType;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.GenerateTypeTests
{
public partial class GenerateTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public GenerateTypeTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new GenerateTypeCodeFixProvider());
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> codeActions)
=> FlattenActions(codeActions);
// TODO: Requires WPF due to IInlineRenameService dependency (https://github.com/dotnet/roslyn/issues/46153)
protected override TestComposition GetComposition()
=> EditorTestCompositions.EditorFeaturesWpf
.AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService))
.AddParts(typeof(MockDiagnosticUpdateSourceRegistrationService));
#region Generate Class
#region Generics
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeParameterFromArgumentInferT()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void Main()
{
[|Goo<int>|] f;
}
}",
@"class Program
{
void Main()
{
Goo<int> f;
}
}
internal class Goo<T>
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromTypeParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
System.Action<[|Employee|]> employees;
}",
@"class Class
{
System.Action<Employee> employees;
private class Employee
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClause()
{
await TestInRegularAndScriptAsync(
@"class EmployeeList<T> where T : [|Employee|], new()
{
}",
@"class EmployeeList<T> where T : Employee, new()
{
}
internal class Employee
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGeneratePublicClassFromASingleConstraintClause()
{
await TestInRegularAndScriptAsync(
@"public class EmployeeList<T> where T : [|Employee|], new()
{
}",
@"public class EmployeeList<T> where T : Employee, new()
{
}
public class Employee
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGenerateClassFromConstructorConstraint()
{
await TestMissingInRegularAndScriptAsync(
@"class EmployeeList<T> where T : Employee, [|new()|]
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromMultipleTypeConstraintClauses()
{
await TestInRegularAndScriptAsync(
@"class Derived<T, U>
where U : struct
where T : [|Base|], new()
{
}",
@"class Derived<T, U>
where U : struct
where T : Base, new()
{
}
internal class Base
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGeneratePublicClassFromMultipleTypeConstraintClauses()
{
await TestInRegularAndScriptAsync(
@"public class Derived<T, U>
where U : struct
where T : [|Base|], new()
{
}",
@"public class Derived<T, U>
where U : struct
where T : Base, new()
{
}
public class Base
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGenerateClassFromClassOrStructConstraint()
{
await TestMissingInRegularAndScriptAsync(
@"class Derived<T, U>
where U : [|struct|]
where T : Base, new()
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAbsenceOfGenerateIntoInvokingTypeForConstraintList()
{
await TestActionCountAsync(
@"class EmployeeList<T> where T : [|Employee|]
{
}",
count: 3,
parameters: new TestParameters(Options.Regular));
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClauseInterface()
{
await TestInRegularAndScriptAsync(
@"interface IEmployeeList<T> where T : [|Employee|], new()
{
}",
@"interface IEmployeeList<T> where T : Employee, new()
{
}
internal class Employee
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGeneratePublicClassFromASingleConstraintClausePublicInterface()
{
await TestInRegularAndScriptAsync(
@"public interface IEmployeeList<T> where T : [|Employee|], new()
{
}",
@"public interface IEmployeeList<T> where T : Employee, new()
{
}
public class Employee
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClauseInternalDelegate()
{
await TestInRegularAndScriptAsync(
@"class Employee
{
internal delegate void Action<T>() where T : [|Command|];
}",
@"class Employee
{
internal delegate void Action<T>() where T : Command;
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClausePublicDelegate()
{
await TestInRegularAndScriptAsync(
@"class Employee
{
public delegate void Action<T>() where T : [|Command|];
}",
@"class Employee
{
public delegate void Action<T>() where T : Command;
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClauseInternalMethod()
{
await TestInRegularAndScriptAsync(
@"class Employee
{
internal void Action<T>() where T : [|Command|] {}
}",
@"class Employee
{
internal void Action<T>() where T : Command {}
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClausePublicMethod()
{
await TestInRegularAndScriptAsync(
@"class Employee
{
public void Action<T>() where T : [|Command|] {}
}",
@"class Employee
{
public void Action<T>() where T : Command {}
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClauseMethod()
{
await TestInRegularAndScriptAsync(
@"class Employee
{
void Action<T>() where T : [|Command|] {}
}",
@"class Employee
{
void Action<T>() where T : Command {}
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClauseMethodInInterface()
{
await TestInRegularAndScriptAsync(
@"interface Employee
{
void Action<T>() where T : [|Command|] {}
}",
@"interface Employee
{
void Action<T>() where T : Command {}
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
[InlineData("public", "internal", "internal")]
[InlineData("public", "private", "internal")]
[InlineData("internal", "protected", "internal")]
[InlineData("public", "protected internal", "public")]
[InlineData("protected", "protected", "public")]
[InlineData("protected internal", "protected", "public")]
[InlineData("protected", "protected private", "internal")]
[InlineData("protected private", "protected", "internal")]
public async Task TestGenerateInternalClassFromASingleConstraintClauseNestedClass(string middleAccessibility, string accessibility, string generatedAccessibility)
{
await TestInRegularAndScriptAsync(
$@"public class A
{{
{middleAccessibility} class B
{{
{accessibility} class C<T> where T : [|D|]
{{
}}
}}
}}",
$@"public class A
{{
{middleAccessibility} class B
{{
{accessibility} class C<T> where T : D
{{
}}
}}
}}
{generatedAccessibility} class D
{{
}}",
index: 1);
}
#endregion
#region Lambdas
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromParenthesizedLambdaExpressionsParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
Func<Employee, int, bool> l = ([|Employee|] e, int age) => e.Age > age;
}",
@"class Class
{
Func<Employee, int, bool> l = (Employee e, int age) => e.Age > age;
private class Employee
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromParenthesizedLambdaExpressionsBody()
{
await TestInRegularAndScriptAsync(
@"class Class
{
System.Action<Class, int> l = (Class e, int age) => {
[|Wage|] w;
};
}",
@"class Class
{
System.Action<Class, int> l = (Class e, int age) => {
Wage w;
};
private class Wage
{
}
}",
index: 2);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromFieldDeclarationIntoSameType()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|Goo|] f;
}",
@"class Class
{
Goo f;
private class Goo
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromNullableFieldDeclarationIntoSameType()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
class Class
{
[|Goo?|] f;
}",
@"#nullable enable
class Class
{
Goo? f;
private class Goo
{
}
}",
index: 2);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromFieldDeclarationIntoGlobalNamespace()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Program { void Main ( ) { [|Goo|] f ; } } ",
@"internal class Goo
{
}",
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "Goo.cs");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromFieldDeclarationIntoCustomNamespace()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Class { [|TestNamespace|].Goo f; }",
@"namespace TestNamespace
{
internal class Goo
{
}
}",
expectedContainers: ImmutableArray.Create("TestNamespace"),
expectedDocumentName: "Goo.cs");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromFieldDeclarationIntoSameNamespace()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|Goo|] f;
}",
@"class Class
{
Goo f;
}
internal class Goo
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassWithCtorFromObjectCreation()
{
await TestInRegularAndScriptAsync(
@"class Class
{
Goo f = new [|Goo|]();
}",
@"class Class
{
Goo f = new Goo();
private class Goo
{
public Goo()
{
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassWithCtorFromObjectCreationWithTuple()
{
await TestInRegularAndScriptAsync(
@"class Class
{
var f = new [|Generated|]((1, 2));
}",
@"class Class
{
var f = new Generated((1, 2));
private class Generated
{
private (int, int) p;
public Generated((int, int) p)
{
this.p = p;
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassWithCtorFromObjectCreationWithTupleWithNames()
{
await TestInRegularAndScriptAsync(
@"class Class
{
var f = new [|Generated|]((a: 1, b: 2, 3));
}",
@"class Class
{
var f = new Generated((a: 1, b: 2, 3));
private class Generated
{
private (int a, int b, int) p;
public Generated((int a, int b, int) p)
{
this.p = p;
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromBaseList()
{
await TestInRegularAndScriptAsync(
@"class Class : [|BaseClass|]
{
}",
@"class Class : BaseClass
{
}
internal class BaseClass
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromMethodParameters()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method([|Goo|] f)
{
}
}",
@"class Class
{
void Method(Goo f)
{
}
private class Goo
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromMethodReturnType()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|Goo|] Method()
{
}
}",
@"class Class
{
Goo Method()
{
}
private class Goo
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromAttribute()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[[|Obsolete|]]
void Method()
{
}
}",
@"using System;
class Class
{
[Obsolete]
void Method()
{
}
private class ObsoleteAttribute : Attribute
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromExpandedAttribute()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[[|ObsoleteAttribute|]]
void Method()
{
}
}",
@"using System;
class Class
{
[ObsoleteAttribute]
void Method()
{
}
private class ObsoleteAttribute : Attribute
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromCatchClause()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
try
{
}
catch ([|ExType|])
{
}
}
}",
@"using System;
using System.Runtime.Serialization;
class Class
{
void Method()
{
try
{
}
catch (ExType)
{
}
}
[Serializable]
private class ExType : Exception
{
public ExType()
{
}
public ExType(string message) : base(message)
{
}
public ExType(string message, Exception innerException) : base(message, innerException)
{
}
protected ExType(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromThrowStatement()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
throw new [|ExType|]();
}
}",
@"using System;
using System.Runtime.Serialization;
class Class
{
void Method()
{
throw new ExType();
}
[Serializable]
private class ExType : Exception
{
public ExType()
{
}
public ExType(string message) : base(message)
{
}
public ExType(string message, Exception innerException) : base(message, innerException)
{
}
protected ExType(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromThrowStatementWithDifferentArg()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
throw new [|ExType|](1);
}
}",
@"using System;
using System.Runtime.Serialization;
class Class
{
void Method()
{
throw new ExType(1);
}
[Serializable]
private class ExType : Exception
{
private int v;
public ExType()
{
}
public ExType(int v)
{
this.v = v;
}
public ExType(string message) : base(message)
{
}
public ExType(string message, Exception innerException) : base(message, innerException)
{
}
protected ExType(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromThrowStatementWithMatchingArg()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
throw new [|ExType|](""message"");
}
}",
@"using System;
using System.Runtime.Serialization;
class Class
{
void Method()
{
throw new ExType(""message"");
}
[Serializable]
private class ExType : Exception
{
public ExType()
{
}
public ExType(string message) : base(message)
{
}
public ExType(string message, Exception innerException) : base(message, innerException)
{
}
protected ExType(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAbsenceOfGenerateIntoInvokingTypeForBaseList()
{
await TestActionCountAsync(
@"class Class : [|BaseClass|]
{
}",
count: 3,
parameters: new TestParameters(Options.Regular));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromUsingStatement()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
using ([|Goo|] f = new Goo())
{
}
}
}",
@"class Class
{
void Method()
{
using (Goo f = new Goo())
{
}
}
private class Goo
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromForeachStatement()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
foreach ([|Employee|] e in empList)
{
}
}
}",
@"class Class
{
void Method()
{
foreach (Employee e in empList)
{
}
}
private class Employee
{
}
}",
index: 2);
}
[WorkItem(538346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538346")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassWhereKeywordBecomesTypeName()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|@class|] c;
}",
@"class Class
{
@class c;
private class @class
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGenerateClassOnContextualKeyword()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|@Goo|] c;
}",
@"class Class
{
@Goo c;
private class Goo
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGenerateClassOnFrameworkTypes()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void Method()
{
[|System|].Console.Write(5);
}
}");
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void Method()
{
System.[|Console|].Write(5);
}
}");
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void Method()
{
System.Console.[|Write|](5);
}
}");
}
[WorkItem(538409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538409")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateIntoRightPart()
{
await TestInRegularAndScriptAsync(
@"partial class Class
{
}
partial class Class
{
[|C|] c;
}",
@"partial class Class
{
}
partial class Class
{
C c;
private class C
{
}
}",
index: 2);
}
[WorkItem(538408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538408")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeIntoCompilationUnit()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|C|] c;
void Main()
{
}
}",
@"class Class
{
C c;
void Main()
{
}
}
internal class C
{
}",
index: 1);
}
[WorkItem(538408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538408")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeIntoNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
class Class
{
[|C|] c;
void Main()
{
}
}
}",
@"namespace N
{
class Class
{
C c;
void Main()
{
}
}
internal class C
{
}
}",
index: 1);
}
[WorkItem(538115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538115")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeWithPreprocessor()
{
await TestInRegularAndScriptAsync(
@"class C
{
#if true
void Goo([|A|] x) { }
#else
#endif
}",
@"class C
{
#if true
void Goo(A x) { }
private class A
{
}
#else
#endif
}",
index: 2);
}
[WorkItem(538495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538495")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeIntoContainingNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
class Class
{
N.[|C|] c;
}
}",
@"namespace N
{
class Class
{
N.C c;
}
internal class C
{
}
}",
index: 1);
}
[WorkItem(538516, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538516")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromIntoNewNamespace()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Class { static void Main(string[] args) { [|N|].C c; } }",
@"namespace N
{
internal class C
{
}
}",
expectedContainers: ImmutableArray.Create("N"),
expectedDocumentName: "C.cs");
}
[WorkItem(538558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538558")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGlobalAlias()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void Method()
{
[|global|]::System.String s;
}
}");
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void Method()
{
global::[|System|].String s;
}
}");
}
[WorkItem(538069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538069")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeFromArrayCreation1()
{
await TestAsync(
@"class A
{
void Goo()
{
A[] x = new [|C|][] { };
}
}",
@"class A
{
void Goo()
{
A[] x = new C[] { };
}
}
internal class C : A
{
}",
index: 1,
parseOptions: null);
}
[WorkItem(538069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538069")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeFromArrayCreation2()
{
await TestAsync(
@"class A
{
void Goo()
{
A[][] x = new [|C|][][] { };
}
}",
@"class A
{
void Goo()
{
A[][] x = new C[][] { };
}
}
internal class C : A
{
}",
index: 1,
parseOptions: null);
}
[WorkItem(538069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538069")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeFromArrayCreation3()
{
await TestAsync(
@"class A
{
void Goo()
{
A[] x = new [|C|][][] { };
}
}",
@"class A
{
void Goo()
{
A[] x = new C[][] { };
}
}
internal class C
{
}",
index: 1,
parseOptions: null);
}
[WorkItem(539329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539329")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestNotInUsingDirective()
{
await TestMissingInRegularAndScriptAsync(
@"using [|A|];");
await TestMissingInRegularAndScriptAsync(
@"using [|A.B|];");
await TestMissingInRegularAndScriptAsync(
@"using [|A|].B;");
await TestMissingInRegularAndScriptAsync(
@"using A.[|B|];");
await TestMissingInRegularAndScriptAsync(
@"using X = [|A|];");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateSimpleConstructor()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M()
{
new [|T|]();
}
}",
@"class Class
{
void M()
{
new T();
}
}
internal class T
{
public T()
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithValueParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M()
{
new [|T|](1);
}
}",
@"class Class
{
void M()
{
new T(1);
}
}
internal class T
{
private int v;
public T(int v)
{
this.v = v;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithTwoValueParameters()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M()
{
new [|T|](1, """");
}
}",
@"class Class
{
void M()
{
new T(1, """");
}
}
internal class T
{
private int v1;
private string v2;
public T(int v1, string v2)
{
this.v1 = v1;
this.v2 = v2;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNullableParameter()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
class Class
{
void M()
{
string? s = null;
new [|T|](s);
}
}",
@"#nullable enable
class Class
{
void M()
{
string? s = null;
new [|T|](s);
}
}
internal class T
{
private string? s;
public T(string? s)
{
this.s = s;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNullableParameterThatIsNotNull()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
class Class
{
void M()
{
string? s = ""asdf"";
new [|T|](s);
}
}",
@"#nullable enable
class Class
{
void M()
{
string? s = ""asdf"";
new [|T|](s);
}
}
internal class T
{
private string s;
public T(string s)
{
this.s = s;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNamedParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M()
{
new [|T|](arg: 1);
}
}",
@"class Class
{
void M()
{
new T(arg: 1);
}
}
internal class T
{
private int arg;
public T(int arg)
{
this.arg = arg;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithRefParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
new [|T|](ref i);
}
}",
@"class Class
{
void M(int i)
{
new T(ref i);
}
}
internal class T
{
private int i;
public T(ref int i)
{
this.i = i;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i, bool b)
{
new [|T|](out i, ref b, null);
}
}",
@"class Class
{
void M(int i, bool b)
{
new T(out i, ref b, null);
}
}
internal class T
{
private bool b;
private object p;
public T(out int i, ref bool b, object p)
{
i = 0;
this.b = b;
this.p = p;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(string s)
{
new [|T|](out s);
}
}",
@"class Class
{
void M(string s)
{
new T(out s);
}
}
internal class T
{
public T(out string s)
{
s = null;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters2_CSharp7()
{
await TestInRegularAndScriptAsync(
@"using System;
class Class
{
void M(DateTime d)
{
new [|T|](out d);
}
}",
@"using System;
class Class
{
void M(DateTime d)
{
new T(out d);
}
}
internal class T
{
public T(out DateTime d)
{
d = default(DateTime);
}
}",
index: 1,
parseOptions: TestOptions.Regular7);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters2()
{
await TestInRegularAndScriptAsync(
@"using System;
class Class
{
void M(DateTime d)
{
new [|T|](out d);
}
}",
@"using System;
class Class
{
void M(DateTime d)
{
new T(out d);
}
}
internal class T
{
public T(out DateTime d)
{
d = default;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters3()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
void M(IList<int> d)
{
new [|T|](out d);
}
}",
@"using System.Collections.Generic;
class Class
{
void M(IList<int> d)
{
new T(out d);
}
}
internal class T
{
public T(out IList<int> d)
{
d = null;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters4()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int? d)
{
new [|T|](out d);
}
}",
@"class Class
{
void M(int? d)
{
new T(out d);
}
}
internal class T
{
public T(out int? d)
{
d = null;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters5()
{
await TestInRegularAndScriptAsync(
@"class Class<X>
{
void M(X d)
{
new [|T|](out d);
}
}",
@"class Class<X>
{
void M(X d)
{
new T(out d);
}
}
internal class T
{
public T(out object d)
{
d = null;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters6_CSharp7()
{
await TestInRegularAndScriptAsync(
@"class Class<X>
{
void M(X d)
{
new [|T|](out d);
}
}",
@"class Class<X>
{
void M(X d)
{
new T(out d);
}
private class T
{
public T(out X d)
{
d = default(X);
}
}
}",
index: 2,
parseOptions: TestOptions.Regular7);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters6()
{
await TestInRegularAndScriptAsync(
@"class Class<X>
{
void M(X d)
{
new [|T|](out d);
}
}",
@"class Class<X>
{
void M(X d)
{
new T(out d);
}
private class T
{
public T(out X d)
{
d = default;
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters7()
{
await TestInRegularAndScriptAsync(
@"class Class<X> where X : class
{
void M(X d)
{
new [|T|](out d);
}
}",
@"class Class<X> where X : class
{
void M(X d)
{
new T(out d);
}
}
internal class T
{
public T(out object d)
{
d = null;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters8()
{
await TestInRegularAndScriptAsync(
@"class Class<X> where X : class
{
void M(X d)
{
new [|T|](out d);
}
}",
@"class Class<X> where X : class
{
void M(X d)
{
new T(out d);
}
private class T
{
public T(out X d)
{
d = null;
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithMethod()
{
await TestInRegularAndScriptAsync(
@"class Class
{
string M(int i)
{
new [|T|](M);
}
}",
@"using System;
class Class
{
string M(int i)
{
new T(M);
}
}
internal class T
{
private Func<int, string> m;
public T(Func<int, string> m)
{
this.m = m;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithLambda()
{
await TestInRegularAndScriptAsync(
@"class Class
{
string M(int i)
{
new [|T|](a => a.ToString());
}
}",
@"using System;
class Class
{
string M(int i)
{
new T(a => a.ToString());
}
}
internal class T
{
private Func<object, object> p;
public T(Func<object, object> p)
{
this.p = p;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](1);
}
}
class Base
{
protected Base(int i)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(1);
}
}
internal class T : Base
{
public T(int i) : base(i)
{
}
}
class Base
{
protected Base(int i)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](1);
}
}
class Base
{
protected Base(object i)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(1);
}
}
internal class T : Base
{
public T(object i) : base(i)
{
}
}
class Base
{
protected Base(object i)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor3()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
void M()
{
Base b = new [|T|](new List<int>());
}
}
class Base
{
protected Base(IEnumerable<int> values)
{
}
}",
@"using System.Collections.Generic;
class Class
{
void M()
{
Base b = new T(new List<int>());
}
}
internal class T : Base
{
public T(IEnumerable<int> values) : base(values)
{
}
}
class Base
{
protected Base(IEnumerable<int> values)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor4()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](ref i);
}
}
class Base
{
protected Base(ref int o)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(ref i);
}
}
internal class T : Base
{
public T(ref int o) : base(ref o)
{
}
}
class Base
{
protected Base(ref int o)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor5()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](a => a.ToString());
}
}
class Base
{
protected Base(System.Func<int, string> f)
{
}
}",
@"using System;
class Class
{
void M(int i)
{
Base b = new T(a => a.ToString());
}
}
internal class T : Base
{
public T(Func<int, string> f) : base(f)
{
}
}
class Base
{
protected Base(System.Func<int, string> f)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor6()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](out i);
}
}
class Base
{
protected Base(out int o)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(out i);
}
}
internal class T : Base
{
public T(out int o) : base(out o)
{
}
}
class Base
{
protected Base(out int o)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructorAssigningToNullableField()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
class Class
{
void M()
{
Base? b = new [|T|]();
}
}
class Base
{
}",
@"#nullable enable
class Class
{
void M()
{
Base? b = new [|T|]();
}
}
internal class T : Base
{
}
class Base
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNonDelegatingConstructor1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](1);
}
}
class Base
{
protected Base(string i)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(1);
}
}
internal class T : Base
{
private int v;
public T(int v)
{
this.v = v;
}
}
class Base
{
protected Base(string i)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNonDelegatingConstructor2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](ref i);
}
}
class Base
{
protected Base(out int o)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(ref i);
}
}
internal class T : Base
{
private int i;
public T(ref int i)
{
this.i = i;
}
}
class Base
{
protected Base(out int o)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNonDelegatingConstructor3()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i, bool f)
{
Base b = new [|T|](out i, out f);
}
}
class Base
{
protected Base(ref int o, out bool b)
{
}
}",
@"class Class
{
void M(int i, bool f)
{
Base b = new T(out i, out f);
}
}
internal class T : Base
{
public T(out int i, out bool f)
{
i = 0;
f = false;
}
}
class Base
{
protected Base(ref int o, out bool b)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNonDelegatingConstructor4()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M()
{
Base b = new [|T|](1);
}
}
class Base
{
private Base(int i)
{
}
}",
@"class Class
{
void M()
{
Base b = new T(1);
}
}
internal class T : Base
{
private int v;
public T(int v)
{
this.v = v;
}
}
class Base
{
private Base(int i)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected int i;
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
this.i = i;
}
}
class Base
{
protected int i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(string i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected object i;
}",
@"class Class
{
void M(string i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(string i)
{
this.i = i;
}
}
class Base
{
protected object i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField3()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(string i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected bool i;
}",
@"class Class
{
void M(string i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private string i;
public T(string i)
{
this.i = i;
}
}
class Base
{
protected bool i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField4()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(bool i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected bool ii;
}",
@"class Class
{
void M(bool i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private bool i;
public T(bool i)
{
this.i = i;
}
}
class Base
{
protected bool ii;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField5()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(bool i)
{
Base b = new [|T|](i);
}
}
class Base
{
private bool i;
}",
@"class Class
{
void M(bool i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private bool i;
public T(bool i)
{
this.i = i;
}
}
class Base
{
private bool i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField6()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(bool i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected readonly bool i;
}",
@"class Class
{
void M(bool i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private bool i;
public T(bool i)
{
this.i = i;
}
}
class Base
{
protected readonly bool i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField7()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected int I;
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
I = i;
}
}
class Base
{
protected int I;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField7WithQualification()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected int I;
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
this.I = i;
}
}
class Base
{
protected int I;
}",
index: 1,
options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField8()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
private int I;
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private int i;
public T(int i)
{
this.i = i;
}
}
class Base
{
private int I;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField9()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
public static int i;
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private int i;
public T(int i)
{
this.i = i;
}
}
class Base
{
public static int i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField10()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
D d = new [|T|](i);
}
}
class D : B
{
protected int I;
}
class B
{
protected int i }",
@"class Class
{
void M(int i)
{
D d = new T(i);
}
}
internal class T : D
{
public T(int i)
{
this.i = i;
}
}
class D : B
{
protected int I;
}
class B
{
protected int i }",
index: 1);
}
[WorkItem(49924, "https://github.com/dotnet/roslyn/issues/49924")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateCorrectFieldNaming()
{
var options = new NamingStylesTestOptionSets(LanguageNames.CSharp);
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
D d = new [|D|](i);
}
}",
@"class Class
{
void M(int i)
{
D d = new D(i);
}
}
internal class D
{
private int _i;
public D(int i)
{
_i = i;
}
}",
index: 1, options: options.FieldNamesAreCamelCaseWithUnderscorePrefix);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToProperty1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
public int I { get; private set; }
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private int i;
public T(int i)
{
this.i = i;
}
}
class Base
{
public int I { get; private set; }
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToProperty2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
public int I { get; protected set; }
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
I = i;
}
}
class Base
{
public int I { get; protected set; }
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToProperty2WithQualification()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
public int I { get; protected set; }
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
this.I = i;
}
}
class Base
{
public int I { get; protected set; }
}",
index: 1,
options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToProperty3()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected int I { get; set; }
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
I = i;
}
}
class Base
{
protected int I { get; set; }
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToProperty3WithQualification()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected int I { get; set; }
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
this.I = i;
}
}
class Base
{
protected int I { get; set; }
}",
index: 1,
options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error));
}
[WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeWithPreferIntrinsicPredefinedKeywordFalse()
{
await TestInRegularAndScriptAsync(
@"class Class {
void M(int i)
{
var b = new [|T|](i);
}
}",
@"class Class {
void M(int i)
{
var b = new T(i);
}
}
internal class T
{
private System.Int32 i;
public T(System.Int32 i)
{
this.i = i;
}
}",
index: 1,
options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error));
}
#endregion
#region Generate Interface
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromTypeConstraint()
{
await TestInRegularAndScriptAsync(
@"class EmployeeList<T> where T : Employee, [|IEmployee|], new()
{
}",
@"class EmployeeList<T> where T : Employee, IEmployee, new()
{
}
internal interface IEmployee
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromTypeConstraints()
{
await TestInRegularAndScriptAsync(
@"class EmployeeList<T> where T : Employee, IEmployee, [|IComparable<T>|], new()
{
}",
@"class EmployeeList<T> where T : Employee, IEmployee, IComparable<T>, new()
{
}
internal interface IComparable<T> where T : Employee, IEmployee, IComparable<T>, new()
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGenerateInterfaceFromTypeConstraint()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class EmployeeList<T> where T : Employee, IEmployee, [|IComparable<T>|], new()
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromBaseList1()
{
await TestInRegularAndScriptAsync(
@"interface A : [|B|]
{
}",
@"interface A : B
{
}
internal interface B
{
}",
index: 1);
}
[WorkItem(538519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538519")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromBaseList2()
{
await TestInRegularAndScriptAsync(
@"class Test : [|ITest|]
{
}",
@"class Test : ITest
{
}
internal interface ITest
{
}",
index: 1);
}
[WorkItem(538519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538519")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromTypeConstraints2()
{
await TestInRegularAndScriptAsync(
@"class Test<T> where T : [|ITest|]
{
}",
@"class Test<T> where T : ITest
{
}
internal interface ITest
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromBaseList3()
{
await TestInRegularAndScriptAsync(
@"class A : object, [|B|]
{
}",
@"class A : object, B
{
}
internal interface B
{
}",
index: 1);
}
#endregion
[WorkItem(539339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NotInLeftSideOfAssignment()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
[|Goo|] = 2;
}
}");
}
[WorkItem(539339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task InLeftSideOfAssignment()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
[|Goo|].Bar = 2;
}
}",
@"class Class
{
void M(int i)
{
Goo.Bar = 2;
}
}
internal class Goo
{
}",
index: 1);
}
[WorkItem(539339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NotInRightSideOfAssignment()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
x = [|Goo|];
}
}");
}
[WorkItem(539339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task InRightSideOfAssignment()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
x = [|Goo|].Bar;
}
}",
@"class Class
{
void M(int i)
{
x = Goo.Bar;
}
}
internal class Goo
{
}",
index: 1);
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestEscapedName()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|@Goo|] f;
}",
@"class Class
{
@Goo f;
}
internal class Goo
{
}",
index: 1);
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestEscapedKeyword()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|@int|] f;
}",
@"class Class
{
@int f;
}
internal class @int
{
}",
index: 1);
}
[WorkItem(539535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539535")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateIntoNewFile()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Class { void F() { new [|Goo|].Bar(); } }",
@"namespace Goo
{
internal class Bar
{
public Bar()
{
}
}
}",
expectedContainers: ImmutableArray.Create("Goo"),
expectedDocumentName: "Bar.cs");
}
[WorkItem(539620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539620")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDeclarationSpan()
{
await TestSpansAsync(
@"class Class
{
void Goo()
{
[|Bar|] b;
}
}");
}
[WorkItem(539674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539674")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNotInEnumBaseList()
{
await TestMissingInRegularAndScriptAsync(
@"enum E : [|A|]
{
}");
}
[WorkItem(539681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539681")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNotInConditional()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
if ([|IsTrue|])
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestInUsing()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
using ([|Goo|] f = bar())
{
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
using (Goo f = bar())
{
}
}
}
internal class Goo
{
}",
index: 1);
}
[WorkItem(54493, "https://github.com/dotnet/roslyn/pull/54493")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestInLocalFunction()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
static [|Goo|]
}
}",
@"using System;
class Program
{
static void Main(string[] args)
{
static Goo
}
}
internal class Goo
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNotInDelegateConstructor()
{
await TestMissingInRegularAndScriptAsync(
@"delegate void D(int x);
class C
{
void M()
{
D d = new D([|Test|]);
}
}");
}
[WorkItem(539754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539754")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestMissingOnVar()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
[|var|] x = new Program();
}
}");
}
[WorkItem(539765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539765")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestElideDefaultConstructor()
{
await TestInRegularAndScriptAsync(
@"class A
{
void M()
{
C test = new [|B|]();
}
}
internal class C
{
}",
@"class A
{
void M()
{
C test = new B();
}
}
internal class B : C
{
}
internal class C
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
[WorkItem(539783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539783")]
public async Task RegressionFor5867ErrorToleranceTopLevel()
{
await TestMissingAsync(
@"[|this|] . f = f ; ",
new TestParameters(GetScriptOptions()));
}
[WorkItem(539799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestOnInaccessibleType()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
private class D
{
}
}
class A
{
void M()
{
C.[|D|] d = new C.D();
}
}");
}
[WorkItem(539794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539794")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDefaultConstructorInTypeDerivingFromInterface()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
I obj = new [|A|]();
}
}
interface I
{
}",
@"class Program
{
static void Main(string[] args)
{
I obj = new A();
}
}
internal class A : I
{
}
interface I
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateWithThrow()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
throw new [|NotFoundException|]();
}
}",
@"using System;
using System.Runtime.Serialization;
class C
{
void M()
{
throw new NotFoundException();
}
}
[Serializable]
internal class NotFoundException : Exception
{
public NotFoundException()
{
}
public NotFoundException(string message) : base(message)
{
}
public NotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
protected NotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInTryCatch()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
try
{
}
catch ([|NotFoundException|] ex)
{
}
}
}",
@"using System;
using System.Runtime.Serialization;
class C
{
void M()
{
try
{
}
catch (NotFoundException ex)
{
}
}
}
[Serializable]
internal class NotFoundException : Exception
{
public NotFoundException()
{
}
public NotFoundException(string message) : base(message)
{
}
public NotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
protected NotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}",
index: 1);
}
[WorkItem(539739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539739")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestNotGenerateInDelegateConstructor()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
delegate void D(int x);
class C
{
void M()
{
D d = new D([|Test|]);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestInStructBaseList()
{
await TestInRegularAndScriptAsync(
@"struct S : [|A|]
{
}",
@"struct S : A
{
}
internal interface A
{
}",
index: 1);
}
[WorkItem(539870, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539870")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenericWhenNonGenericExists()
{
await TestInRegularAndScriptAsync(
@"class C
{
void Goo()
{
[|A<T>|] a;
}
}
class A
{
}",
@"class C
{
void Goo()
{
A<T> a;
}
}
internal class A<T>
{
}
class A
{
}",
index: 1);
}
[WorkItem(539930, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539930")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestInheritedTypeParameters()
{
await TestInRegularAndScriptAsync(
@"class C<T, R>
{
void M()
{
I<T, R> i = new [|D<T, R>|]();
}
}
interface I<T, R>
{
}",
@"class C<T, R>
{
void M()
{
I<T, R> i = new D<T, R>();
}
}
internal class D<T, R> : I<T, R>
{
}
interface I<T, R>
{
}",
index: 1);
}
[WorkItem(539971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539971")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDoNotUseOuterTypeParameters()
{
await TestInRegularAndScriptAsync(
@"class C<T1, T2>
{
public void Goo()
{
[|D<int, string>|] d;
}
}",
@"class C<T1, T2>
{
public void Goo()
{
D<int, string> d;
}
private class D<T3, T4>
{
}
}",
index: 2);
}
[WorkItem(539970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539970")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestReferencingTypeParameters1()
{
await TestInRegularAndScriptAsync(
@"class M<T, R>
{
public void Goo()
{
I<T, R> i = new [|C<int, string>|]();
}
}
interface I<T, R>
{
}",
@"class M<T, R>
{
public void Goo()
{
I<T, R> i = new C<int, string>();
}
}
internal class C<T1, T2> : I<object, object>
{
}
interface I<T, R>
{
}",
index: 1);
}
[WorkItem(539970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539970")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestReferencingTypeParameters2()
{
await TestInRegularAndScriptAsync(
@"class M<T, R>
{
public void Goo()
{
I<T, R> i = new [|C<int, string>|]();
}
}
interface I<T, R>
{
}",
@"class M<T, R>
{
public void Goo()
{
I<T, R> i = new C<int, string>();
}
private class C<T1, T2> : I<T, R>
{
}
}
interface I<T, R>
{
}",
index: 2);
}
[WorkItem(539972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539972")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestReferencingTypeParameters3()
{
await TestInRegularAndScriptAsync(
@"class C<T1, T2>
{
public void Goo(T1 t1, T2 t2)
{
A a = new [|A|](t1, t2);
}
}",
@"class C<T1, T2>
{
public void Goo(T1 t1, T2 t2)
{
A a = new A(t1, t2);
}
}
internal class A
{
private object t1;
private object t2;
public A(object t1, object t2)
{
this.t1 = t1;
this.t2 = t2;
}
}",
index: 1);
}
[WorkItem(539972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539972")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestReferencingTypeParameters4()
{
await TestInRegularAndScriptAsync(
@"class C<T1, T2>
{
public void Goo(T1 t1, T2 t2)
{
A a = new [|A|](t1, t2);
}
}",
@"class C<T1, T2>
{
public void Goo(T1 t1, T2 t2)
{
A a = new A(t1, t2);
}
private class A
{
private T1 t1;
private T2 t2;
public A(T1 t1, T2 t2)
{
this.t1 = t1;
this.t2 = t2;
}
}
}",
index: 2);
}
[WorkItem(539992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539992")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNotPassingEmptyIssueListToCtor()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Linq;
class Program
{
void Main()
{
Enumerable.[|T|] Enumerable . Select(Enumerable.Range(0, 9), i => char.Parse(i.ToString())) }
}");
}
[WorkItem(540644, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540644")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateWithVoidArg()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void M()
{
C c = new [|C|](M());
}
}",
@"class Program
{
void M()
{
C c = new C(M());
}
}
internal class C
{
private object v;
public C(object v)
{
this.v = v;
}
}",
index: 1);
}
[WorkItem(540989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540989")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestMissingOnInaccessibleType()
{
await TestMissingInRegularAndScriptAsync(
@"class Outer
{
class Inner
{
}
}
class A
{
Outer.[|Inner|] inner;
}");
}
[WorkItem(540766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540766")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestOnInvalidGlobalCode()
{
await TestInRegularAndScriptAsync(
@"[|a|] test ",
@"[|a|] test internal class a
{
}",
index: 1);
}
[WorkItem(539985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539985")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDoNotInferTypeWithWrongArity()
{
await TestInRegularAndScriptAsync(
@"class C<T1>
{
public void Test()
{
C c = new [|C|]();
}
}",
@"class C<T1>
{
public void Test()
{
C c = new C();
}
}
internal class C
{
public C()
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestMissingOnInvalidConstructorToExistingType()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
new [|Program|](1);
}
}");
}
[WorkItem(541263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541263")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public static class MyExtension
{
public static int ExtensionMethod(this String s, [|D|] d)
{
return 10;
}
}",
@"public static class MyExtension
{
public static int ExtensionMethod(this String s, D d)
{
return 10;
}
}
public class D
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestBaseTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C : [|D|]
{
}",
@"public class C : D
{
}
public class D
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestBaseInterfaceAccessibilityConstraint1()
{
await TestInRegularAndScriptAsync(
@"public class C : X, [|IGoo|]
{
}",
@"public class C : X, IGoo
{
}
internal interface IGoo
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityConstraint2()
{
await TestInRegularAndScriptAsync(
@"public interface C : [|IBar|], IGoo
{
}",
@"public interface C : IBar, IGoo
{
}
public interface IBar
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityConstraint3()
{
await TestInRegularAndScriptAsync(
@"public interface C : IBar, [|IGoo|]
{
}",
@"public interface C : IBar, IGoo
{
}
public interface IGoo
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDelegateReturnTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public delegate [|D|] Goo();",
@"public delegate D Goo();
public class D
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDelegateParameterAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public delegate D Goo([|S|] d);",
@"public delegate D Goo(S d);
public class S
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestMethodParameterAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C
{
public void Goo([|F|] f);
}",
@"public class C
{
public void Goo(F f);
}
public class F
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestMethodReturnTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C
{
public [|F|] Goo(Bar f);
}",
@"public class C
{
public F Goo(Bar f);
public class F
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestPropertyTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C
{
public [|F|] Goo { get; }
}",
@"public class C
{
public F Goo { get; }
public class F
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestFieldEventTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C
{
public event [|F|] E;
}",
@"public class C
{
public event F E;
public class F
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestEventTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C
{
public event [|F|] E
{
add
{
}
remove
{
}
}
}",
@"public class C
{
public event F E
{
add
{
}
remove
{
}
}
}
public class F
{
}",
index: 1);
}
[WorkItem(541654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541654")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateVarType()
{
await TestInRegularAndScriptAsync(
@"class C
{
public static void Main()
{
[|@var|] v;
}
}",
@"class C
{
public static void Main()
{
@var v;
}
}
internal class var
{
}",
index: 1);
}
[WorkItem(541641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541641")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestOnBadAttribute()
{
await TestInRegularAndScriptAsync(
@"[[|AttClass|]()]
class C
{
}
internal class AttClassAttribute
{
}",
@"using System;
[AttClass()]
class C
{
}
internal class AttClassAttribute : Attribute
{
}
internal class AttClassAttribute
{
}",
index: 1);
}
[WorkItem(542528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542528")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateStruct1()
{
await TestInRegularAndScriptAsync(
@"using System;
class A<T> where T : struct
{
}
class Program
{
static void Main()
{
new A<[|S|]>();
}
}",
@"using System;
class A<T> where T : struct
{
}
class Program
{
static void Main()
{
new A<S>();
}
}
internal struct S
{
}",
index: 1);
}
[WorkItem(542480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542480")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestCopyConstraints1()
{
await TestInRegularAndScriptAsync(
@"class A<T> where T : class
{
}
class Program
{
static void Goo<T>() where T : class
{
A<T> a = new [|B<T>|]();
}
}",
@"class A<T> where T : class
{
}
class Program
{
static void Goo<T>() where T : class
{
A<T> a = new B<T>();
}
}
internal class B<T> : A<T> where T : class
{
}",
index: 1);
}
[WorkItem(542528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542528")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateStruct2()
{
await TestInRegularAndScriptAsync(
@"using System;
class A<T> where T : struct
{
}
class Program
{
static void Main()
{
new A<Program.[|S|]>();
}
}",
@"using System;
class A<T> where T : struct
{
}
class Program
{
static void Main()
{
new A<Program.S>();
}
private struct S
{
}
}");
}
[WorkItem(542528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542528")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateStruct3()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main()
{
Goo<Program.[|S|]>();
}
static void Goo<T>() where T : struct
{
}
}",
@"using System;
class Program
{
static void Main()
{
Goo<Program.S>();
}
static void Goo<T>() where T : struct
{
}
private struct S
{
}
}");
}
[WorkItem(542761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542761")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateOpenType1()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
var x = typeof([|C<,>|]);
}
}",
@"class Program
{
static void Main()
{
var x = typeof(C<,>);
}
}
internal class C<T1, T2>
{
}",
index: 1);
}
[WorkItem(542766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542766")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateAttributeInGenericType()
{
await TestActionCountAsync(
@"using System;
class A<T>
{
[[|C|]]
void Goo()
{
}
}",
count: 6);
}
[WorkItem(543061, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543061")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNestedGenericAccessibility()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
public class C
{
public void Goo(List<[|NewClass|]> x)
{
}
}",
@"using System.Collections.Generic;
public class C
{
public void Goo(List<NewClass> x)
{
}
}
public class NewClass
{
}",
index: 1);
}
[WorkItem(543493, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543493")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task MissingIfNotInTypeStatementOrExpressionContext()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
a [|b|] c d }
}");
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
a b [|c|] d }
}");
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
a b c [|d|] }
}");
}
[WorkItem(542641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542641")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAttributeSuffixOnAttributeSubclasses()
{
await TestInRegularAndScriptAsync(
@"using System.Runtime.CompilerServices;
class Program
{
static void Main(string[] args)
{
CustomConstantAttribute a = new [|GooAttribute|]();
}
}",
@"using System.Runtime.CompilerServices;
class Program
{
static void Main(string[] args)
{
CustomConstantAttribute a = new GooAttribute();
}
}
internal class GooAttribute : CustomConstantAttribute
{
}",
index: 1);
}
[WorkItem(543853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDisplayStringForGlobalNamespace()
{
await TestSmartTagTextAsync(
@"class C : [|Goo|]",
string.Format(FeaturesResources.Generate_0_1_in_new_file, "class", "Goo", FeaturesResources.Global_Namespace));
}
[WorkItem(543853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543853")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAddDocumentForGlobalNamespace()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class C : [|Goo|]",
@"internal class Goo
{
}",
ImmutableArray<string>.Empty,
"Goo.cs");
}
[WorkItem(543886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543886")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestVerbatimAttribute()
{
await TestInRegularAndScriptAsync(
@"[[|@X|]]
class Class3
{
}",
@"using System;
[@X]
class Class3
{
}
internal class X : Attribute
{
}",
index: 1);
}
[WorkItem(531220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531220")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task CompareIncompleteMembersToEqual()
{
await TestInRegularAndScriptAsync(
@"class C
{
X.X,X class X
{
X
}
X void X<X void X
x, [|x|])",
@"class C
{
X.X,X class X
{
X
}
X void X<X void X
x, x)private class x
{
}
}
",
index: 2);
}
[WorkItem(544168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544168")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNotOnAbstractClassCreation()
{
await TestMissingInRegularAndScriptAsync(
@"abstract class Goo
{
}
class SomeClass
{
void goo()
{
var q = new [|Goo|]();
}
}");
}
[WorkItem(545362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545362")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInVenus1()
{
var code = @"
#line hidden
#line 1 ""Default.aspx""
class Program
{
static void Main(string[] args)
{
[|Goo|] f;
#line hidden
#line 2 ""Default.aspx""
}
}
";
await TestExactActionSetOfferedAsync(code,
new[]
{
string.Format(FeaturesResources.Generate_0_1_in_new_file, "class", "Goo", FeaturesResources.Global_Namespace),
string.Format(FeaturesResources.Generate_nested_0_1, "class", "Goo", "Program"),
FeaturesResources.Generate_new_type
});
await TestInRegularAndScriptAsync(code,
@"
#line hidden
#line 1 ""Default.aspx""
class Program
{
static void Main(string[] args)
{
[|Goo|] f;
#line hidden
#line 2 ""Default.aspx""
}
private class Goo
{
}
}
", index: 1);
}
[WorkItem(869506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/869506")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeOutsideCurrentProject()
{
var code = @"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<ProjectReference>Assembly2</ProjectReference>
<Document FilePath=""Test1.cs"">
class Program
{
static void Main(string[] args)
{
[|A.B.C$$|].D f;
}
}
namespace A
{
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document FilePath=""Test2.cs"">
namespace A
{
public class B
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
namespace A
{
public class B
{
public class C
{
}
}
}
";
await TestInRegularAndScriptAsync(code, expected);
}
[WorkItem(932602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932602")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeInFolderNotDefaultNamespace_0()
{
var code = @"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DefaultNamespace = ""Namespace1.Namespace2"">
<Document FilePath=""Test1.cs"">
namespace Namespace1.Namespace2
{
public class ClassA : [|$$ClassB|]
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"namespace Namespace1.Namespace2
{
public class ClassB
{
}
}";
await TestAddDocumentInRegularAndScriptAsync(code,
expected,
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "ClassB.cs");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeInFolderNotDefaultNamespace_0_FileScopedNamespace()
{
var code = @"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DefaultNamespace = ""Namespace1.Namespace2"">
<Document FilePath=""Test1.cs"">
namespace Namespace1.Namespace2;
public class ClassA : [|$$ClassB|]
{
}
</Document>
</Project>
</Workspace>";
var expected = @"namespace Namespace1.Namespace2;
public class ClassB
{
}";
await TestAddDocumentInRegularAndScriptAsync(code,
expected,
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "ClassB.cs",
new TestParameters(
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10),
options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent)));
}
[WorkItem(932602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932602")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeInFolderNotDefaultNamespace_1()
{
var code = @"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DefaultNamespace = ""Namespace1.Namespace2"" >
<Document FilePath=""Test1.cs"" Folders=""Namespace1\Namespace2"">
namespace Namespace1.Namespace2.Namespace3
{
public class ClassA : [|$$ClassB|]
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"namespace Namespace1.Namespace2.Namespace3
{
public class ClassB
{
}
}";
await TestAddDocumentInRegularAndScriptAsync(code,
expected,
expectedContainers: ImmutableArray.Create("Namespace1", "Namespace2"),
expectedDocumentName: "ClassB.cs");
}
[WorkItem(612700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612700")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeWithNoBraces()
{
var code = @"class Test : [|Base|]";
var expected = @"class Test : Base
internal class Base
{
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(940003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/940003")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithProperties1()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = ""John"", Age = DateTime.Today};
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new Customer(x: 1, y: ""Hello"") {Name = ""John"", Age = DateTime.Today};
}
}
internal class Customer
{
private int x;
private string y;
public Customer(int x, string y)
{
this.x = x;
this.y = y;
}
public string Name { get; set; }
public DateTime Age { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(940003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/940003")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithProperties2()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = null, Age = DateTime.Today};
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new Customer(x: 1, y: ""Hello"") {Name = null, Age = DateTime.Today};
}
}
internal class Customer
{
private int x;
private string y;
public Customer(int x, string y)
{
this.x = x;
this.y = y;
}
public object Name { get; set; }
public DateTime Age { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(940003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/940003")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithProperties3()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = Goo, Age = DateTime.Today};
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new Customer(x: 1, y: ""Hello"") {Name = Goo, Age = DateTime.Today};
}
}
internal class Customer
{
private int x;
private string y;
public Customer(int x, string y)
{
this.x = x;
this.y = y;
}
public object Name { get; set; }
public DateTime Age { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(1082031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082031")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithProperties4()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new [|Customer|] {Name = ""John"", Age = DateTime.Today};
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new Customer {Name = ""John"", Age = DateTime.Today};
}
}
internal class Customer
{
public string Name { get; set; }
public DateTime Age { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176"), WorkItem(1073099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithNameOf()
{
var code = @"class C
{
void M()
{
var x = nameof([|Z|]);
}
}
";
var expected = @"class C
{
void M()
{
var x = nameof(Z);
}
}
internal class Z
{
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176"), WorkItem(1073099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithNameOf2()
{
var code = @"class C
{
void M()
{
var x = nameof([|C.Test|]);
}
}";
var expected = @"class C
{
void M()
{
var x = nameof(C.Test);
}
private class Test
{
}
}";
await TestInRegularAndScriptAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithUsingStatic()
{
await TestInRegularAndScriptAsync(
@"using static [|Sample|];",
@"using static Sample;
internal class Sample
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithUsingStatic2()
{
await TestMissingInRegularAndScriptAsync(
@"using [|Sample|];");
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B b = new [|B|]();
}",
@"public class B
{
public B()
{
}
}");
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields2()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B b = new [|B|]();
}",
@"class A
{
public B b = new B();
}
public class B
{
public B()
{
}
}",
index: 1);
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields3()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B b = new [|B|]();
}",
@"class A
{
public B b = new B();
public class B
{
public B()
{
}
}
}",
index: 2);
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields4()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B<int> b = new [|B|]<int>();
}",
@"public class B<T>
{
public B()
{
}
}");
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields5()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B<int> b = new [|B|]<int>();
}",
@"class A
{
public B<int> b = new B<int>();
}
public class B<T>
{
public B()
{
}
}",
index: 1);
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields6()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B<int> b = new [|B|]<int>();
}",
@"class A
{
public B<int> b = new B<int>();
public class B<T>
{
public B()
{
}
}
}",
index: 2);
}
[WorkItem(17361, "https://github.com/dotnet/roslyn/issues/17361")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestPreserveFileBanner1()
{
await TestAddDocumentInRegularAndScriptAsync(
@"// I am a banner
class Program
{
void Main ( )
{
[|Goo|] f ;
}
} ",
@"// I am a banner
internal class Goo
{
}",
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "Goo.cs");
}
[WorkItem(17361, "https://github.com/dotnet/roslyn/issues/17361")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestPreserveFileBanner2()
{
await TestAddDocumentInRegularAndScriptAsync(
@"/// I am a doc comment
class Program
{
void Main ( )
{
[|Goo|] f ;
}
} ",
@"internal class Goo
{
}",
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "Goo.cs");
}
[WorkItem(17361, "https://github.com/dotnet/roslyn/issues/17361")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestPreserveFileBanner3()
{
await TestAddDocumentInRegularAndScriptAsync(
@"// I am a banner
using System;
class Program
{
void Main (StackOverflowException e)
{
var f = new [|Goo|](e);
}
}",
@"// I am a banner
using System;
internal class Goo
{
private StackOverflowException e;
public Goo(StackOverflowException e)
{
this.e = e;
}
}",
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "Goo.cs");
}
[WorkItem(22293, "https://github.com/dotnet/roslyn/issues/22293")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
[InlineData("void")]
[InlineData("int")]
public async Task TestMethodGroupWithMissingSystemActionAndFunc(string returnType)
{
await TestInRegularAndScriptAsync(
$@"
<Workspace>
<Project Language=""C#"" CommonReferences=""false"">
<Document><;
}}
{returnType} Method()
{{
}}
}}
]]>
</Document>
</Project>
</Workspace>",
$@"
class C
{{
void M()
{{
new Class(Method);
}}
{returnType} Method()
{{
}}
}}
internal class Class
{{
private global::System.Object method;
public Class(global::System.Object method)
{{
this.method = method;
}}
}}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
[WorkItem(270, "https://github.com/dotnet/roslyn/issues/270")]
public async Task TestGenerateInIsExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main(Exception p)
{
bool result = p is [|SampleType|];
}
}",
@"using System;
using System.Runtime.Serialization;
class Program
{
static void Main(Exception p)
{
bool result = p is SampleType;
}
}
[Serializable]
internal class SampleType : Exception
{
public SampleType()
{
}
public SampleType(string message) : base(message)
{
}
public SampleType(string message, Exception innerException) : base(message, innerException)
{
}
protected SampleType(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
[WorkItem(45808, "https://github.com/dotnet/roslyn/issues/45808")]
public async Task TestGenerateUnsafe()
{
await TestInRegularAndScriptAsync(
@"class C
{
unsafe void M(int* x)
{
new [|D|](x);
}
}",
@"class C
{
unsafe void M(int* x)
{
new D(x);
}
}
internal class D
{
private unsafe int* x;
public unsafe D(int* x)
{
this.x = x;
}
}", index: 1);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.GenerateType;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.GenerateTypeTests
{
public partial class GenerateTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public GenerateTypeTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new GenerateTypeCodeFixProvider());
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> codeActions)
=> FlattenActions(codeActions);
// TODO: Requires WPF due to IInlineRenameService dependency (https://github.com/dotnet/roslyn/issues/46153)
protected override TestComposition GetComposition()
=> EditorTestCompositions.EditorFeaturesWpf
.AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService))
.AddParts(typeof(MockDiagnosticUpdateSourceRegistrationService));
#region Generate Class
#region Generics
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeParameterFromArgumentInferT()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void Main()
{
[|Goo<int>|] f;
}
}",
@"class Program
{
void Main()
{
Goo<int> f;
}
}
internal class Goo<T>
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromTypeParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
System.Action<[|Employee|]> employees;
}",
@"class Class
{
System.Action<Employee> employees;
private class Employee
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClause()
{
await TestInRegularAndScriptAsync(
@"class EmployeeList<T> where T : [|Employee|], new()
{
}",
@"class EmployeeList<T> where T : Employee, new()
{
}
internal class Employee
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGeneratePublicClassFromASingleConstraintClause()
{
await TestInRegularAndScriptAsync(
@"public class EmployeeList<T> where T : [|Employee|], new()
{
}",
@"public class EmployeeList<T> where T : Employee, new()
{
}
public class Employee
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGenerateClassFromConstructorConstraint()
{
await TestMissingInRegularAndScriptAsync(
@"class EmployeeList<T> where T : Employee, [|new()|]
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromMultipleTypeConstraintClauses()
{
await TestInRegularAndScriptAsync(
@"class Derived<T, U>
where U : struct
where T : [|Base|], new()
{
}",
@"class Derived<T, U>
where U : struct
where T : Base, new()
{
}
internal class Base
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGeneratePublicClassFromMultipleTypeConstraintClauses()
{
await TestInRegularAndScriptAsync(
@"public class Derived<T, U>
where U : struct
where T : [|Base|], new()
{
}",
@"public class Derived<T, U>
where U : struct
where T : Base, new()
{
}
public class Base
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGenerateClassFromClassOrStructConstraint()
{
await TestMissingInRegularAndScriptAsync(
@"class Derived<T, U>
where U : [|struct|]
where T : Base, new()
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAbsenceOfGenerateIntoInvokingTypeForConstraintList()
{
await TestActionCountAsync(
@"class EmployeeList<T> where T : [|Employee|]
{
}",
count: 3,
parameters: new TestParameters(Options.Regular));
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClauseInterface()
{
await TestInRegularAndScriptAsync(
@"interface IEmployeeList<T> where T : [|Employee|], new()
{
}",
@"interface IEmployeeList<T> where T : Employee, new()
{
}
internal class Employee
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGeneratePublicClassFromASingleConstraintClausePublicInterface()
{
await TestInRegularAndScriptAsync(
@"public interface IEmployeeList<T> where T : [|Employee|], new()
{
}",
@"public interface IEmployeeList<T> where T : Employee, new()
{
}
public class Employee
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClauseInternalDelegate()
{
await TestInRegularAndScriptAsync(
@"class Employee
{
internal delegate void Action<T>() where T : [|Command|];
}",
@"class Employee
{
internal delegate void Action<T>() where T : Command;
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClausePublicDelegate()
{
await TestInRegularAndScriptAsync(
@"class Employee
{
public delegate void Action<T>() where T : [|Command|];
}",
@"class Employee
{
public delegate void Action<T>() where T : Command;
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClauseInternalMethod()
{
await TestInRegularAndScriptAsync(
@"class Employee
{
internal void Action<T>() where T : [|Command|] {}
}",
@"class Employee
{
internal void Action<T>() where T : Command {}
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClausePublicMethod()
{
await TestInRegularAndScriptAsync(
@"class Employee
{
public void Action<T>() where T : [|Command|] {}
}",
@"class Employee
{
public void Action<T>() where T : Command {}
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClauseMethod()
{
await TestInRegularAndScriptAsync(
@"class Employee
{
void Action<T>() where T : [|Command|] {}
}",
@"class Employee
{
void Action<T>() where T : Command {}
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInternalClassFromASingleConstraintClauseMethodInInterface()
{
await TestInRegularAndScriptAsync(
@"interface Employee
{
void Action<T>() where T : [|Command|] {}
}",
@"interface Employee
{
void Action<T>() where T : Command {}
}
internal class Command
{
}",
index: 1);
}
[WorkItem(18240, "https://github.com/dotnet/roslyn/issues/18240")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
[InlineData("public", "internal", "internal")]
[InlineData("public", "private", "internal")]
[InlineData("internal", "protected", "internal")]
[InlineData("public", "protected internal", "public")]
[InlineData("protected", "protected", "public")]
[InlineData("protected internal", "protected", "public")]
[InlineData("protected", "protected private", "internal")]
[InlineData("protected private", "protected", "internal")]
public async Task TestGenerateInternalClassFromASingleConstraintClauseNestedClass(string middleAccessibility, string accessibility, string generatedAccessibility)
{
await TestInRegularAndScriptAsync(
$@"public class A
{{
{middleAccessibility} class B
{{
{accessibility} class C<T> where T : [|D|]
{{
}}
}}
}}",
$@"public class A
{{
{middleAccessibility} class B
{{
{accessibility} class C<T> where T : D
{{
}}
}}
}}
{generatedAccessibility} class D
{{
}}",
index: 1);
}
#endregion
#region Lambdas
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromParenthesizedLambdaExpressionsParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
Func<Employee, int, bool> l = ([|Employee|] e, int age) => e.Age > age;
}",
@"class Class
{
Func<Employee, int, bool> l = (Employee e, int age) => e.Age > age;
private class Employee
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromParenthesizedLambdaExpressionsBody()
{
await TestInRegularAndScriptAsync(
@"class Class
{
System.Action<Class, int> l = (Class e, int age) => {
[|Wage|] w;
};
}",
@"class Class
{
System.Action<Class, int> l = (Class e, int age) => {
Wage w;
};
private class Wage
{
}
}",
index: 2);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromFieldDeclarationIntoSameType()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|Goo|] f;
}",
@"class Class
{
Goo f;
private class Goo
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromNullableFieldDeclarationIntoSameType()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
class Class
{
[|Goo?|] f;
}",
@"#nullable enable
class Class
{
Goo? f;
private class Goo
{
}
}",
index: 2);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromFieldDeclarationIntoGlobalNamespace()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Program { void Main ( ) { [|Goo|] f ; } } ",
@"internal class Goo
{
}",
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "Goo.cs");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromFieldDeclarationIntoCustomNamespace()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Class { [|TestNamespace|].Goo f; }",
@"namespace TestNamespace
{
internal class Goo
{
}
}",
expectedContainers: ImmutableArray.Create("TestNamespace"),
expectedDocumentName: "Goo.cs");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromFieldDeclarationIntoSameNamespace()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|Goo|] f;
}",
@"class Class
{
Goo f;
}
internal class Goo
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassWithCtorFromObjectCreation()
{
await TestInRegularAndScriptAsync(
@"class Class
{
Goo f = new [|Goo|]();
}",
@"class Class
{
Goo f = new Goo();
private class Goo
{
public Goo()
{
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassWithCtorFromObjectCreationWithTuple()
{
await TestInRegularAndScriptAsync(
@"class Class
{
var f = new [|Generated|]((1, 2));
}",
@"class Class
{
var f = new Generated((1, 2));
private class Generated
{
private (int, int) p;
public Generated((int, int) p)
{
this.p = p;
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassWithCtorFromObjectCreationWithTupleWithNames()
{
await TestInRegularAndScriptAsync(
@"class Class
{
var f = new [|Generated|]((a: 1, b: 2, 3));
}",
@"class Class
{
var f = new Generated((a: 1, b: 2, 3));
private class Generated
{
private (int a, int b, int) p;
public Generated((int a, int b, int) p)
{
this.p = p;
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromBaseList()
{
await TestInRegularAndScriptAsync(
@"class Class : [|BaseClass|]
{
}",
@"class Class : BaseClass
{
}
internal class BaseClass
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromMethodParameters()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method([|Goo|] f)
{
}
}",
@"class Class
{
void Method(Goo f)
{
}
private class Goo
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromMethodReturnType()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|Goo|] Method()
{
}
}",
@"class Class
{
Goo Method()
{
}
private class Goo
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromAttribute()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[[|Obsolete|]]
void Method()
{
}
}",
@"using System;
class Class
{
[Obsolete]
void Method()
{
}
private class ObsoleteAttribute : Attribute
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromExpandedAttribute()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[[|ObsoleteAttribute|]]
void Method()
{
}
}",
@"using System;
class Class
{
[ObsoleteAttribute]
void Method()
{
}
private class ObsoleteAttribute : Attribute
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromCatchClause()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
try
{
}
catch ([|ExType|])
{
}
}
}",
@"using System;
using System.Runtime.Serialization;
class Class
{
void Method()
{
try
{
}
catch (ExType)
{
}
}
[Serializable]
private class ExType : Exception
{
public ExType()
{
}
public ExType(string message) : base(message)
{
}
public ExType(string message, Exception innerException) : base(message, innerException)
{
}
protected ExType(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromThrowStatement()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
throw new [|ExType|]();
}
}",
@"using System;
using System.Runtime.Serialization;
class Class
{
void Method()
{
throw new ExType();
}
[Serializable]
private class ExType : Exception
{
public ExType()
{
}
public ExType(string message) : base(message)
{
}
public ExType(string message, Exception innerException) : base(message, innerException)
{
}
protected ExType(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromThrowStatementWithDifferentArg()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
throw new [|ExType|](1);
}
}",
@"using System;
using System.Runtime.Serialization;
class Class
{
void Method()
{
throw new ExType(1);
}
[Serializable]
private class ExType : Exception
{
private int v;
public ExType()
{
}
public ExType(int v)
{
this.v = v;
}
public ExType(string message) : base(message)
{
}
public ExType(string message, Exception innerException) : base(message, innerException)
{
}
protected ExType(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromThrowStatementWithMatchingArg()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
throw new [|ExType|](""message"");
}
}",
@"using System;
using System.Runtime.Serialization;
class Class
{
void Method()
{
throw new ExType(""message"");
}
[Serializable]
private class ExType : Exception
{
public ExType()
{
}
public ExType(string message) : base(message)
{
}
public ExType(string message, Exception innerException) : base(message, innerException)
{
}
protected ExType(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAbsenceOfGenerateIntoInvokingTypeForBaseList()
{
await TestActionCountAsync(
@"class Class : [|BaseClass|]
{
}",
count: 3,
parameters: new TestParameters(Options.Regular));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromUsingStatement()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
using ([|Goo|] f = new Goo())
{
}
}
}",
@"class Class
{
void Method()
{
using (Goo f = new Goo())
{
}
}
private class Goo
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromForeachStatement()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void Method()
{
foreach ([|Employee|] e in empList)
{
}
}
}",
@"class Class
{
void Method()
{
foreach (Employee e in empList)
{
}
}
private class Employee
{
}
}",
index: 2);
}
[WorkItem(538346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538346")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassWhereKeywordBecomesTypeName()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|@class|] c;
}",
@"class Class
{
@class c;
private class @class
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGenerateClassOnContextualKeyword()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|@Goo|] c;
}",
@"class Class
{
@Goo c;
private class Goo
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGenerateClassOnFrameworkTypes()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void Method()
{
[|System|].Console.Write(5);
}
}");
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void Method()
{
System.[|Console|].Write(5);
}
}");
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void Method()
{
System.Console.[|Write|](5);
}
}");
}
[WorkItem(538409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538409")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateIntoRightPart()
{
await TestInRegularAndScriptAsync(
@"partial class Class
{
}
partial class Class
{
[|C|] c;
}",
@"partial class Class
{
}
partial class Class
{
C c;
private class C
{
}
}",
index: 2);
}
[WorkItem(538408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538408")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeIntoCompilationUnit()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|C|] c;
void Main()
{
}
}",
@"class Class
{
C c;
void Main()
{
}
}
internal class C
{
}",
index: 1);
}
[WorkItem(538408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538408")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeIntoNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
class Class
{
[|C|] c;
void Main()
{
}
}
}",
@"namespace N
{
class Class
{
C c;
void Main()
{
}
}
internal class C
{
}
}",
index: 1);
}
[WorkItem(538115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538115")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeWithPreprocessor()
{
await TestInRegularAndScriptAsync(
@"class C
{
#if true
void Goo([|A|] x) { }
#else
#endif
}",
@"class C
{
#if true
void Goo(A x) { }
private class A
{
}
#else
#endif
}",
index: 2);
}
[WorkItem(538495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538495")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeIntoContainingNamespace()
{
await TestInRegularAndScriptAsync(
@"namespace N
{
class Class
{
N.[|C|] c;
}
}",
@"namespace N
{
class Class
{
N.C c;
}
internal class C
{
}
}",
index: 1);
}
[WorkItem(538516, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538516")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateClassFromIntoNewNamespace()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Class { static void Main(string[] args) { [|N|].C c; } }",
@"namespace N
{
internal class C
{
}
}",
expectedContainers: ImmutableArray.Create("N"),
expectedDocumentName: "C.cs");
}
[WorkItem(538558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538558")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGlobalAlias()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void Method()
{
[|global|]::System.String s;
}
}");
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void Method()
{
global::[|System|].String s;
}
}");
}
[WorkItem(538069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538069")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeFromArrayCreation1()
{
await TestAsync(
@"class A
{
void Goo()
{
A[] x = new [|C|][] { };
}
}",
@"class A
{
void Goo()
{
A[] x = new C[] { };
}
}
internal class C : A
{
}",
index: 1,
parseOptions: null);
}
[WorkItem(538069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538069")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeFromArrayCreation2()
{
await TestAsync(
@"class A
{
void Goo()
{
A[][] x = new [|C|][][] { };
}
}",
@"class A
{
void Goo()
{
A[][] x = new C[][] { };
}
}
internal class C : A
{
}",
index: 1,
parseOptions: null);
}
[WorkItem(538069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538069")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeFromArrayCreation3()
{
await TestAsync(
@"class A
{
void Goo()
{
A[] x = new [|C|][][] { };
}
}",
@"class A
{
void Goo()
{
A[] x = new C[][] { };
}
}
internal class C
{
}",
index: 1,
parseOptions: null);
}
[WorkItem(539329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539329")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestNotInUsingDirective()
{
await TestMissingInRegularAndScriptAsync(
@"using [|A|];");
await TestMissingInRegularAndScriptAsync(
@"using [|A.B|];");
await TestMissingInRegularAndScriptAsync(
@"using [|A|].B;");
await TestMissingInRegularAndScriptAsync(
@"using A.[|B|];");
await TestMissingInRegularAndScriptAsync(
@"using X = [|A|];");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateSimpleConstructor()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M()
{
new [|T|]();
}
}",
@"class Class
{
void M()
{
new T();
}
}
internal class T
{
public T()
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithValueParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M()
{
new [|T|](1);
}
}",
@"class Class
{
void M()
{
new T(1);
}
}
internal class T
{
private int v;
public T(int v)
{
this.v = v;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithTwoValueParameters()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M()
{
new [|T|](1, """");
}
}",
@"class Class
{
void M()
{
new T(1, """");
}
}
internal class T
{
private int v1;
private string v2;
public T(int v1, string v2)
{
this.v1 = v1;
this.v2 = v2;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNullableParameter()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
class Class
{
void M()
{
string? s = null;
new [|T|](s);
}
}",
@"#nullable enable
class Class
{
void M()
{
string? s = null;
new [|T|](s);
}
}
internal class T
{
private string? s;
public T(string? s)
{
this.s = s;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNullableParameterThatIsNotNull()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
class Class
{
void M()
{
string? s = ""asdf"";
new [|T|](s);
}
}",
@"#nullable enable
class Class
{
void M()
{
string? s = ""asdf"";
new [|T|](s);
}
}
internal class T
{
private string s;
public T(string s)
{
this.s = s;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNamedParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M()
{
new [|T|](arg: 1);
}
}",
@"class Class
{
void M()
{
new T(arg: 1);
}
}
internal class T
{
private int arg;
public T(int arg)
{
this.arg = arg;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithRefParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
new [|T|](ref i);
}
}",
@"class Class
{
void M(int i)
{
new T(ref i);
}
}
internal class T
{
private int i;
public T(ref int i)
{
this.i = i;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameter()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i, bool b)
{
new [|T|](out i, ref b, null);
}
}",
@"class Class
{
void M(int i, bool b)
{
new T(out i, ref b, null);
}
}
internal class T
{
private bool b;
private object p;
public T(out int i, ref bool b, object p)
{
i = 0;
this.b = b;
this.p = p;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(string s)
{
new [|T|](out s);
}
}",
@"class Class
{
void M(string s)
{
new T(out s);
}
}
internal class T
{
public T(out string s)
{
s = null;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters2_CSharp7()
{
await TestInRegularAndScriptAsync(
@"using System;
class Class
{
void M(DateTime d)
{
new [|T|](out d);
}
}",
@"using System;
class Class
{
void M(DateTime d)
{
new T(out d);
}
}
internal class T
{
public T(out DateTime d)
{
d = default(DateTime);
}
}",
index: 1,
parseOptions: TestOptions.Regular7);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters2()
{
await TestInRegularAndScriptAsync(
@"using System;
class Class
{
void M(DateTime d)
{
new [|T|](out d);
}
}",
@"using System;
class Class
{
void M(DateTime d)
{
new T(out d);
}
}
internal class T
{
public T(out DateTime d)
{
d = default;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters3()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
void M(IList<int> d)
{
new [|T|](out d);
}
}",
@"using System.Collections.Generic;
class Class
{
void M(IList<int> d)
{
new T(out d);
}
}
internal class T
{
public T(out IList<int> d)
{
d = null;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters4()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int? d)
{
new [|T|](out d);
}
}",
@"class Class
{
void M(int? d)
{
new T(out d);
}
}
internal class T
{
public T(out int? d)
{
d = null;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters5()
{
await TestInRegularAndScriptAsync(
@"class Class<X>
{
void M(X d)
{
new [|T|](out d);
}
}",
@"class Class<X>
{
void M(X d)
{
new T(out d);
}
}
internal class T
{
public T(out object d)
{
d = null;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters6_CSharp7()
{
await TestInRegularAndScriptAsync(
@"class Class<X>
{
void M(X d)
{
new [|T|](out d);
}
}",
@"class Class<X>
{
void M(X d)
{
new T(out d);
}
private class T
{
public T(out X d)
{
d = default(X);
}
}
}",
index: 2,
parseOptions: TestOptions.Regular7);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters6()
{
await TestInRegularAndScriptAsync(
@"class Class<X>
{
void M(X d)
{
new [|T|](out d);
}
}",
@"class Class<X>
{
void M(X d)
{
new T(out d);
}
private class T
{
public T(out X d)
{
d = default;
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters7()
{
await TestInRegularAndScriptAsync(
@"class Class<X> where X : class
{
void M(X d)
{
new [|T|](out d);
}
}",
@"class Class<X> where X : class
{
void M(X d)
{
new T(out d);
}
}
internal class T
{
public T(out object d)
{
d = null;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithOutParameters8()
{
await TestInRegularAndScriptAsync(
@"class Class<X> where X : class
{
void M(X d)
{
new [|T|](out d);
}
}",
@"class Class<X> where X : class
{
void M(X d)
{
new T(out d);
}
private class T
{
public T(out X d)
{
d = null;
}
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithMethod()
{
await TestInRegularAndScriptAsync(
@"class Class
{
string M(int i)
{
new [|T|](M);
}
}",
@"using System;
class Class
{
string M(int i)
{
new T(M);
}
}
internal class T
{
private Func<int, string> m;
public T(Func<int, string> m)
{
this.m = m;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithLambda()
{
await TestInRegularAndScriptAsync(
@"class Class
{
string M(int i)
{
new [|T|](a => a.ToString());
}
}",
@"using System;
class Class
{
string M(int i)
{
new T(a => a.ToString());
}
}
internal class T
{
private Func<object, object> p;
public T(Func<object, object> p)
{
this.p = p;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](1);
}
}
class Base
{
protected Base(int i)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(1);
}
}
internal class T : Base
{
public T(int i) : base(i)
{
}
}
class Base
{
protected Base(int i)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](1);
}
}
class Base
{
protected Base(object i)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(1);
}
}
internal class T : Base
{
public T(object i) : base(i)
{
}
}
class Base
{
protected Base(object i)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor3()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
class Class
{
void M()
{
Base b = new [|T|](new List<int>());
}
}
class Base
{
protected Base(IEnumerable<int> values)
{
}
}",
@"using System.Collections.Generic;
class Class
{
void M()
{
Base b = new T(new List<int>());
}
}
internal class T : Base
{
public T(IEnumerable<int> values) : base(values)
{
}
}
class Base
{
protected Base(IEnumerable<int> values)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor4()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](ref i);
}
}
class Base
{
protected Base(ref int o)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(ref i);
}
}
internal class T : Base
{
public T(ref int o) : base(ref o)
{
}
}
class Base
{
protected Base(ref int o)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor5()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](a => a.ToString());
}
}
class Base
{
protected Base(System.Func<int, string> f)
{
}
}",
@"using System;
class Class
{
void M(int i)
{
Base b = new T(a => a.ToString());
}
}
internal class T : Base
{
public T(Func<int, string> f) : base(f)
{
}
}
class Base
{
protected Base(System.Func<int, string> f)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructor6()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](out i);
}
}
class Base
{
protected Base(out int o)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(out i);
}
}
internal class T : Base
{
public T(out int o) : base(out o)
{
}
}
class Base
{
protected Base(out int o)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithDelegatingConstructorAssigningToNullableField()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
class Class
{
void M()
{
Base? b = new [|T|]();
}
}
class Base
{
}",
@"#nullable enable
class Class
{
void M()
{
Base? b = new [|T|]();
}
}
internal class T : Base
{
}
class Base
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNonDelegatingConstructor1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](1);
}
}
class Base
{
protected Base(string i)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(1);
}
}
internal class T : Base
{
private int v;
public T(int v)
{
this.v = v;
}
}
class Base
{
protected Base(string i)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNonDelegatingConstructor2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](ref i);
}
}
class Base
{
protected Base(out int o)
{
}
}",
@"class Class
{
void M(int i)
{
Base b = new T(ref i);
}
}
internal class T : Base
{
private int i;
public T(ref int i)
{
this.i = i;
}
}
class Base
{
protected Base(out int o)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNonDelegatingConstructor3()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i, bool f)
{
Base b = new [|T|](out i, out f);
}
}
class Base
{
protected Base(ref int o, out bool b)
{
}
}",
@"class Class
{
void M(int i, bool f)
{
Base b = new T(out i, out f);
}
}
internal class T : Base
{
public T(out int i, out bool f)
{
i = 0;
f = false;
}
}
class Base
{
protected Base(ref int o, out bool b)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithNonDelegatingConstructor4()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M()
{
Base b = new [|T|](1);
}
}
class Base
{
private Base(int i)
{
}
}",
@"class Class
{
void M()
{
Base b = new T(1);
}
}
internal class T : Base
{
private int v;
public T(int v)
{
this.v = v;
}
}
class Base
{
private Base(int i)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected int i;
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
this.i = i;
}
}
class Base
{
protected int i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(string i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected object i;
}",
@"class Class
{
void M(string i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(string i)
{
this.i = i;
}
}
class Base
{
protected object i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField3()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(string i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected bool i;
}",
@"class Class
{
void M(string i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private string i;
public T(string i)
{
this.i = i;
}
}
class Base
{
protected bool i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField4()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(bool i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected bool ii;
}",
@"class Class
{
void M(bool i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private bool i;
public T(bool i)
{
this.i = i;
}
}
class Base
{
protected bool ii;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField5()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(bool i)
{
Base b = new [|T|](i);
}
}
class Base
{
private bool i;
}",
@"class Class
{
void M(bool i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private bool i;
public T(bool i)
{
this.i = i;
}
}
class Base
{
private bool i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField6()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(bool i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected readonly bool i;
}",
@"class Class
{
void M(bool i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private bool i;
public T(bool i)
{
this.i = i;
}
}
class Base
{
protected readonly bool i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField7()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected int I;
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
I = i;
}
}
class Base
{
protected int I;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField7WithQualification()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected int I;
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
this.I = i;
}
}
class Base
{
protected int I;
}",
index: 1,
options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField8()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
private int I;
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private int i;
public T(int i)
{
this.i = i;
}
}
class Base
{
private int I;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField9()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
public static int i;
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private int i;
public T(int i)
{
this.i = i;
}
}
class Base
{
public static int i;
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToField10()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
D d = new [|T|](i);
}
}
class D : B
{
protected int I;
}
class B
{
protected int i }",
@"class Class
{
void M(int i)
{
D d = new T(i);
}
}
internal class T : D
{
public T(int i)
{
this.i = i;
}
}
class D : B
{
protected int I;
}
class B
{
protected int i }",
index: 1);
}
[WorkItem(49924, "https://github.com/dotnet/roslyn/issues/49924")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateCorrectFieldNaming()
{
var options = new NamingStylesTestOptionSets(LanguageNames.CSharp);
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
D d = new [|D|](i);
}
}",
@"class Class
{
void M(int i)
{
D d = new D(i);
}
}
internal class D
{
private int _i;
public D(int i)
{
_i = i;
}
}",
index: 1, options: options.FieldNamesAreCamelCaseWithUnderscorePrefix);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToProperty1()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
public int I { get; private set; }
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
private int i;
public T(int i)
{
this.i = i;
}
}
class Base
{
public int I { get; private set; }
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToProperty2()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
public int I { get; protected set; }
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
I = i;
}
}
class Base
{
public int I { get; protected set; }
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToProperty2WithQualification()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
public int I { get; protected set; }
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
this.I = i;
}
}
class Base
{
public int I { get; protected set; }
}",
index: 1,
options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToProperty3()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected int I { get; set; }
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
I = i;
}
}
class Base
{
protected int I { get; set; }
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateWithCallToProperty3WithQualification()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
Base b = new [|T|](i);
}
}
class Base
{
protected int I { get; set; }
}",
@"class Class
{
void M(int i)
{
Base b = new T(i);
}
}
internal class T : Base
{
public T(int i)
{
this.I = i;
}
}
class Base
{
protected int I { get; set; }
}",
index: 1,
options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Error));
}
[WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task GenerateTypeWithPreferIntrinsicPredefinedKeywordFalse()
{
await TestInRegularAndScriptAsync(
@"class Class {
void M(int i)
{
var b = new [|T|](i);
}
}",
@"class Class {
void M(int i)
{
var b = new T(i);
}
}
internal class T
{
private System.Int32 i;
public T(System.Int32 i)
{
this.i = i;
}
}",
index: 1,
options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error));
}
#endregion
#region Generate Interface
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromTypeConstraint()
{
await TestInRegularAndScriptAsync(
@"class EmployeeList<T> where T : Employee, [|IEmployee|], new()
{
}",
@"class EmployeeList<T> where T : Employee, IEmployee, new()
{
}
internal interface IEmployee
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromTypeConstraints()
{
await TestInRegularAndScriptAsync(
@"class EmployeeList<T> where T : Employee, IEmployee, [|IComparable<T>|], new()
{
}",
@"class EmployeeList<T> where T : Employee, IEmployee, IComparable<T>, new()
{
}
internal interface IComparable<T> where T : Employee, IEmployee, IComparable<T>, new()
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NegativeTestGenerateInterfaceFromTypeConstraint()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class EmployeeList<T> where T : Employee, IEmployee, [|IComparable<T>|], new()
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromBaseList1()
{
await TestInRegularAndScriptAsync(
@"interface A : [|B|]
{
}",
@"interface A : B
{
}
internal interface B
{
}",
index: 1);
}
[WorkItem(538519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538519")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromBaseList2()
{
await TestInRegularAndScriptAsync(
@"class Test : [|ITest|]
{
}",
@"class Test : ITest
{
}
internal interface ITest
{
}",
index: 1);
}
[WorkItem(538519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538519")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromTypeConstraints2()
{
await TestInRegularAndScriptAsync(
@"class Test<T> where T : [|ITest|]
{
}",
@"class Test<T> where T : ITest
{
}
internal interface ITest
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInterfaceFromBaseList3()
{
await TestInRegularAndScriptAsync(
@"class A : object, [|B|]
{
}",
@"class A : object, B
{
}
internal interface B
{
}",
index: 1);
}
#endregion
[WorkItem(539339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NotInLeftSideOfAssignment()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
[|Goo|] = 2;
}
}");
}
[WorkItem(539339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task InLeftSideOfAssignment()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
[|Goo|].Bar = 2;
}
}",
@"class Class
{
void M(int i)
{
Goo.Bar = 2;
}
}
internal class Goo
{
}",
index: 1);
}
[WorkItem(539339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task NotInRightSideOfAssignment()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
x = [|Goo|];
}
}");
}
[WorkItem(539339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539339")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task InRightSideOfAssignment()
{
await TestInRegularAndScriptAsync(
@"class Class
{
void M(int i)
{
x = [|Goo|].Bar;
}
}",
@"class Class
{
void M(int i)
{
x = Goo.Bar;
}
}
internal class Goo
{
}",
index: 1);
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestEscapedName()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|@Goo|] f;
}",
@"class Class
{
@Goo f;
}
internal class Goo
{
}",
index: 1);
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestEscapedKeyword()
{
await TestInRegularAndScriptAsync(
@"class Class
{
[|@int|] f;
}",
@"class Class
{
@int f;
}
internal class @int
{
}",
index: 1);
}
[WorkItem(539535, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539535")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateIntoNewFile()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Class { void F() { new [|Goo|].Bar(); } }",
@"namespace Goo
{
internal class Bar
{
public Bar()
{
}
}
}",
expectedContainers: ImmutableArray.Create("Goo"),
expectedDocumentName: "Bar.cs");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateIntoNewFileWithUsings1()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Class { void F() { new [|Goo|].Bar(new System.Collections.Generic.List<int>()); } }",
@"using System.Collections.Generic;
namespace Goo
{
internal class Bar
{
private List<int> list;
public Bar(List<int> list)
{
this.list = list;
}
}
}",
expectedContainers: ImmutableArray.Create("Goo"),
expectedDocumentName: "Bar.cs");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateIntoNewFileWithUsings2()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Class { void F() { new [|Goo|].Bar(new System.Collections.Generic.List<int>()); } }",
@"namespace Goo
{
using System.Collections.Generic;
internal class Bar
{
private List<int> list;
public Bar(List<int> list)
{
this.list = list;
}
}
}",
expectedContainers: ImmutableArray.Create("Goo"),
expectedDocumentName: "Bar.cs",
parameters: new TestParameters(options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, AddImportPlacement.InsideNamespace, NotificationOption2.Error)));
}
[WorkItem(539620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539620")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDeclarationSpan()
{
await TestSpansAsync(
@"class Class
{
void Goo()
{
[|Bar|] b;
}
}");
}
[WorkItem(539674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539674")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNotInEnumBaseList()
{
await TestMissingInRegularAndScriptAsync(
@"enum E : [|A|]
{
}");
}
[WorkItem(539681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539681")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNotInConditional()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
if ([|IsTrue|])
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestInUsing()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
using ([|Goo|] f = bar())
{
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
using (Goo f = bar())
{
}
}
}
internal class Goo
{
}",
index: 1);
}
[WorkItem(54493, "https://github.com/dotnet/roslyn/pull/54493")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestInLocalFunction()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
static [|Goo|]
}
}",
@"using System;
class Program
{
static void Main(string[] args)
{
static Goo
}
}
internal class Goo
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNotInDelegateConstructor()
{
await TestMissingInRegularAndScriptAsync(
@"delegate void D(int x);
class C
{
void M()
{
D d = new D([|Test|]);
}
}");
}
[WorkItem(539754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539754")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestMissingOnVar()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
[|var|] x = new Program();
}
}");
}
[WorkItem(539765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539765")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestElideDefaultConstructor()
{
await TestInRegularAndScriptAsync(
@"class A
{
void M()
{
C test = new [|B|]();
}
}
internal class C
{
}",
@"class A
{
void M()
{
C test = new B();
}
}
internal class B : C
{
}
internal class C
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
[WorkItem(539783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539783")]
public async Task RegressionFor5867ErrorToleranceTopLevel()
{
await TestMissingAsync(
@"[|this|] . f = f ; ",
new TestParameters(GetScriptOptions()));
}
[WorkItem(539799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestOnInaccessibleType()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
private class D
{
}
}
class A
{
void M()
{
C.[|D|] d = new C.D();
}
}");
}
[WorkItem(539794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539794")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDefaultConstructorInTypeDerivingFromInterface()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main(string[] args)
{
I obj = new [|A|]();
}
}
interface I
{
}",
@"class Program
{
static void Main(string[] args)
{
I obj = new A();
}
}
internal class A : I
{
}
interface I
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateWithThrow()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
throw new [|NotFoundException|]();
}
}",
@"using System;
using System.Runtime.Serialization;
class C
{
void M()
{
throw new NotFoundException();
}
}
[Serializable]
internal class NotFoundException : Exception
{
public NotFoundException()
{
}
public NotFoundException(string message) : base(message)
{
}
public NotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
protected NotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInTryCatch()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M()
{
try
{
}
catch ([|NotFoundException|] ex)
{
}
}
}",
@"using System;
using System.Runtime.Serialization;
class C
{
void M()
{
try
{
}
catch (NotFoundException ex)
{
}
}
}
[Serializable]
internal class NotFoundException : Exception
{
public NotFoundException()
{
}
public NotFoundException(string message) : base(message)
{
}
public NotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
protected NotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}",
index: 1);
}
[WorkItem(539739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539739")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestNotGenerateInDelegateConstructor()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
delegate void D(int x);
class C
{
void M()
{
D d = new D([|Test|]);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestInStructBaseList()
{
await TestInRegularAndScriptAsync(
@"struct S : [|A|]
{
}",
@"struct S : A
{
}
internal interface A
{
}",
index: 1);
}
[WorkItem(539870, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539870")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenericWhenNonGenericExists()
{
await TestInRegularAndScriptAsync(
@"class C
{
void Goo()
{
[|A<T>|] a;
}
}
class A
{
}",
@"class C
{
void Goo()
{
A<T> a;
}
}
internal class A<T>
{
}
class A
{
}",
index: 1);
}
[WorkItem(539930, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539930")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestInheritedTypeParameters()
{
await TestInRegularAndScriptAsync(
@"class C<T, R>
{
void M()
{
I<T, R> i = new [|D<T, R>|]();
}
}
interface I<T, R>
{
}",
@"class C<T, R>
{
void M()
{
I<T, R> i = new D<T, R>();
}
}
internal class D<T, R> : I<T, R>
{
}
interface I<T, R>
{
}",
index: 1);
}
[WorkItem(539971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539971")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDoNotUseOuterTypeParameters()
{
await TestInRegularAndScriptAsync(
@"class C<T1, T2>
{
public void Goo()
{
[|D<int, string>|] d;
}
}",
@"class C<T1, T2>
{
public void Goo()
{
D<int, string> d;
}
private class D<T3, T4>
{
}
}",
index: 2);
}
[WorkItem(539970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539970")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestReferencingTypeParameters1()
{
await TestInRegularAndScriptAsync(
@"class M<T, R>
{
public void Goo()
{
I<T, R> i = new [|C<int, string>|]();
}
}
interface I<T, R>
{
}",
@"class M<T, R>
{
public void Goo()
{
I<T, R> i = new C<int, string>();
}
}
internal class C<T1, T2> : I<object, object>
{
}
interface I<T, R>
{
}",
index: 1);
}
[WorkItem(539970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539970")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestReferencingTypeParameters2()
{
await TestInRegularAndScriptAsync(
@"class M<T, R>
{
public void Goo()
{
I<T, R> i = new [|C<int, string>|]();
}
}
interface I<T, R>
{
}",
@"class M<T, R>
{
public void Goo()
{
I<T, R> i = new C<int, string>();
}
private class C<T1, T2> : I<T, R>
{
}
}
interface I<T, R>
{
}",
index: 2);
}
[WorkItem(539972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539972")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestReferencingTypeParameters3()
{
await TestInRegularAndScriptAsync(
@"class C<T1, T2>
{
public void Goo(T1 t1, T2 t2)
{
A a = new [|A|](t1, t2);
}
}",
@"class C<T1, T2>
{
public void Goo(T1 t1, T2 t2)
{
A a = new A(t1, t2);
}
}
internal class A
{
private object t1;
private object t2;
public A(object t1, object t2)
{
this.t1 = t1;
this.t2 = t2;
}
}",
index: 1);
}
[WorkItem(539972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539972")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestReferencingTypeParameters4()
{
await TestInRegularAndScriptAsync(
@"class C<T1, T2>
{
public void Goo(T1 t1, T2 t2)
{
A a = new [|A|](t1, t2);
}
}",
@"class C<T1, T2>
{
public void Goo(T1 t1, T2 t2)
{
A a = new A(t1, t2);
}
private class A
{
private T1 t1;
private T2 t2;
public A(T1 t1, T2 t2)
{
this.t1 = t1;
this.t2 = t2;
}
}
}",
index: 2);
}
[WorkItem(539992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539992")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNotPassingEmptyIssueListToCtor()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Linq;
class Program
{
void Main()
{
Enumerable.[|T|] Enumerable . Select(Enumerable.Range(0, 9), i => char.Parse(i.ToString())) }
}");
}
[WorkItem(540644, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540644")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateWithVoidArg()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void M()
{
C c = new [|C|](M());
}
}",
@"class Program
{
void M()
{
C c = new C(M());
}
}
internal class C
{
private object v;
public C(object v)
{
this.v = v;
}
}",
index: 1);
}
[WorkItem(540989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540989")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestMissingOnInaccessibleType()
{
await TestMissingInRegularAndScriptAsync(
@"class Outer
{
class Inner
{
}
}
class A
{
Outer.[|Inner|] inner;
}");
}
[WorkItem(540766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540766")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestOnInvalidGlobalCode()
{
await TestInRegularAndScriptAsync(
@"[|a|] test ",
@"[|a|] test internal class a
{
}",
index: 1);
}
[WorkItem(539985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539985")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDoNotInferTypeWithWrongArity()
{
await TestInRegularAndScriptAsync(
@"class C<T1>
{
public void Test()
{
C c = new [|C|]();
}
}",
@"class C<T1>
{
public void Test()
{
C c = new C();
}
}
internal class C
{
public C()
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestMissingOnInvalidConstructorToExistingType()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
new [|Program|](1);
}
}");
}
[WorkItem(541263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541263")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public static class MyExtension
{
public static int ExtensionMethod(this String s, [|D|] d)
{
return 10;
}
}",
@"public static class MyExtension
{
public static int ExtensionMethod(this String s, D d)
{
return 10;
}
}
public class D
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestBaseTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C : [|D|]
{
}",
@"public class C : D
{
}
public class D
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestBaseInterfaceAccessibilityConstraint1()
{
await TestInRegularAndScriptAsync(
@"public class C : X, [|IGoo|]
{
}",
@"public class C : X, IGoo
{
}
internal interface IGoo
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityConstraint2()
{
await TestInRegularAndScriptAsync(
@"public interface C : [|IBar|], IGoo
{
}",
@"public interface C : IBar, IGoo
{
}
public interface IBar
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityConstraint3()
{
await TestInRegularAndScriptAsync(
@"public interface C : IBar, [|IGoo|]
{
}",
@"public interface C : IBar, IGoo
{
}
public interface IGoo
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDelegateReturnTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public delegate [|D|] Goo();",
@"public delegate D Goo();
public class D
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDelegateParameterAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public delegate D Goo([|S|] d);",
@"public delegate D Goo(S d);
public class S
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestMethodParameterAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C
{
public void Goo([|F|] f);
}",
@"public class C
{
public void Goo(F f);
}
public class F
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestMethodReturnTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C
{
public [|F|] Goo(Bar f);
}",
@"public class C
{
public F Goo(Bar f);
public class F
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestPropertyTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C
{
public [|F|] Goo { get; }
}",
@"public class C
{
public F Goo { get; }
public class F
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestFieldEventTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C
{
public event [|F|] E;
}",
@"public class C
{
public event F E;
public class F
{
}
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestEventTypeAccessibilityConstraint()
{
await TestInRegularAndScriptAsync(
@"public class C
{
public event [|F|] E
{
add
{
}
remove
{
}
}
}",
@"public class C
{
public event F E
{
add
{
}
remove
{
}
}
}
public class F
{
}",
index: 1);
}
[WorkItem(541654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541654")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateVarType()
{
await TestInRegularAndScriptAsync(
@"class C
{
public static void Main()
{
[|@var|] v;
}
}",
@"class C
{
public static void Main()
{
@var v;
}
}
internal class var
{
}",
index: 1);
}
[WorkItem(541641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541641")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestOnBadAttribute()
{
await TestInRegularAndScriptAsync(
@"[[|AttClass|]()]
class C
{
}
internal class AttClassAttribute
{
}",
@"using System;
[AttClass()]
class C
{
}
internal class AttClassAttribute : Attribute
{
}
internal class AttClassAttribute
{
}",
index: 1);
}
[WorkItem(542528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542528")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateStruct1()
{
await TestInRegularAndScriptAsync(
@"using System;
class A<T> where T : struct
{
}
class Program
{
static void Main()
{
new A<[|S|]>();
}
}",
@"using System;
class A<T> where T : struct
{
}
class Program
{
static void Main()
{
new A<S>();
}
}
internal struct S
{
}",
index: 1);
}
[WorkItem(542480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542480")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestCopyConstraints1()
{
await TestInRegularAndScriptAsync(
@"class A<T> where T : class
{
}
class Program
{
static void Goo<T>() where T : class
{
A<T> a = new [|B<T>|]();
}
}",
@"class A<T> where T : class
{
}
class Program
{
static void Goo<T>() where T : class
{
A<T> a = new B<T>();
}
}
internal class B<T> : A<T> where T : class
{
}",
index: 1);
}
[WorkItem(542528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542528")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateStruct2()
{
await TestInRegularAndScriptAsync(
@"using System;
class A<T> where T : struct
{
}
class Program
{
static void Main()
{
new A<Program.[|S|]>();
}
}",
@"using System;
class A<T> where T : struct
{
}
class Program
{
static void Main()
{
new A<Program.S>();
}
private struct S
{
}
}");
}
[WorkItem(542528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542528")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateStruct3()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main()
{
Goo<Program.[|S|]>();
}
static void Goo<T>() where T : struct
{
}
}",
@"using System;
class Program
{
static void Main()
{
Goo<Program.S>();
}
static void Goo<T>() where T : struct
{
}
private struct S
{
}
}");
}
[WorkItem(542761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542761")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateOpenType1()
{
await TestInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
var x = typeof([|C<,>|]);
}
}",
@"class Program
{
static void Main()
{
var x = typeof(C<,>);
}
}
internal class C<T1, T2>
{
}",
index: 1);
}
[WorkItem(542766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542766")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateAttributeInGenericType()
{
await TestActionCountAsync(
@"using System;
class A<T>
{
[[|C|]]
void Goo()
{
}
}",
count: 6);
}
[WorkItem(543061, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543061")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNestedGenericAccessibility()
{
await TestInRegularAndScriptAsync(
@"using System.Collections.Generic;
public class C
{
public void Goo(List<[|NewClass|]> x)
{
}
}",
@"using System.Collections.Generic;
public class C
{
public void Goo(List<NewClass> x)
{
}
}
public class NewClass
{
}",
index: 1);
}
[WorkItem(543493, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543493")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task MissingIfNotInTypeStatementOrExpressionContext()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
a [|b|] c d }
}");
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
a b [|c|] d }
}");
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
a b c [|d|] }
}");
}
[WorkItem(542641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542641")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAttributeSuffixOnAttributeSubclasses()
{
await TestInRegularAndScriptAsync(
@"using System.Runtime.CompilerServices;
class Program
{
static void Main(string[] args)
{
CustomConstantAttribute a = new [|GooAttribute|]();
}
}",
@"using System.Runtime.CompilerServices;
class Program
{
static void Main(string[] args)
{
CustomConstantAttribute a = new GooAttribute();
}
}
internal class GooAttribute : CustomConstantAttribute
{
}",
index: 1);
}
[WorkItem(543853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543853")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestDisplayStringForGlobalNamespace()
{
await TestSmartTagTextAsync(
@"class C : [|Goo|]",
string.Format(FeaturesResources.Generate_0_1_in_new_file, "class", "Goo", FeaturesResources.Global_Namespace));
}
[WorkItem(543853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543853")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAddDocumentForGlobalNamespace()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class C : [|Goo|]",
@"internal class Goo
{
}",
ImmutableArray<string>.Empty,
"Goo.cs");
}
[WorkItem(543886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543886")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestVerbatimAttribute()
{
await TestInRegularAndScriptAsync(
@"[[|@X|]]
class Class3
{
}",
@"using System;
[@X]
class Class3
{
}
internal class X : Attribute
{
}",
index: 1);
}
[WorkItem(531220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531220")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task CompareIncompleteMembersToEqual()
{
await TestInRegularAndScriptAsync(
@"class C
{
X.X,X class X
{
X
}
X void X<X void X
x, [|x|])",
@"class C
{
X.X,X class X
{
X
}
X void X<X void X
x, x)private class x
{
}
}
",
index: 2);
}
[WorkItem(544168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544168")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestNotOnAbstractClassCreation()
{
await TestMissingInRegularAndScriptAsync(
@"abstract class Goo
{
}
class SomeClass
{
void goo()
{
var q = new [|Goo|]();
}
}");
}
[WorkItem(545362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545362")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateInVenus1()
{
var code = @"
#line hidden
#line 1 ""Default.aspx""
class Program
{
static void Main(string[] args)
{
[|Goo|] f;
#line hidden
#line 2 ""Default.aspx""
}
}
";
await TestExactActionSetOfferedAsync(code,
new[]
{
string.Format(FeaturesResources.Generate_0_1_in_new_file, "class", "Goo", FeaturesResources.Global_Namespace),
string.Format(FeaturesResources.Generate_nested_0_1, "class", "Goo", "Program"),
FeaturesResources.Generate_new_type
});
await TestInRegularAndScriptAsync(code,
@"
#line hidden
#line 1 ""Default.aspx""
class Program
{
static void Main(string[] args)
{
[|Goo|] f;
#line hidden
#line 2 ""Default.aspx""
}
private class Goo
{
}
}
", index: 1);
}
[WorkItem(869506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/869506")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeOutsideCurrentProject()
{
var code = @"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<ProjectReference>Assembly2</ProjectReference>
<Document FilePath=""Test1.cs"">
class Program
{
static void Main(string[] args)
{
[|A.B.C$$|].D f;
}
}
namespace A
{
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document FilePath=""Test2.cs"">
namespace A
{
public class B
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
namespace A
{
public class B
{
public class C
{
}
}
}
";
await TestInRegularAndScriptAsync(code, expected);
}
[WorkItem(932602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932602")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeInFolderNotDefaultNamespace_0()
{
var code = @"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DefaultNamespace = ""Namespace1.Namespace2"">
<Document FilePath=""Test1.cs"">
namespace Namespace1.Namespace2
{
public class ClassA : [|$$ClassB|]
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"namespace Namespace1.Namespace2
{
public class ClassB
{
}
}";
await TestAddDocumentInRegularAndScriptAsync(code,
expected,
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "ClassB.cs");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeInFolderNotDefaultNamespace_0_FileScopedNamespace()
{
var code = @"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DefaultNamespace = ""Namespace1.Namespace2"">
<Document FilePath=""Test1.cs"">
namespace Namespace1.Namespace2;
public class ClassA : [|$$ClassB|]
{
}
</Document>
</Project>
</Workspace>";
var expected = @"namespace Namespace1.Namespace2;
public class ClassB
{
}";
await TestAddDocumentInRegularAndScriptAsync(code,
expected,
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "ClassB.cs",
new TestParameters(
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10),
options: Option(CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped, NotificationOption2.Silent)));
}
[WorkItem(932602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932602")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeInFolderNotDefaultNamespace_1()
{
var code = @"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" DefaultNamespace = ""Namespace1.Namespace2"" >
<Document FilePath=""Test1.cs"" Folders=""Namespace1\Namespace2"">
namespace Namespace1.Namespace2.Namespace3
{
public class ClassA : [|$$ClassB|]
{
}
}
</Document>
</Project>
</Workspace>";
var expected = @"namespace Namespace1.Namespace2.Namespace3
{
public class ClassB
{
}
}";
await TestAddDocumentInRegularAndScriptAsync(code,
expected,
expectedContainers: ImmutableArray.Create("Namespace1", "Namespace2"),
expectedDocumentName: "ClassB.cs");
}
[WorkItem(612700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612700")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestGenerateTypeWithNoBraces()
{
var code = @"class Test : [|Base|]";
var expected = @"class Test : Base
internal class Base
{
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(940003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/940003")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithProperties1()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = ""John"", Age = DateTime.Today};
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new Customer(x: 1, y: ""Hello"") {Name = ""John"", Age = DateTime.Today};
}
}
internal class Customer
{
private int x;
private string y;
public Customer(int x, string y)
{
this.x = x;
this.y = y;
}
public string Name { get; set; }
public DateTime Age { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(940003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/940003")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithProperties2()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = null, Age = DateTime.Today};
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new Customer(x: 1, y: ""Hello"") {Name = null, Age = DateTime.Today};
}
}
internal class Customer
{
private int x;
private string y;
public Customer(int x, string y)
{
this.x = x;
this.y = y;
}
public object Name { get; set; }
public DateTime Age { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(940003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/940003")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithProperties3()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = Goo, Age = DateTime.Today};
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new Customer(x: 1, y: ""Hello"") {Name = Goo, Age = DateTime.Today};
}
}
internal class Customer
{
private int x;
private string y;
public Customer(int x, string y)
{
this.x = x;
this.y = y;
}
public object Name { get; set; }
public DateTime Age { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(1082031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082031")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithProperties4()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new [|Customer|] {Name = ""John"", Age = DateTime.Today};
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
var c = new Customer {Name = ""John"", Age = DateTime.Today};
}
}
internal class Customer
{
public string Name { get; set; }
public DateTime Age { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176"), WorkItem(1073099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithNameOf()
{
var code = @"class C
{
void M()
{
var x = nameof([|Z|]);
}
}
";
var expected = @"class C
{
void M()
{
var x = nameof(Z);
}
}
internal class Z
{
}";
await TestInRegularAndScriptAsync(code, expected, index: 1);
}
[WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176"), WorkItem(1073099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithNameOf2()
{
var code = @"class C
{
void M()
{
var x = nameof([|C.Test|]);
}
}";
var expected = @"class C
{
void M()
{
var x = nameof(C.Test);
}
private class Test
{
}
}";
await TestInRegularAndScriptAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithUsingStatic()
{
await TestInRegularAndScriptAsync(
@"using static [|Sample|];",
@"using static Sample;
internal class Sample
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestWithUsingStatic2()
{
await TestMissingInRegularAndScriptAsync(
@"using [|Sample|];");
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B b = new [|B|]();
}",
@"public class B
{
public B()
{
}
}");
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields2()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B b = new [|B|]();
}",
@"class A
{
public B b = new B();
}
public class B
{
public B()
{
}
}",
index: 1);
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields3()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B b = new [|B|]();
}",
@"class A
{
public B b = new B();
public class B
{
public B()
{
}
}
}",
index: 2);
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields4()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B<int> b = new [|B|]<int>();
}",
@"public class B<T>
{
public B()
{
}
}");
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields5()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B<int> b = new [|B|]<int>();
}",
@"class A
{
public B<int> b = new B<int>();
}
public class B<T>
{
public B()
{
}
}",
index: 1);
}
[WorkItem(1107929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107929")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestAccessibilityForPublicFields6()
{
await TestInRegularAndScriptAsync(
@"class A
{
public B<int> b = new [|B|]<int>();
}",
@"class A
{
public B<int> b = new B<int>();
public class B<T>
{
public B()
{
}
}
}",
index: 2);
}
[WorkItem(17361, "https://github.com/dotnet/roslyn/issues/17361")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestPreserveFileBanner1()
{
await TestAddDocumentInRegularAndScriptAsync(
@"// I am a banner
class Program
{
void Main ( )
{
[|Goo|] f ;
}
} ",
@"// I am a banner
internal class Goo
{
}",
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "Goo.cs");
}
[WorkItem(17361, "https://github.com/dotnet/roslyn/issues/17361")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestPreserveFileBanner2()
{
await TestAddDocumentInRegularAndScriptAsync(
@"/// I am a doc comment
class Program
{
void Main ( )
{
[|Goo|] f ;
}
} ",
@"internal class Goo
{
}",
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "Goo.cs");
}
[WorkItem(17361, "https://github.com/dotnet/roslyn/issues/17361")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestPreserveFileBanner3()
{
await TestAddDocumentInRegularAndScriptAsync(
@"// I am a banner
using System;
class Program
{
void Main (StackOverflowException e)
{
var f = new [|Goo|](e);
}
}",
@"// I am a banner
using System;
internal class Goo
{
private StackOverflowException e;
public Goo(StackOverflowException e)
{
this.e = e;
}
}",
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "Goo.cs");
}
[WorkItem(17361, "https://github.com/dotnet/roslyn/issues/17361")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public async Task TestPreserveFileBanner4()
{
await TestAddDocumentInRegularAndScriptAsync(
@"class Program
{
void Main ( )
{
[|Goo|] f ;
}
} ",
@"// I am a banner
internal class Goo
{
}",
expectedContainers: ImmutableArray<string>.Empty,
expectedDocumentName: "Goo.cs",
new TestParameters(options: Option(CodeStyleOptions2.FileHeaderTemplate, "I am a banner")));
}
[WorkItem(22293, "https://github.com/dotnet/roslyn/issues/22293")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
[InlineData("void")]
[InlineData("int")]
public async Task TestMethodGroupWithMissingSystemActionAndFunc(string returnType)
{
await TestInRegularAndScriptAsync(
$@"
<Workspace>
<Project Language=""C#"" CommonReferences=""false"">
<Document><;
}}
{returnType} Method()
{{
}}
}}
]]>
</Document>
</Project>
</Workspace>",
$@"
class C
{{
void M()
{{
new Class(Method);
}}
{returnType} Method()
{{
}}
}}
internal class Class
{{
private global::System.Object method;
public Class(global::System.Object method)
{{
this.method = method;
}}
}}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
[WorkItem(270, "https://github.com/dotnet/roslyn/issues/270")]
public async Task TestGenerateInIsExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
class Program
{
static void Main(Exception p)
{
bool result = p is [|SampleType|];
}
}",
@"using System;
using System.Runtime.Serialization;
class Program
{
static void Main(Exception p)
{
bool result = p is SampleType;
}
}
[Serializable]
internal class SampleType : Exception
{
public SampleType()
{
}
public SampleType(string message) : base(message)
{
}
public SampleType(string message, Exception innerException) : base(message, innerException)
{
}
protected SampleType(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
[WorkItem(45808, "https://github.com/dotnet/roslyn/issues/45808")]
public async Task TestGenerateUnsafe()
{
await TestInRegularAndScriptAsync(
@"class C
{
unsafe void M(int* x)
{
new [|D|](x);
}
}",
@"class C
{
unsafe void M(int* x)
{
new D(x);
}
}
internal class D
{
private unsafe int* x;
public unsafe D(int* x)
{
this.x = x;
}
}", index: 1);
}
}
}
| 1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.Editor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
{
protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType);
private partial class Editor
{
private readonly TService _service;
private TargetProjectChangeInLanguage _targetProjectChangeInLanguage = TargetProjectChangeInLanguage.NoChange;
private IGenerateTypeService _targetLanguageService;
private readonly SemanticDocument _semanticDocument;
private readonly State _state;
private readonly bool _intoNamespace;
private readonly bool _inNewFile;
private readonly bool _fromDialog;
private readonly GenerateTypeOptionsResult _generateTypeOptionsResult;
private readonly CancellationToken _cancellationToken;
public Editor(
TService service,
SemanticDocument document,
State state,
bool intoNamespace,
bool inNewFile,
CancellationToken cancellationToken)
{
_service = service;
_semanticDocument = document;
_state = state;
_intoNamespace = intoNamespace;
_inNewFile = inNewFile;
_cancellationToken = cancellationToken;
}
public Editor(
TService service,
SemanticDocument document,
State state,
bool fromDialog,
GenerateTypeOptionsResult generateTypeOptionsResult,
CancellationToken cancellationToken)
{
// the document comes from the same snapshot as the project
Contract.ThrowIfFalse(document.Project.Solution == generateTypeOptionsResult.Project.Solution);
_service = service;
_semanticDocument = document;
_state = state;
_fromDialog = fromDialog;
_generateTypeOptionsResult = generateTypeOptionsResult;
_cancellationToken = cancellationToken;
}
private enum TargetProjectChangeInLanguage
{
NoChange,
CSharpToVisualBasic,
VisualBasicToCSharp
}
internal async Task<IEnumerable<CodeActionOperation>> GetOperationsAsync()
{
// Check to see if it is from GFU Dialog
if (!_fromDialog)
{
// Generate the actual type declaration.
var namedType = await GenerateNamedTypeAsync().ConfigureAwait(false);
if (_intoNamespace)
{
if (_inNewFile)
{
// Generating into a new file is somewhat complicated.
var documentName = GetTypeName(_state) + _service.DefaultFileExtension;
return await GetGenerateInNewFileOperationsAsync(
namedType,
documentName,
null,
true,
null,
_semanticDocument.Project,
_semanticDocument.Project,
isDialog: false).ConfigureAwait(false);
}
else
{
return await GetGenerateIntoContainingNamespaceOperationsAsync(namedType).ConfigureAwait(false);
}
}
else
{
return await GetGenerateIntoTypeOperationsAsync(namedType).ConfigureAwait(false);
}
}
else
{
var namedType = await GenerateNamedTypeAsync(_generateTypeOptionsResult).ConfigureAwait(false);
// Honor the options from the dialog
// Check to see if the type is requested to be generated in cross language Project
// e.g.: C# -> VB or VB -> C#
if (_semanticDocument.Project.Language != _generateTypeOptionsResult.Project.Language)
{
_targetProjectChangeInLanguage =
_generateTypeOptionsResult.Project.Language == LanguageNames.CSharp
? TargetProjectChangeInLanguage.VisualBasicToCSharp
: TargetProjectChangeInLanguage.CSharpToVisualBasic;
// Get the cross language service
_targetLanguageService = _generateTypeOptionsResult.Project.LanguageServices.GetService<IGenerateTypeService>();
}
if (_generateTypeOptionsResult.IsNewFile)
{
return await GetGenerateInNewFileOperationsAsync(
namedType,
_generateTypeOptionsResult.NewFileName,
_generateTypeOptionsResult.Folders,
_generateTypeOptionsResult.AreFoldersValidIdentifiers,
_generateTypeOptionsResult.FullFilePath,
_generateTypeOptionsResult.Project,
_semanticDocument.Project,
isDialog: true).ConfigureAwait(false);
}
else
{
return await GetGenerateIntoExistingDocumentAsync(
namedType,
_semanticDocument.Project,
_generateTypeOptionsResult,
isDialog: true).ConfigureAwait(false);
}
}
}
private string GetNamespaceToGenerateInto()
{
var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim();
var rootNamespace = _service.GetRootNamespace(_semanticDocument.SemanticModel.Compilation.Options).Trim();
if (!string.IsNullOrWhiteSpace(rootNamespace))
{
if (namespaceToGenerateInto == rootNamespace ||
namespaceToGenerateInto.StartsWith(rootNamespace + ".", StringComparison.Ordinal))
{
namespaceToGenerateInto = namespaceToGenerateInto[rootNamespace.Length..];
}
}
return namespaceToGenerateInto;
}
private string GetNamespaceToGenerateIntoForUsageWithNamespace(Project targetProject, Project triggeringProject)
{
var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim();
if (targetProject.Language == LanguageNames.CSharp ||
targetProject == triggeringProject)
{
// If the target project is C# project then we don't have to make any modification to the namespace
// or
// This is a VB project generation into itself which requires no change as well
return namespaceToGenerateInto;
}
// If the target Project is VB then we have to check if the RootNamespace of the VB project is the parent most namespace of the type being generated
// True, Remove the RootNamespace
// False, Add Global to the Namespace
Debug.Assert(targetProject.Language == LanguageNames.VisualBasic);
IGenerateTypeService targetLanguageService;
if (_semanticDocument.Project.Language == LanguageNames.VisualBasic)
{
targetLanguageService = _service;
}
else
{
Debug.Assert(_targetLanguageService != null);
targetLanguageService = _targetLanguageService;
}
var rootNamespace = targetLanguageService.GetRootNamespace(targetProject.CompilationOptions).Trim();
if (!string.IsNullOrWhiteSpace(rootNamespace))
{
var rootNamespaceLength = CheckIfRootNamespacePresentInNamespace(namespaceToGenerateInto, rootNamespace);
if (rootNamespaceLength > -1)
{
// True, Remove the RootNamespace
namespaceToGenerateInto = namespaceToGenerateInto[rootNamespaceLength..];
}
else
{
// False, Add Global to the Namespace
namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto);
}
}
else
{
// False, Add Global to the Namespace
namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto);
}
return namespaceToGenerateInto;
}
private static string AddGlobalDotToTheNamespace(string namespaceToBeGenerated)
=> "Global." + namespaceToBeGenerated;
// Returns the length of the meaningful rootNamespace substring part of namespaceToGenerateInto
private static int CheckIfRootNamespacePresentInNamespace(string namespaceToGenerateInto, string rootNamespace)
{
if (namespaceToGenerateInto == rootNamespace)
{
return rootNamespace.Length;
}
if (namespaceToGenerateInto.StartsWith(rootNamespace + ".", StringComparison.Ordinal))
{
return rootNamespace.Length + 1;
}
return -1;
}
private static void AddFoldersToNamespaceContainers(List<string> container, IList<string> folders)
{
// Add the folder as part of the namespace if there are not empty
if (folders != null && folders.Count != 0)
{
// Remove the empty entries and replace the spaces in the folder name to '_'
var refinedFolders = folders.Where(n => n != null && !n.IsEmpty()).Select(n => n.Replace(' ', '_')).ToArray();
container.AddRange(refinedFolders);
}
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateInNewFileOperationsAsync(
INamedTypeSymbol namedType,
string documentName,
IList<string> folders,
bool areFoldersValidIdentifiers,
string fullFilePath,
Project projectToBeUpdated,
Project triggeringProject,
bool isDialog)
{
// First, we fork the solution with a new, empty, file in it.
var newDocumentId = DocumentId.CreateNewId(projectToBeUpdated.Id, debugName: documentName);
var newSolution = projectToBeUpdated.Solution.AddDocument(newDocumentId, documentName, string.Empty, folders, fullFilePath);
// Now we get the semantic model for that file we just added. We do that to get the
// root namespace in that new document, along with location for that new namespace.
// That way, when we use the code gen service we can say "add this symbol to the
// root namespace" and it will pick the one in the new file.
var newDocument = newSolution.GetDocument(newDocumentId);
var newSemanticModel = await newDocument.GetSemanticModelAsync(_cancellationToken).ConfigureAwait(false);
var enclosingNamespace = newSemanticModel.GetEnclosingNamespace(0, _cancellationToken);
var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport(
isDialog, folders, areFoldersValidIdentifiers, projectToBeUpdated, triggeringProject);
var containers = namespaceContainersAndUsings.containers;
var includeUsingsOrImports = namespaceContainersAndUsings.usingOrImport;
var rootNamespaceOrType = namedType.GenerateRootNamespaceOrType(containers);
// Now, actually ask the code gen service to add this namespace or type to the root
// namespace in the new file. This will properly generate the code, and add any
// additional niceties like imports/usings.
var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync(
newSolution,
enclosingNamespace,
rootNamespaceOrType,
new CodeGenerationOptions(newSemanticModel.SyntaxTree.GetLocation(new TextSpan())),
_cancellationToken).ConfigureAwait(false);
// containers is determined to be
// 1: folders -> if triggered from Dialog
// 2: containers -> if triggered not from a Dialog but from QualifiedName
// 3: triggering document folder structure -> if triggered not from a Dialog and a SimpleName
var adjustedContainer = isDialog
? folders
: _state.SimpleName != _state.NameOrMemberAccessExpression
? containers.ToList()
: _semanticDocument.Document.Folders.ToList();
// Now, take the code that would be generated and actually create an edit that would
// produce a document with that code in it.
var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
if (newDocument.Project.Language == _semanticDocument.Document.Project.Language)
{
var syntaxFacts = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>();
var fileBanner = syntaxFacts.GetFileBanner(_semanticDocument.Root);
newRoot = newRoot.WithPrependedLeadingTrivia(fileBanner);
}
return await CreateAddDocumentAndUpdateUsingsOrImportsOperationsAsync(
projectToBeUpdated,
triggeringProject,
documentName,
newRoot,
includeUsingsOrImports,
adjustedContainer,
SourceCodeKind.Regular,
_cancellationToken).ConfigureAwait(false);
}
private async Task<IEnumerable<CodeActionOperation>> CreateAddDocumentAndUpdateUsingsOrImportsOperationsAsync(
Project projectToBeUpdated,
Project triggeringProject,
string documentName,
SyntaxNode root,
string includeUsingsOrImports,
IList<string> containers,
SourceCodeKind sourceCodeKind,
CancellationToken cancellationToken)
{
// TODO(cyrusn): make sure documentId is unique.
var documentId = DocumentId.CreateNewId(projectToBeUpdated.Id, documentName);
var updatedSolution = projectToBeUpdated.Solution.AddDocument(DocumentInfo.Create(
documentId,
documentName,
containers,
sourceCodeKind));
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity);
// Update the Generating Document with a using if required
if (includeUsingsOrImports != null)
{
updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync(updatedSolution, null, _semanticDocument.Document, _state.SimpleName, includeUsingsOrImports, cancellationToken).ConfigureAwait(false);
}
// Add reference of the updated project to the triggering Project if they are 2 different projects
updatedSolution = AddProjectReference(projectToBeUpdated, triggeringProject, updatedSolution);
return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution), new OpenDocumentOperation(documentId) };
}
private static Solution AddProjectReference(Project projectToBeUpdated, Project triggeringProject, Solution updatedSolution)
{
if (projectToBeUpdated != triggeringProject)
{
if (!triggeringProject.ProjectReferences.Any(pr => pr.ProjectId == projectToBeUpdated.Id))
{
updatedSolution = updatedSolution.AddProjectReference(triggeringProject.Id, new ProjectReference(projectToBeUpdated.Id));
}
}
return updatedSolution;
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoContainingNamespaceOperationsAsync(INamedTypeSymbol namedType)
{
var enclosingNamespace = _semanticDocument.SemanticModel.GetEnclosingNamespace(
_state.SimpleName.SpanStart, _cancellationToken);
var solution = _semanticDocument.Project.Solution;
var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync(
solution,
enclosingNamespace,
namedType,
new CodeGenerationOptions(
afterThisLocation: _semanticDocument.SyntaxTree.GetLocation(_state.SimpleName.Span),
options: await _semanticDocument.Document.GetOptionsAsync(_cancellationToken).ConfigureAwait(false)),
_cancellationToken).ConfigureAwait(false);
return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) };
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoExistingDocumentAsync(
INamedTypeSymbol namedType,
Project triggeringProject,
GenerateTypeOptionsResult generateTypeOptionsResult,
bool isDialog)
{
var root = await generateTypeOptionsResult.ExistingDocument.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var folders = generateTypeOptionsResult.ExistingDocument.Folders;
var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport(isDialog, new List<string>(folders), generateTypeOptionsResult.AreFoldersValidIdentifiers, generateTypeOptionsResult.Project, triggeringProject);
var containers = namespaceContainersAndUsings.containers;
var includeUsingsOrImports = namespaceContainersAndUsings.usingOrImport;
(INamespaceSymbol, INamespaceOrTypeSymbol, Location) enclosingNamespaceGeneratedTypeToAddAndLocation;
if (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange)
{
enclosingNamespaceGeneratedTypeToAddAndLocation = await _service.GetOrGenerateEnclosingNamespaceSymbolAsync(
namedType,
containers,
generateTypeOptionsResult.ExistingDocument,
root,
_cancellationToken).ConfigureAwait(false);
}
else
{
enclosingNamespaceGeneratedTypeToAddAndLocation = await _targetLanguageService.GetOrGenerateEnclosingNamespaceSymbolAsync(
namedType,
containers,
generateTypeOptionsResult.ExistingDocument,
root,
_cancellationToken).ConfigureAwait(false);
}
var solution = _semanticDocument.Project.Solution;
var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync(
solution,
enclosingNamespaceGeneratedTypeToAddAndLocation.Item1,
enclosingNamespaceGeneratedTypeToAddAndLocation.Item2,
new CodeGenerationOptions(afterThisLocation: enclosingNamespaceGeneratedTypeToAddAndLocation.Item3),
_cancellationToken)
.ConfigureAwait(false);
var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var updatedSolution = solution.WithDocumentSyntaxRoot(generateTypeOptionsResult.ExistingDocument.Id, newRoot, PreservationMode.PreserveIdentity);
// Update the Generating Document with a using if required
if (includeUsingsOrImports != null)
{
updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync(
updatedSolution,
generateTypeOptionsResult.ExistingDocument.Id == _semanticDocument.Document.Id ? newRoot : null,
_semanticDocument.Document,
_state.SimpleName,
includeUsingsOrImports,
_cancellationToken).ConfigureAwait(false);
}
updatedSolution = AddProjectReference(generateTypeOptionsResult.Project, triggeringProject, updatedSolution);
return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution) };
}
private (string[] containers, string usingOrImport) GetNamespaceContainersAndAddUsingsOrImport(
bool isDialog,
IList<string> folders,
bool areFoldersValidIdentifiers,
Project targetProject,
Project triggeringProject)
{
string includeUsingsOrImports = null;
if (!areFoldersValidIdentifiers)
{
folders = SpecializedCollections.EmptyList<string>();
}
// Now actually create the symbol that we want to add to the root namespace. The
// symbol may either be a named type (if we're not generating into a namespace) or
// it may be a namespace symbol.
string[] containers = null;
if (!isDialog)
{
// Not generated from the Dialog
containers = GetNamespaceToGenerateInto().Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
}
else if (!_service.IsSimpleName(_state.NameOrMemberAccessExpression))
{
// If the usage was with a namespace
containers = GetNamespaceToGenerateIntoForUsageWithNamespace(targetProject, triggeringProject).Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
}
else
{
// Generated from the Dialog
var containerList = new List<string>();
var rootNamespaceOfTheProjectGeneratedInto =
_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange
? _service.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim()
: _targetLanguageService.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim();
var defaultNamespace = _generateTypeOptionsResult.DefaultNamespace;
// Case 1 : If the type is generated into the same C# project or
// Case 2 : If the type is generated from a C# project to a C# Project
// Case 3 : If the Type is generated from a VB Project to a C# Project
// Using and Namespace will be the DefaultNamespace + Folder Structure
if ((_semanticDocument.Project == _generateTypeOptionsResult.Project && _semanticDocument.Project.Language == LanguageNames.CSharp) ||
(_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp) ||
_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.VisualBasicToCSharp)
{
if (!string.IsNullOrWhiteSpace(defaultNamespace))
{
containerList.Add(defaultNamespace);
}
// Populate the ContainerList
AddFoldersToNamespaceContainers(containerList, folders);
containers = containerList.ToArray();
includeUsingsOrImports = string.Join(".", containerList.ToArray());
}
// Case 4 : If the type is generated into the same VB project or
// Case 5 : If Type is generated from a VB Project to VB Project
// Case 6 : If Type is generated from a C# Project to VB Project
// Namespace will be Folder Structure and Import will have the RootNamespace of the project generated into as part of the Imports
if ((_semanticDocument.Project == _generateTypeOptionsResult.Project && _semanticDocument.Project.Language == LanguageNames.VisualBasic) ||
(_semanticDocument.Project != _generateTypeOptionsResult.Project && _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.VisualBasic) ||
_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.CSharpToVisualBasic)
{
// Populate the ContainerList
AddFoldersToNamespaceContainers(containerList, folders);
containers = containerList.ToArray();
includeUsingsOrImports = string.Join(".", containerList.ToArray());
if (!string.IsNullOrWhiteSpace(rootNamespaceOfTheProjectGeneratedInto))
{
includeUsingsOrImports = string.IsNullOrEmpty(includeUsingsOrImports) ?
rootNamespaceOfTheProjectGeneratedInto :
rootNamespaceOfTheProjectGeneratedInto + "." + includeUsingsOrImports;
}
}
Debug.Assert(includeUsingsOrImports != null);
}
return (containers, includeUsingsOrImports);
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoTypeOperationsAsync(INamedTypeSymbol namedType)
{
var solution = _semanticDocument.Project.Solution;
var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync(
solution,
_state.TypeToGenerateInOpt,
namedType,
new CodeGenerationOptions(contextLocation: _state.SimpleName.GetLocation()),
_cancellationToken)
.ConfigureAwait(false);
return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) };
}
private ImmutableArray<ITypeSymbol> GetArgumentTypes(IList<TArgumentSyntax> argumentList)
{
var types = argumentList.Select(a => _service.DetermineArgumentType(_semanticDocument.SemanticModel, a, _cancellationToken));
return types.SelectAsArray(FixType);
}
private ImmutableArray<TExpressionSyntax> GetArgumentExpressions(IList<TArgumentSyntax> argumentList)
{
var syntaxFacts = _semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>();
return argumentList.SelectAsArray(a => (TExpressionSyntax)syntaxFacts.GetExpressionOfArgument(a));
}
private ITypeSymbol FixType(
ITypeSymbol typeSymbol)
{
var compilation = _semanticDocument.SemanticModel.Compilation;
return typeSymbol.RemoveUnnamedErrorTypes(compilation);
}
private async Task<bool> FindExistingOrCreateNewMemberAsync(
ParameterName parameterName,
ITypeSymbol parameterType,
ImmutableDictionary<string, ISymbol>.Builder parameterToFieldMap,
ImmutableDictionary<string, string>.Builder parameterToNewFieldMap)
{
// If the base types have an accessible field or property with the same name and
// an acceptable type, then we should just defer to that.
if (_state.BaseTypeOrInterfaceOpt != null)
{
var expectedFieldName = parameterName.NameBasedOnArgument;
var members = from t in _state.BaseTypeOrInterfaceOpt.GetBaseTypesAndThis()
from m in t.GetMembers()
where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase)
where IsSymbolAccessible(m)
where IsViableFieldOrProperty(parameterType, m)
select m;
var membersArray = members.ToImmutableArray();
var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault();
if (symbol != null)
{
parameterToFieldMap[parameterName.BestNameForParameter] = symbol;
return true;
}
}
var fieldNamingRule = await _semanticDocument.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, _cancellationToken).ConfigureAwait(false);
var nameToUse = fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First();
parameterToNewFieldMap[parameterName.BestNameForParameter] = nameToUse;
return false;
}
private bool IsViableFieldOrProperty(
ITypeSymbol parameterType,
ISymbol symbol)
{
if (symbol != null && !symbol.IsStatic && parameterType.Language == symbol.Language)
{
if (symbol is IFieldSymbol field)
{
return
!field.IsReadOnly &&
_service.IsConversionImplicit(_semanticDocument.SemanticModel.Compilation, parameterType, field.Type);
}
else if (symbol is IPropertySymbol property)
{
return
property.Parameters.Length == 0 &&
property.SetMethod != null &&
IsSymbolAccessible(property.SetMethod) &&
_service.IsConversionImplicit(_semanticDocument.SemanticModel.Compilation, parameterType, property.Type);
}
}
return false;
}
private bool IsSymbolAccessible(ISymbol symbol)
{
// Public and protected constructors are accessible. Internal constructors are
// accessible if we have friend access. We can't call the normal accessibility
// checkers since they will think that a protected constructor isn't accessible
// (since we don't have the destination type that would have access to them yet).
switch (symbol.DeclaredAccessibility)
{
case Accessibility.ProtectedOrInternal:
case Accessibility.Protected:
case Accessibility.Public:
return true;
case Accessibility.ProtectedAndInternal:
case Accessibility.Internal:
// TODO: Code coverage
return _semanticDocument.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(
symbol.ContainingAssembly);
default:
return false;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
{
protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType);
private partial class Editor
{
private readonly TService _service;
private TargetProjectChangeInLanguage _targetProjectChangeInLanguage = TargetProjectChangeInLanguage.NoChange;
private IGenerateTypeService _targetLanguageService;
private readonly SemanticDocument _semanticDocument;
private readonly State _state;
private readonly bool _intoNamespace;
private readonly bool _inNewFile;
private readonly bool _fromDialog;
private readonly GenerateTypeOptionsResult _generateTypeOptionsResult;
private readonly CancellationToken _cancellationToken;
public Editor(
TService service,
SemanticDocument document,
State state,
bool intoNamespace,
bool inNewFile,
CancellationToken cancellationToken)
{
_service = service;
_semanticDocument = document;
_state = state;
_intoNamespace = intoNamespace;
_inNewFile = inNewFile;
_cancellationToken = cancellationToken;
}
public Editor(
TService service,
SemanticDocument document,
State state,
bool fromDialog,
GenerateTypeOptionsResult generateTypeOptionsResult,
CancellationToken cancellationToken)
{
// the document comes from the same snapshot as the project
Contract.ThrowIfFalse(document.Project.Solution == generateTypeOptionsResult.Project.Solution);
_service = service;
_semanticDocument = document;
_state = state;
_fromDialog = fromDialog;
_generateTypeOptionsResult = generateTypeOptionsResult;
_cancellationToken = cancellationToken;
}
private enum TargetProjectChangeInLanguage
{
NoChange,
CSharpToVisualBasic,
VisualBasicToCSharp
}
internal async Task<IEnumerable<CodeActionOperation>> GetOperationsAsync()
{
// Check to see if it is from GFU Dialog
if (!_fromDialog)
{
// Generate the actual type declaration.
var namedType = await GenerateNamedTypeAsync().ConfigureAwait(false);
if (_intoNamespace)
{
if (_inNewFile)
{
// Generating into a new file is somewhat complicated.
var documentName = GetTypeName(_state) + _service.DefaultFileExtension;
return await GetGenerateInNewFileOperationsAsync(
namedType,
documentName,
null,
true,
null,
_semanticDocument.Project,
_semanticDocument.Project,
isDialog: false).ConfigureAwait(false);
}
else
{
return await GetGenerateIntoContainingNamespaceOperationsAsync(namedType).ConfigureAwait(false);
}
}
else
{
return await GetGenerateIntoTypeOperationsAsync(namedType).ConfigureAwait(false);
}
}
else
{
var namedType = await GenerateNamedTypeAsync(_generateTypeOptionsResult).ConfigureAwait(false);
// Honor the options from the dialog
// Check to see if the type is requested to be generated in cross language Project
// e.g.: C# -> VB or VB -> C#
if (_semanticDocument.Project.Language != _generateTypeOptionsResult.Project.Language)
{
_targetProjectChangeInLanguage =
_generateTypeOptionsResult.Project.Language == LanguageNames.CSharp
? TargetProjectChangeInLanguage.VisualBasicToCSharp
: TargetProjectChangeInLanguage.CSharpToVisualBasic;
// Get the cross language service
_targetLanguageService = _generateTypeOptionsResult.Project.LanguageServices.GetService<IGenerateTypeService>();
}
if (_generateTypeOptionsResult.IsNewFile)
{
return await GetGenerateInNewFileOperationsAsync(
namedType,
_generateTypeOptionsResult.NewFileName,
_generateTypeOptionsResult.Folders,
_generateTypeOptionsResult.AreFoldersValidIdentifiers,
_generateTypeOptionsResult.FullFilePath,
_generateTypeOptionsResult.Project,
_semanticDocument.Project,
isDialog: true).ConfigureAwait(false);
}
else
{
return await GetGenerateIntoExistingDocumentAsync(
namedType,
_semanticDocument.Project,
_generateTypeOptionsResult,
isDialog: true).ConfigureAwait(false);
}
}
}
private string GetNamespaceToGenerateInto()
{
var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim();
var rootNamespace = _service.GetRootNamespace(_semanticDocument.SemanticModel.Compilation.Options).Trim();
if (!string.IsNullOrWhiteSpace(rootNamespace))
{
if (namespaceToGenerateInto == rootNamespace ||
namespaceToGenerateInto.StartsWith(rootNamespace + ".", StringComparison.Ordinal))
{
namespaceToGenerateInto = namespaceToGenerateInto[rootNamespace.Length..];
}
}
return namespaceToGenerateInto;
}
private string GetNamespaceToGenerateIntoForUsageWithNamespace(Project targetProject, Project triggeringProject)
{
var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim();
if (targetProject.Language == LanguageNames.CSharp ||
targetProject == triggeringProject)
{
// If the target project is C# project then we don't have to make any modification to the namespace
// or
// This is a VB project generation into itself which requires no change as well
return namespaceToGenerateInto;
}
// If the target Project is VB then we have to check if the RootNamespace of the VB project is the parent most namespace of the type being generated
// True, Remove the RootNamespace
// False, Add Global to the Namespace
Debug.Assert(targetProject.Language == LanguageNames.VisualBasic);
IGenerateTypeService targetLanguageService;
if (_semanticDocument.Project.Language == LanguageNames.VisualBasic)
{
targetLanguageService = _service;
}
else
{
Debug.Assert(_targetLanguageService != null);
targetLanguageService = _targetLanguageService;
}
var rootNamespace = targetLanguageService.GetRootNamespace(targetProject.CompilationOptions).Trim();
if (!string.IsNullOrWhiteSpace(rootNamespace))
{
var rootNamespaceLength = CheckIfRootNamespacePresentInNamespace(namespaceToGenerateInto, rootNamespace);
if (rootNamespaceLength > -1)
{
// True, Remove the RootNamespace
namespaceToGenerateInto = namespaceToGenerateInto[rootNamespaceLength..];
}
else
{
// False, Add Global to the Namespace
namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto);
}
}
else
{
// False, Add Global to the Namespace
namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto);
}
return namespaceToGenerateInto;
}
private static string AddGlobalDotToTheNamespace(string namespaceToBeGenerated)
=> "Global." + namespaceToBeGenerated;
// Returns the length of the meaningful rootNamespace substring part of namespaceToGenerateInto
private static int CheckIfRootNamespacePresentInNamespace(string namespaceToGenerateInto, string rootNamespace)
{
if (namespaceToGenerateInto == rootNamespace)
{
return rootNamespace.Length;
}
if (namespaceToGenerateInto.StartsWith(rootNamespace + ".", StringComparison.Ordinal))
{
return rootNamespace.Length + 1;
}
return -1;
}
private static void AddFoldersToNamespaceContainers(List<string> container, IList<string> folders)
{
// Add the folder as part of the namespace if there are not empty
if (folders != null && folders.Count != 0)
{
// Remove the empty entries and replace the spaces in the folder name to '_'
var refinedFolders = folders.Where(n => n != null && !n.IsEmpty()).Select(n => n.Replace(' ', '_')).ToArray();
container.AddRange(refinedFolders);
}
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateInNewFileOperationsAsync(
INamedTypeSymbol namedType,
string documentName,
IList<string> folders,
bool areFoldersValidIdentifiers,
string fullFilePath,
Project projectToBeUpdated,
Project triggeringProject,
bool isDialog)
{
// First, we fork the solution with a new, empty, file in it.
var newDocumentId = DocumentId.CreateNewId(projectToBeUpdated.Id, debugName: documentName);
var newSolution = projectToBeUpdated.Solution.AddDocument(newDocumentId, documentName, string.Empty, folders, fullFilePath);
// Now we get the semantic model for that file we just added. We do that to get the
// root namespace in that new document, along with location for that new namespace.
// That way, when we use the code gen service we can say "add this symbol to the
// root namespace" and it will pick the one in the new file.
var newDocument = newSolution.GetDocument(newDocumentId);
var newSemanticModel = await newDocument.GetSemanticModelAsync(_cancellationToken).ConfigureAwait(false);
var enclosingNamespace = newSemanticModel.GetEnclosingNamespace(0, _cancellationToken);
var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport(
isDialog, folders, areFoldersValidIdentifiers, projectToBeUpdated, triggeringProject);
var containers = namespaceContainersAndUsings.containers;
var includeUsingsOrImports = namespaceContainersAndUsings.usingOrImport;
var rootNamespaceOrType = namedType.GenerateRootNamespaceOrType(containers);
// Now, actually ask the code gen service to add this namespace or type to the root
// namespace in the new file. This will properly generate the code, and add any
// additional niceties like imports/usings.
var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync(
newSolution,
enclosingNamespace,
rootNamespaceOrType,
new CodeGenerationOptions(newSemanticModel.SyntaxTree.GetLocation(new TextSpan())),
_cancellationToken).ConfigureAwait(false);
// containers is determined to be
// 1: folders -> if triggered from Dialog
// 2: containers -> if triggered not from a Dialog but from QualifiedName
// 3: triggering document folder structure -> if triggered not from a Dialog and a SimpleName
var adjustedContainer = isDialog
? folders
: _state.SimpleName != _state.NameOrMemberAccessExpression
? containers.ToList()
: _semanticDocument.Document.Folders.ToList();
if (newDocument.Project.Language == _semanticDocument.Document.Project.Language)
{
var formattingService = newDocument.GetLanguageService<INewDocumentFormattingService>();
if (formattingService is not null)
{
codeGenResult = await formattingService.FormatNewDocumentAsync(codeGenResult, _semanticDocument.Document, _cancellationToken).ConfigureAwait(false);
}
}
// Now, take the code that would be generated and actually create an edit that would
// produce a document with that code in it.
var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
return await CreateAddDocumentAndUpdateUsingsOrImportsOperationsAsync(
projectToBeUpdated,
triggeringProject,
documentName,
newRoot,
includeUsingsOrImports,
adjustedContainer,
SourceCodeKind.Regular,
_cancellationToken).ConfigureAwait(false);
}
private async Task<IEnumerable<CodeActionOperation>> CreateAddDocumentAndUpdateUsingsOrImportsOperationsAsync(
Project projectToBeUpdated,
Project triggeringProject,
string documentName,
SyntaxNode root,
string includeUsingsOrImports,
IList<string> containers,
SourceCodeKind sourceCodeKind,
CancellationToken cancellationToken)
{
// TODO(cyrusn): make sure documentId is unique.
var documentId = DocumentId.CreateNewId(projectToBeUpdated.Id, documentName);
var updatedSolution = projectToBeUpdated.Solution.AddDocument(DocumentInfo.Create(
documentId,
documentName,
containers,
sourceCodeKind));
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity);
// Update the Generating Document with a using if required
if (includeUsingsOrImports != null)
{
updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync(updatedSolution, null, _semanticDocument.Document, _state.SimpleName, includeUsingsOrImports, cancellationToken).ConfigureAwait(false);
}
// Add reference of the updated project to the triggering Project if they are 2 different projects
updatedSolution = AddProjectReference(projectToBeUpdated, triggeringProject, updatedSolution);
return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution), new OpenDocumentOperation(documentId) };
}
private static Solution AddProjectReference(Project projectToBeUpdated, Project triggeringProject, Solution updatedSolution)
{
if (projectToBeUpdated != triggeringProject)
{
if (!triggeringProject.ProjectReferences.Any(pr => pr.ProjectId == projectToBeUpdated.Id))
{
updatedSolution = updatedSolution.AddProjectReference(triggeringProject.Id, new ProjectReference(projectToBeUpdated.Id));
}
}
return updatedSolution;
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoContainingNamespaceOperationsAsync(INamedTypeSymbol namedType)
{
var enclosingNamespace = _semanticDocument.SemanticModel.GetEnclosingNamespace(
_state.SimpleName.SpanStart, _cancellationToken);
var solution = _semanticDocument.Project.Solution;
var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync(
solution,
enclosingNamespace,
namedType,
new CodeGenerationOptions(
afterThisLocation: _semanticDocument.SyntaxTree.GetLocation(_state.SimpleName.Span),
options: await _semanticDocument.Document.GetOptionsAsync(_cancellationToken).ConfigureAwait(false)),
_cancellationToken).ConfigureAwait(false);
return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) };
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoExistingDocumentAsync(
INamedTypeSymbol namedType,
Project triggeringProject,
GenerateTypeOptionsResult generateTypeOptionsResult,
bool isDialog)
{
var root = await generateTypeOptionsResult.ExistingDocument.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var folders = generateTypeOptionsResult.ExistingDocument.Folders;
var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport(isDialog, new List<string>(folders), generateTypeOptionsResult.AreFoldersValidIdentifiers, generateTypeOptionsResult.Project, triggeringProject);
var containers = namespaceContainersAndUsings.containers;
var includeUsingsOrImports = namespaceContainersAndUsings.usingOrImport;
(INamespaceSymbol, INamespaceOrTypeSymbol, Location) enclosingNamespaceGeneratedTypeToAddAndLocation;
if (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange)
{
enclosingNamespaceGeneratedTypeToAddAndLocation = await _service.GetOrGenerateEnclosingNamespaceSymbolAsync(
namedType,
containers,
generateTypeOptionsResult.ExistingDocument,
root,
_cancellationToken).ConfigureAwait(false);
}
else
{
enclosingNamespaceGeneratedTypeToAddAndLocation = await _targetLanguageService.GetOrGenerateEnclosingNamespaceSymbolAsync(
namedType,
containers,
generateTypeOptionsResult.ExistingDocument,
root,
_cancellationToken).ConfigureAwait(false);
}
var solution = _semanticDocument.Project.Solution;
var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync(
solution,
enclosingNamespaceGeneratedTypeToAddAndLocation.Item1,
enclosingNamespaceGeneratedTypeToAddAndLocation.Item2,
new CodeGenerationOptions(afterThisLocation: enclosingNamespaceGeneratedTypeToAddAndLocation.Item3),
_cancellationToken)
.ConfigureAwait(false);
var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var updatedSolution = solution.WithDocumentSyntaxRoot(generateTypeOptionsResult.ExistingDocument.Id, newRoot, PreservationMode.PreserveIdentity);
// Update the Generating Document with a using if required
if (includeUsingsOrImports != null)
{
updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync(
updatedSolution,
generateTypeOptionsResult.ExistingDocument.Id == _semanticDocument.Document.Id ? newRoot : null,
_semanticDocument.Document,
_state.SimpleName,
includeUsingsOrImports,
_cancellationToken).ConfigureAwait(false);
}
updatedSolution = AddProjectReference(generateTypeOptionsResult.Project, triggeringProject, updatedSolution);
return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution) };
}
private (string[] containers, string usingOrImport) GetNamespaceContainersAndAddUsingsOrImport(
bool isDialog,
IList<string> folders,
bool areFoldersValidIdentifiers,
Project targetProject,
Project triggeringProject)
{
string includeUsingsOrImports = null;
if (!areFoldersValidIdentifiers)
{
folders = SpecializedCollections.EmptyList<string>();
}
// Now actually create the symbol that we want to add to the root namespace. The
// symbol may either be a named type (if we're not generating into a namespace) or
// it may be a namespace symbol.
string[] containers = null;
if (!isDialog)
{
// Not generated from the Dialog
containers = GetNamespaceToGenerateInto().Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
}
else if (!_service.IsSimpleName(_state.NameOrMemberAccessExpression))
{
// If the usage was with a namespace
containers = GetNamespaceToGenerateIntoForUsageWithNamespace(targetProject, triggeringProject).Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
}
else
{
// Generated from the Dialog
var containerList = new List<string>();
var rootNamespaceOfTheProjectGeneratedInto =
_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange
? _service.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim()
: _targetLanguageService.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim();
var defaultNamespace = _generateTypeOptionsResult.DefaultNamespace;
// Case 1 : If the type is generated into the same C# project or
// Case 2 : If the type is generated from a C# project to a C# Project
// Case 3 : If the Type is generated from a VB Project to a C# Project
// Using and Namespace will be the DefaultNamespace + Folder Structure
if ((_semanticDocument.Project == _generateTypeOptionsResult.Project && _semanticDocument.Project.Language == LanguageNames.CSharp) ||
(_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp) ||
_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.VisualBasicToCSharp)
{
if (!string.IsNullOrWhiteSpace(defaultNamespace))
{
containerList.Add(defaultNamespace);
}
// Populate the ContainerList
AddFoldersToNamespaceContainers(containerList, folders);
containers = containerList.ToArray();
includeUsingsOrImports = string.Join(".", containerList.ToArray());
}
// Case 4 : If the type is generated into the same VB project or
// Case 5 : If Type is generated from a VB Project to VB Project
// Case 6 : If Type is generated from a C# Project to VB Project
// Namespace will be Folder Structure and Import will have the RootNamespace of the project generated into as part of the Imports
if ((_semanticDocument.Project == _generateTypeOptionsResult.Project && _semanticDocument.Project.Language == LanguageNames.VisualBasic) ||
(_semanticDocument.Project != _generateTypeOptionsResult.Project && _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.VisualBasic) ||
_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.CSharpToVisualBasic)
{
// Populate the ContainerList
AddFoldersToNamespaceContainers(containerList, folders);
containers = containerList.ToArray();
includeUsingsOrImports = string.Join(".", containerList.ToArray());
if (!string.IsNullOrWhiteSpace(rootNamespaceOfTheProjectGeneratedInto))
{
includeUsingsOrImports = string.IsNullOrEmpty(includeUsingsOrImports) ?
rootNamespaceOfTheProjectGeneratedInto :
rootNamespaceOfTheProjectGeneratedInto + "." + includeUsingsOrImports;
}
}
Debug.Assert(includeUsingsOrImports != null);
}
return (containers, includeUsingsOrImports);
}
private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoTypeOperationsAsync(INamedTypeSymbol namedType)
{
var solution = _semanticDocument.Project.Solution;
var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync(
solution,
_state.TypeToGenerateInOpt,
namedType,
new CodeGenerationOptions(contextLocation: _state.SimpleName.GetLocation()),
_cancellationToken)
.ConfigureAwait(false);
return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) };
}
private ImmutableArray<ITypeSymbol> GetArgumentTypes(IList<TArgumentSyntax> argumentList)
{
var types = argumentList.Select(a => _service.DetermineArgumentType(_semanticDocument.SemanticModel, a, _cancellationToken));
return types.SelectAsArray(FixType);
}
private ImmutableArray<TExpressionSyntax> GetArgumentExpressions(IList<TArgumentSyntax> argumentList)
{
var syntaxFacts = _semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>();
return argumentList.SelectAsArray(a => (TExpressionSyntax)syntaxFacts.GetExpressionOfArgument(a));
}
private ITypeSymbol FixType(
ITypeSymbol typeSymbol)
{
var compilation = _semanticDocument.SemanticModel.Compilation;
return typeSymbol.RemoveUnnamedErrorTypes(compilation);
}
private async Task<bool> FindExistingOrCreateNewMemberAsync(
ParameterName parameterName,
ITypeSymbol parameterType,
ImmutableDictionary<string, ISymbol>.Builder parameterToFieldMap,
ImmutableDictionary<string, string>.Builder parameterToNewFieldMap)
{
// If the base types have an accessible field or property with the same name and
// an acceptable type, then we should just defer to that.
if (_state.BaseTypeOrInterfaceOpt != null)
{
var expectedFieldName = parameterName.NameBasedOnArgument;
var members = from t in _state.BaseTypeOrInterfaceOpt.GetBaseTypesAndThis()
from m in t.GetMembers()
where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase)
where IsSymbolAccessible(m)
where IsViableFieldOrProperty(parameterType, m)
select m;
var membersArray = members.ToImmutableArray();
var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault();
if (symbol != null)
{
parameterToFieldMap[parameterName.BestNameForParameter] = symbol;
return true;
}
}
var fieldNamingRule = await _semanticDocument.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, _cancellationToken).ConfigureAwait(false);
var nameToUse = fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First();
parameterToNewFieldMap[parameterName.BestNameForParameter] = nameToUse;
return false;
}
private bool IsViableFieldOrProperty(
ITypeSymbol parameterType,
ISymbol symbol)
{
if (symbol != null && !symbol.IsStatic && parameterType.Language == symbol.Language)
{
if (symbol is IFieldSymbol field)
{
return
!field.IsReadOnly &&
_service.IsConversionImplicit(_semanticDocument.SemanticModel.Compilation, parameterType, field.Type);
}
else if (symbol is IPropertySymbol property)
{
return
property.Parameters.Length == 0 &&
property.SetMethod != null &&
IsSymbolAccessible(property.SetMethod) &&
_service.IsConversionImplicit(_semanticDocument.SemanticModel.Compilation, parameterType, property.Type);
}
}
return false;
}
private bool IsSymbolAccessible(ISymbol symbol)
{
// Public and protected constructors are accessible. Internal constructors are
// accessible if we have friend access. We can't call the normal accessibility
// checkers since they will think that a protected constructor isn't accessible
// (since we don't have the destination type that would have access to them yet).
switch (symbol.DeclaredAccessibility)
{
case Accessibility.ProtectedOrInternal:
case Accessibility.Protected:
case Accessibility.Public:
return true;
case Accessibility.ProtectedAndInternal:
case Accessibility.Internal:
// TODO: Code coverage
return _semanticDocument.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(
symbol.ContainingAssembly);
default:
return false;
}
}
}
}
}
| 1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/VisualStudio/CSharp/Impl/LanguageService/CSharpEditorFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.FileHeaders;
using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.FileHeaders;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
[ExcludeFromCodeCoverage]
[Guid(Guids.CSharpEditorFactoryIdString)]
internal class CSharpEditorFactory : AbstractEditorFactory
{
public CSharpEditorFactory(IComponentModel componentModel)
: base(componentModel)
{
}
protected override string ContentTypeName => ContentTypeNames.CSharpContentType;
protected override string LanguageName => LanguageNames.CSharp;
protected override SyntaxGenerator SyntaxGenerator => CSharpSyntaxGenerator.Instance;
protected override SyntaxGeneratorInternal SyntaxGeneratorInternal => CSharpSyntaxGeneratorInternal.Instance;
protected override AbstractFileHeaderHelper FileHeaderHelper => CSharpFileHeaderHelper.Instance;
protected override async Task<Document> OrganizeUsingsCreatedFromTemplateAsync(Document document, CancellationToken cancellationToken)
{
var organizedDocument = await base.OrganizeUsingsCreatedFromTemplateAsync(document, cancellationToken).ConfigureAwait(false);
return await MisplacedUsingDirectivesCodeFixProvider.TransformDocumentIfRequiredAsync(organizedDocument, 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.
#nullable disable
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.FileHeaders;
using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.FileHeaders;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
[ExcludeFromCodeCoverage]
[Guid(Guids.CSharpEditorFactoryIdString)]
internal class CSharpEditorFactory : AbstractEditorFactory
{
public CSharpEditorFactory(IComponentModel componentModel)
: base(componentModel)
{
}
protected override string ContentTypeName => ContentTypeNames.CSharpContentType;
protected override string LanguageName => LanguageNames.CSharp;
}
}
| 1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/VisualStudio/Core/Def/Implementation/AbstractEditorFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.AddAccessibilityModifiers;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FileHeaders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Designer.Interfaces;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
/// <summary>
/// The base class of both the Roslyn editor factories.
/// </summary>
internal abstract class AbstractEditorFactory : IVsEditorFactory, IVsEditorFactory4, IVsEditorFactoryNotify
{
private readonly IComponentModel _componentModel;
private Microsoft.VisualStudio.OLE.Interop.IServiceProvider? _oleServiceProvider;
private bool _encoding;
protected AbstractEditorFactory(IComponentModel componentModel)
=> _componentModel = componentModel;
protected abstract string ContentTypeName { get; }
protected abstract string LanguageName { get; }
protected abstract SyntaxGenerator SyntaxGenerator { get; }
protected abstract SyntaxGeneratorInternal SyntaxGeneratorInternal { get; }
protected abstract AbstractFileHeaderHelper FileHeaderHelper { get; }
public void SetEncoding(bool value)
=> _encoding = value;
int IVsEditorFactory.Close()
=> VSConstants.S_OK;
public int CreateEditorInstance(
uint grfCreateDoc,
string pszMkDocument,
string? pszPhysicalView,
IVsHierarchy vsHierarchy,
uint itemid,
IntPtr punkDocDataExisting,
out IntPtr ppunkDocView,
out IntPtr ppunkDocData,
out string pbstrEditorCaption,
out Guid pguidCmdUI,
out int pgrfCDW)
{
Contract.ThrowIfNull(_oleServiceProvider);
ppunkDocView = IntPtr.Zero;
ppunkDocData = IntPtr.Zero;
pbstrEditorCaption = string.Empty;
pguidCmdUI = Guid.Empty;
pgrfCDW = 0;
var physicalView = pszPhysicalView ?? "Code";
IVsTextBuffer? textBuffer = null;
// Is this document already open? If so, let's see if it's a IVsTextBuffer we should re-use. This allows us
// to properly handle multiple windows open for the same document.
if (punkDocDataExisting != IntPtr.Zero)
{
var docDataExisting = Marshal.GetObjectForIUnknown(punkDocDataExisting);
textBuffer = docDataExisting as IVsTextBuffer;
if (textBuffer == null)
{
// We are incompatible with the existing doc data
return VSConstants.VS_E_INCOMPATIBLEDOCDATA;
}
}
var editorAdaptersFactoryService = _componentModel.GetService<IVsEditorAdaptersFactoryService>();
// Do we need to create a text buffer?
if (textBuffer == null)
{
textBuffer = (IVsTextBuffer)GetDocumentData(grfCreateDoc, pszMkDocument, vsHierarchy, itemid);
Contract.ThrowIfNull(textBuffer, $"Failed to get document data for {pszMkDocument}");
}
// If the text buffer is marked as read-only, ensure that the padlock icon is displayed
// next the new window's title and that [Read Only] is appended to title.
var readOnlyStatus = READONLYSTATUS.ROSTATUS_NotReadOnly;
if (ErrorHandler.Succeeded(textBuffer.GetStateFlags(out var textBufferFlags)) &&
0 != (textBufferFlags & ((uint)BUFFERSTATEFLAGS.BSF_FILESYS_READONLY | (uint)BUFFERSTATEFLAGS.BSF_USER_READONLY)))
{
readOnlyStatus = READONLYSTATUS.ROSTATUS_ReadOnly;
}
switch (physicalView)
{
case "Form":
// We must create the WinForms designer here
var loaderName = GetWinFormsLoaderName(vsHierarchy);
var designerService = (IVSMDDesignerService)Microsoft.VisualStudio.Shell.PackageUtilities.QueryService<SVSMDDesignerService>(_oleServiceProvider);
var designerLoader = (IVSMDDesignerLoader)designerService.CreateDesignerLoader(loaderName);
if (designerLoader is null)
{
goto case "Code";
}
try
{
designerLoader.Initialize(_oleServiceProvider, vsHierarchy, (int)itemid, (IVsTextLines)textBuffer);
pbstrEditorCaption = designerLoader.GetEditorCaption((int)readOnlyStatus);
var designer = designerService.CreateDesigner(_oleServiceProvider, designerLoader);
ppunkDocView = Marshal.GetIUnknownForObject(designer.View);
pguidCmdUI = designer.CommandGuid;
}
catch
{
// Only dispose the designer loader on failure to create a designer.
// The IVSMDDesignerService.CreateDesigner() method in VS passes it into the DesignSurface that gets created
// and is used to perform the actual load (and reloads -- which happen during normal designer operation).
// http://index/?leftProject=Microsoft.VisualStudio.Design&leftSymbol=n8p1tszkfyz7&file=DesignerActivationService.cs&line=629
designerLoader.Dispose();
throw;
}
break;
case "Code":
var codeWindow = editorAdaptersFactoryService.CreateVsCodeWindowAdapter(_oleServiceProvider);
codeWindow.SetBuffer((IVsTextLines)textBuffer);
codeWindow.GetEditorCaption(readOnlyStatus, out pbstrEditorCaption);
ppunkDocView = Marshal.GetIUnknownForObject(codeWindow);
pguidCmdUI = VSConstants.GUID_TextEditorFactory;
break;
default:
return VSConstants.E_INVALIDARG;
}
ppunkDocData = Marshal.GetIUnknownForObject(textBuffer);
return VSConstants.S_OK;
}
public object GetDocumentData(uint grfCreate, string pszMkDocument, IVsHierarchy pHier, uint itemid)
{
Contract.ThrowIfNull(_oleServiceProvider);
var editorAdaptersFactoryService = _componentModel.GetService<IVsEditorAdaptersFactoryService>();
var contentTypeRegistryService = _componentModel.GetService<IContentTypeRegistryService>();
var contentType = contentTypeRegistryService.GetContentType(ContentTypeName);
var textBuffer = editorAdaptersFactoryService.CreateVsTextBufferAdapter(_oleServiceProvider, contentType);
if (_encoding)
{
if (textBuffer is IVsUserData userData)
{
// The editor shims require that the boxed value when setting the PromptOnLoad flag is a uint
var hresult = userData.SetData(
VSConstants.VsTextBufferUserDataGuid.VsBufferEncodingPromptOnLoad_guid,
(uint)__PROMPTONLOADFLAGS.codepagePrompt);
Marshal.ThrowExceptionForHR(hresult);
}
}
return textBuffer;
}
public object GetDocumentView(uint grfCreate, string pszPhysicalView, IVsHierarchy pHier, IntPtr punkDocData, uint itemid)
{
// There is no scenario need currently to implement this method.
throw new NotImplementedException();
}
public string GetEditorCaption(string pszMkDocument, string pszPhysicalView, IVsHierarchy pHier, IntPtr punkDocData, out Guid pguidCmdUI)
{
// It is not possible to get this information without initializing the designer.
// There is no other scenario need currently to implement this method.
throw new NotImplementedException();
}
public bool ShouldDeferUntilIntellisenseIsReady(uint grfCreate, string pszMkDocument, string pszPhysicalView)
{
return "Form".Equals(pszPhysicalView, StringComparison.OrdinalIgnoreCase);
}
private static string GetWinFormsLoaderName(IVsHierarchy vsHierarchy)
{
const string LoaderName = "Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader";
const string NewLoaderName = "Microsoft.VisualStudio.Design.Core.Serialization.CodeDom.VSCodeDomDesignerLoader";
// If this is a netcoreapp3.0 (or newer), we must create the newer WinForms designer.
// TODO: This check will eventually move into the WinForms designer itself.
if (!vsHierarchy.TryGetTargetFrameworkMoniker((uint)VSConstants.VSITEMID.Root, out var targetFrameworkMoniker) ||
string.IsNullOrWhiteSpace(targetFrameworkMoniker))
{
return LoaderName;
}
try
{
var frameworkName = new FrameworkName(targetFrameworkMoniker);
if (frameworkName.Identifier == ".NETCoreApp" && frameworkName.Version?.Major >= 3)
{
return NewLoaderName;
}
}
catch
{
// Fall back to the old loader name if there are any failures
// while parsing the TFM.
}
return LoaderName;
}
public int MapLogicalView(ref Guid rguidLogicalView, out string? pbstrPhysicalView)
{
pbstrPhysicalView = null;
if (rguidLogicalView == VSConstants.LOGVIEWID.Primary_guid ||
rguidLogicalView == VSConstants.LOGVIEWID.Debugging_guid ||
rguidLogicalView == VSConstants.LOGVIEWID.Code_guid ||
rguidLogicalView == VSConstants.LOGVIEWID.TextView_guid)
{
return VSConstants.S_OK;
}
else if (rguidLogicalView == VSConstants.LOGVIEWID.Designer_guid)
{
pbstrPhysicalView = "Form";
return VSConstants.S_OK;
}
else
{
return VSConstants.E_NOTIMPL;
}
}
int IVsEditorFactory.SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
{
_oleServiceProvider = psp;
return VSConstants.S_OK;
}
int IVsEditorFactoryNotify.NotifyDependentItemSaved(IVsHierarchy pHier, uint itemidParent, string pszMkDocumentParent, uint itemidDpendent, string pszMkDocumentDependent)
=> VSConstants.S_OK;
int IVsEditorFactoryNotify.NotifyItemAdded(uint grfEFN, IVsHierarchy pHier, uint itemid, string pszMkDocument)
{
// Is this being added from a template?
if (((__EFNFLAGS)grfEFN & __EFNFLAGS.EFN_ClonedFromTemplate) != 0)
{
var uiThreadOperationExecutor = _componentModel.GetService<IUIThreadOperationExecutor>();
// TODO(cyrusn): Can this be cancellable?
uiThreadOperationExecutor.Execute(
"Intellisense",
defaultDescription: "",
allowCancellation: false,
showProgress: false,
action: c => FormatDocumentCreatedFromTemplate(pHier, itemid, pszMkDocument, c.UserCancellationToken));
}
return VSConstants.S_OK;
}
int IVsEditorFactoryNotify.NotifyItemRenamed(IVsHierarchy pHier, uint itemid, string pszMkDocumentOld, string pszMkDocumentNew)
=> VSConstants.S_OK;
protected virtual Task<Document> OrganizeUsingsCreatedFromTemplateAsync(Document document, CancellationToken cancellationToken)
=> Formatter.OrganizeImportsAsync(document, cancellationToken);
private void FormatDocumentCreatedFromTemplate(IVsHierarchy hierarchy, uint itemid, string filePath, CancellationToken cancellationToken)
{
Microsoft.VisualStudio.Shell.ThreadHelper.JoinableTaskFactory.Run(() => FormatDocumentCreatedFromTemplateAsync(hierarchy, itemid, filePath, cancellationToken));
}
private async Task FormatDocumentCreatedFromTemplateAsync(IVsHierarchy hierarchy, uint itemid, string filePath, CancellationToken cancellationToken)
{
// A file has been created on disk which the user added from the "Add Item" dialog. We need
// to include this in a workspace to figure out the right options it should be formatted with.
// This requires us to place it in the correct project.
var workspace = _componentModel.GetService<VisualStudioWorkspace>();
var solution = workspace.CurrentSolution;
ProjectId? projectIdToAddTo = null;
foreach (var projectId in solution.ProjectIds)
{
if (workspace.GetHierarchy(projectId) == hierarchy)
{
projectIdToAddTo = projectId;
break;
}
}
if (projectIdToAddTo == null)
{
// We don't have a project for this, so we'll just make up a fake project altogether
var temporaryProject = solution.AddProject(
name: nameof(FormatDocumentCreatedFromTemplate),
assemblyName: nameof(FormatDocumentCreatedFromTemplate),
language: LanguageName);
solution = temporaryProject.Solution;
projectIdToAddTo = temporaryProject.Id;
}
var documentId = DocumentId.CreateNewId(projectIdToAddTo);
var forkedSolution = solution.AddDocument(DocumentInfo.Create(documentId, filePath, loader: new FileTextLoader(filePath, defaultEncoding: null), filePath: filePath));
var addedDocument = forkedSolution.GetDocument(documentId)!;
var rootToFormat = await addedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(true);
var documentOptions = await addedDocument.GetOptionsAsync(cancellationToken).ConfigureAwait(true);
// Apply file header preferences
var fileHeaderTemplate = documentOptions.GetOption(CodeStyleOptions2.FileHeaderTemplate);
if (!string.IsNullOrEmpty(fileHeaderTemplate))
{
var newLineText = documentOptions.GetOption(FormattingOptions.NewLine, rootToFormat.Language);
var newLineTrivia = SyntaxGeneratorInternal.EndOfLine(newLineText);
var rootWithFileHeader = await AbstractFileHeaderCodeFixProvider.GetTransformedSyntaxRootAsync(
SyntaxGenerator.SyntaxFacts,
FileHeaderHelper,
newLineTrivia,
addedDocument,
cancellationToken).ConfigureAwait(true);
addedDocument = addedDocument.WithSyntaxRoot(rootWithFileHeader);
rootToFormat = rootWithFileHeader;
}
// Organize using directives
addedDocument = await OrganizeUsingsCreatedFromTemplateAsync(addedDocument, cancellationToken).ConfigureAwait(true);
rootToFormat = await addedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(true);
// Add access modifier
var accessibilityPreferences = documentOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, addedDocument.Project.Language);
if (addedDocument.Project.Language == LanguageNames.CSharp &&
accessibilityPreferences.Value != AccessibilityModifiersRequired.Never)
{
addedDocument = await AddAccessibilityModifiersAsync(addedDocument, accessibilityPreferences.Value, cancellationToken).ConfigureAwait(true);
rootToFormat = await addedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(true);
}
// Format document
var unformattedText = await addedDocument.GetTextAsync(cancellationToken).ConfigureAwait(true);
var formattedRoot = Formatter.Format(rootToFormat, workspace, documentOptions, cancellationToken);
var formattedText = formattedRoot.GetText(unformattedText.Encoding, unformattedText.ChecksumAlgorithm);
// Ensure the line endings are normalized. The formatter doesn't touch everything if it doesn't need to.
var targetLineEnding = documentOptions.GetOption(FormattingOptions.NewLine)!;
var originalText = formattedText;
foreach (var originalLine in originalText.Lines)
{
var originalNewLine = originalText.ToString(CodeAnalysis.Text.TextSpan.FromBounds(originalLine.End, originalLine.EndIncludingLineBreak));
// Check if we have a line ending, so we don't go adding one to the end if we don't need to.
if (originalNewLine.Length > 0 && originalNewLine != targetLineEnding)
{
var currentLine = formattedText.Lines[originalLine.LineNumber];
var currentSpan = CodeAnalysis.Text.TextSpan.FromBounds(currentLine.End, currentLine.EndIncludingLineBreak);
formattedText = formattedText.WithChanges(new TextChange(currentSpan, targetLineEnding));
}
}
IOUtilities.PerformIO(() =>
{
using var textWriter = new StreamWriter(filePath, append: false, encoding: formattedText.Encoding);
// We pass null here for cancellation, since cancelling in the middle of the file write would leave the file corrupted
formattedText.Write(textWriter, cancellationToken: CancellationToken.None);
});
}
private static async Task<Document> AddAccessibilityModifiersAsync(
Document document, AccessibilityModifiersRequired option, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(true);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(true);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var typeDeclarations = root.DescendantNodes().Where(node => syntaxFacts.IsTypeDeclaration(node));
var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
var service = document.GetRequiredLanguageService<IAddAccessibilityModifiersService>();
foreach (var declaration in typeDeclarations)
{
if (!service.ShouldUpdateAccessibilityModifier(syntaxFacts, declaration, option, out _))
continue;
var type = semanticModel.GetDeclaredSymbol(declaration, cancellationToken);
if (type == null)
continue;
AddAccessibilityModifiersHelpers.UpdateDeclaration(editor, type, declaration);
}
return document.WithSyntaxRoot(editor.GetChangedRoot());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.AddAccessibilityModifiers;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FileHeaders;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Designer.Interfaces;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
/// <summary>
/// The base class of both the Roslyn editor factories.
/// </summary>
internal abstract class AbstractEditorFactory : IVsEditorFactory, IVsEditorFactory4, IVsEditorFactoryNotify
{
private readonly IComponentModel _componentModel;
private Microsoft.VisualStudio.OLE.Interop.IServiceProvider? _oleServiceProvider;
private bool _encoding;
protected AbstractEditorFactory(IComponentModel componentModel)
=> _componentModel = componentModel;
protected abstract string ContentTypeName { get; }
protected abstract string LanguageName { get; }
public void SetEncoding(bool value)
=> _encoding = value;
int IVsEditorFactory.Close()
=> VSConstants.S_OK;
public int CreateEditorInstance(
uint grfCreateDoc,
string pszMkDocument,
string? pszPhysicalView,
IVsHierarchy vsHierarchy,
uint itemid,
IntPtr punkDocDataExisting,
out IntPtr ppunkDocView,
out IntPtr ppunkDocData,
out string pbstrEditorCaption,
out Guid pguidCmdUI,
out int pgrfCDW)
{
Contract.ThrowIfNull(_oleServiceProvider);
ppunkDocView = IntPtr.Zero;
ppunkDocData = IntPtr.Zero;
pbstrEditorCaption = string.Empty;
pguidCmdUI = Guid.Empty;
pgrfCDW = 0;
var physicalView = pszPhysicalView ?? "Code";
IVsTextBuffer? textBuffer = null;
// Is this document already open? If so, let's see if it's a IVsTextBuffer we should re-use. This allows us
// to properly handle multiple windows open for the same document.
if (punkDocDataExisting != IntPtr.Zero)
{
var docDataExisting = Marshal.GetObjectForIUnknown(punkDocDataExisting);
textBuffer = docDataExisting as IVsTextBuffer;
if (textBuffer == null)
{
// We are incompatible with the existing doc data
return VSConstants.VS_E_INCOMPATIBLEDOCDATA;
}
}
var editorAdaptersFactoryService = _componentModel.GetService<IVsEditorAdaptersFactoryService>();
// Do we need to create a text buffer?
if (textBuffer == null)
{
textBuffer = (IVsTextBuffer)GetDocumentData(grfCreateDoc, pszMkDocument, vsHierarchy, itemid);
Contract.ThrowIfNull(textBuffer, $"Failed to get document data for {pszMkDocument}");
}
// If the text buffer is marked as read-only, ensure that the padlock icon is displayed
// next the new window's title and that [Read Only] is appended to title.
var readOnlyStatus = READONLYSTATUS.ROSTATUS_NotReadOnly;
if (ErrorHandler.Succeeded(textBuffer.GetStateFlags(out var textBufferFlags)) &&
0 != (textBufferFlags & ((uint)BUFFERSTATEFLAGS.BSF_FILESYS_READONLY | (uint)BUFFERSTATEFLAGS.BSF_USER_READONLY)))
{
readOnlyStatus = READONLYSTATUS.ROSTATUS_ReadOnly;
}
switch (physicalView)
{
case "Form":
// We must create the WinForms designer here
var loaderName = GetWinFormsLoaderName(vsHierarchy);
var designerService = (IVSMDDesignerService)Microsoft.VisualStudio.Shell.PackageUtilities.QueryService<SVSMDDesignerService>(_oleServiceProvider);
var designerLoader = (IVSMDDesignerLoader)designerService.CreateDesignerLoader(loaderName);
if (designerLoader is null)
{
goto case "Code";
}
try
{
designerLoader.Initialize(_oleServiceProvider, vsHierarchy, (int)itemid, (IVsTextLines)textBuffer);
pbstrEditorCaption = designerLoader.GetEditorCaption((int)readOnlyStatus);
var designer = designerService.CreateDesigner(_oleServiceProvider, designerLoader);
ppunkDocView = Marshal.GetIUnknownForObject(designer.View);
pguidCmdUI = designer.CommandGuid;
}
catch
{
// Only dispose the designer loader on failure to create a designer.
// The IVSMDDesignerService.CreateDesigner() method in VS passes it into the DesignSurface that gets created
// and is used to perform the actual load (and reloads -- which happen during normal designer operation).
// http://index/?leftProject=Microsoft.VisualStudio.Design&leftSymbol=n8p1tszkfyz7&file=DesignerActivationService.cs&line=629
designerLoader.Dispose();
throw;
}
break;
case "Code":
var codeWindow = editorAdaptersFactoryService.CreateVsCodeWindowAdapter(_oleServiceProvider);
codeWindow.SetBuffer((IVsTextLines)textBuffer);
codeWindow.GetEditorCaption(readOnlyStatus, out pbstrEditorCaption);
ppunkDocView = Marshal.GetIUnknownForObject(codeWindow);
pguidCmdUI = VSConstants.GUID_TextEditorFactory;
break;
default:
return VSConstants.E_INVALIDARG;
}
ppunkDocData = Marshal.GetIUnknownForObject(textBuffer);
return VSConstants.S_OK;
}
public object GetDocumentData(uint grfCreate, string pszMkDocument, IVsHierarchy pHier, uint itemid)
{
Contract.ThrowIfNull(_oleServiceProvider);
var editorAdaptersFactoryService = _componentModel.GetService<IVsEditorAdaptersFactoryService>();
var contentTypeRegistryService = _componentModel.GetService<IContentTypeRegistryService>();
var contentType = contentTypeRegistryService.GetContentType(ContentTypeName);
var textBuffer = editorAdaptersFactoryService.CreateVsTextBufferAdapter(_oleServiceProvider, contentType);
if (_encoding)
{
if (textBuffer is IVsUserData userData)
{
// The editor shims require that the boxed value when setting the PromptOnLoad flag is a uint
var hresult = userData.SetData(
VSConstants.VsTextBufferUserDataGuid.VsBufferEncodingPromptOnLoad_guid,
(uint)__PROMPTONLOADFLAGS.codepagePrompt);
Marshal.ThrowExceptionForHR(hresult);
}
}
return textBuffer;
}
public object GetDocumentView(uint grfCreate, string pszPhysicalView, IVsHierarchy pHier, IntPtr punkDocData, uint itemid)
{
// There is no scenario need currently to implement this method.
throw new NotImplementedException();
}
public string GetEditorCaption(string pszMkDocument, string pszPhysicalView, IVsHierarchy pHier, IntPtr punkDocData, out Guid pguidCmdUI)
{
// It is not possible to get this information without initializing the designer.
// There is no other scenario need currently to implement this method.
throw new NotImplementedException();
}
public bool ShouldDeferUntilIntellisenseIsReady(uint grfCreate, string pszMkDocument, string pszPhysicalView)
{
return "Form".Equals(pszPhysicalView, StringComparison.OrdinalIgnoreCase);
}
private static string GetWinFormsLoaderName(IVsHierarchy vsHierarchy)
{
const string LoaderName = "Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader";
const string NewLoaderName = "Microsoft.VisualStudio.Design.Core.Serialization.CodeDom.VSCodeDomDesignerLoader";
// If this is a netcoreapp3.0 (or newer), we must create the newer WinForms designer.
// TODO: This check will eventually move into the WinForms designer itself.
if (!vsHierarchy.TryGetTargetFrameworkMoniker((uint)VSConstants.VSITEMID.Root, out var targetFrameworkMoniker) ||
string.IsNullOrWhiteSpace(targetFrameworkMoniker))
{
return LoaderName;
}
try
{
var frameworkName = new FrameworkName(targetFrameworkMoniker);
if (frameworkName.Identifier == ".NETCoreApp" && frameworkName.Version?.Major >= 3)
{
return NewLoaderName;
}
}
catch
{
// Fall back to the old loader name if there are any failures
// while parsing the TFM.
}
return LoaderName;
}
public int MapLogicalView(ref Guid rguidLogicalView, out string? pbstrPhysicalView)
{
pbstrPhysicalView = null;
if (rguidLogicalView == VSConstants.LOGVIEWID.Primary_guid ||
rguidLogicalView == VSConstants.LOGVIEWID.Debugging_guid ||
rguidLogicalView == VSConstants.LOGVIEWID.Code_guid ||
rguidLogicalView == VSConstants.LOGVIEWID.TextView_guid)
{
return VSConstants.S_OK;
}
else if (rguidLogicalView == VSConstants.LOGVIEWID.Designer_guid)
{
pbstrPhysicalView = "Form";
return VSConstants.S_OK;
}
else
{
return VSConstants.E_NOTIMPL;
}
}
int IVsEditorFactory.SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
{
_oleServiceProvider = psp;
return VSConstants.S_OK;
}
int IVsEditorFactoryNotify.NotifyDependentItemSaved(IVsHierarchy pHier, uint itemidParent, string pszMkDocumentParent, uint itemidDpendent, string pszMkDocumentDependent)
=> VSConstants.S_OK;
int IVsEditorFactoryNotify.NotifyItemAdded(uint grfEFN, IVsHierarchy pHier, uint itemid, string pszMkDocument)
{
// Is this being added from a template?
if (((__EFNFLAGS)grfEFN & __EFNFLAGS.EFN_ClonedFromTemplate) != 0)
{
var uiThreadOperationExecutor = _componentModel.GetService<IUIThreadOperationExecutor>();
// TODO(cyrusn): Can this be cancellable?
uiThreadOperationExecutor.Execute(
"Intellisense",
defaultDescription: "",
allowCancellation: false,
showProgress: false,
action: c => FormatDocumentCreatedFromTemplate(pHier, itemid, pszMkDocument, c.UserCancellationToken));
}
return VSConstants.S_OK;
}
int IVsEditorFactoryNotify.NotifyItemRenamed(IVsHierarchy pHier, uint itemid, string pszMkDocumentOld, string pszMkDocumentNew)
=> VSConstants.S_OK;
private void FormatDocumentCreatedFromTemplate(IVsHierarchy hierarchy, uint itemid, string filePath, CancellationToken cancellationToken)
{
Microsoft.VisualStudio.Shell.ThreadHelper.JoinableTaskFactory.Run(() => FormatDocumentCreatedFromTemplateAsync(hierarchy, itemid, filePath, cancellationToken));
}
private async Task FormatDocumentCreatedFromTemplateAsync(IVsHierarchy hierarchy, uint itemid, string filePath, CancellationToken cancellationToken)
{
// A file has been created on disk which the user added from the "Add Item" dialog. We need
// to include this in a workspace to figure out the right options it should be formatted with.
// This requires us to place it in the correct project.
var workspace = _componentModel.GetService<VisualStudioWorkspace>();
var solution = workspace.CurrentSolution;
ProjectId? projectIdToAddTo = null;
foreach (var projectId in solution.ProjectIds)
{
if (workspace.GetHierarchy(projectId) == hierarchy)
{
projectIdToAddTo = projectId;
break;
}
}
if (projectIdToAddTo == null)
{
// We don't have a project for this, so we'll just make up a fake project altogether
var temporaryProject = solution.AddProject(
name: nameof(FormatDocumentCreatedFromTemplate),
assemblyName: nameof(FormatDocumentCreatedFromTemplate),
language: LanguageName);
solution = temporaryProject.Solution;
projectIdToAddTo = temporaryProject.Id;
}
var documentId = DocumentId.CreateNewId(projectIdToAddTo);
var forkedSolution = solution.AddDocument(DocumentInfo.Create(documentId, filePath, loader: new FileTextLoader(filePath, defaultEncoding: null), filePath: filePath));
var addedDocument = forkedSolution.GetDocument(documentId)!;
// Call out to various new document formatters to tweak what they want
var formattingService = addedDocument.GetLanguageService<INewDocumentFormattingService>();
if (formattingService is not null)
{
addedDocument = await formattingService.FormatNewDocumentAsync(addedDocument, hintDocument: null, cancellationToken).ConfigureAwait(true);
}
var rootToFormat = await addedDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(true);
var documentOptions = await addedDocument.GetOptionsAsync(cancellationToken).ConfigureAwait(true);
// Format document
var unformattedText = await addedDocument.GetTextAsync(cancellationToken).ConfigureAwait(true);
var formattedRoot = Formatter.Format(rootToFormat, workspace, documentOptions, cancellationToken);
var formattedText = formattedRoot.GetText(unformattedText.Encoding, unformattedText.ChecksumAlgorithm);
// Ensure the line endings are normalized. The formatter doesn't touch everything if it doesn't need to.
var targetLineEnding = documentOptions.GetOption(FormattingOptions.NewLine)!;
var originalText = formattedText;
foreach (var originalLine in originalText.Lines)
{
var originalNewLine = originalText.ToString(CodeAnalysis.Text.TextSpan.FromBounds(originalLine.End, originalLine.EndIncludingLineBreak));
// Check if we have a line ending, so we don't go adding one to the end if we don't need to.
if (originalNewLine.Length > 0 && originalNewLine != targetLineEnding)
{
var currentLine = formattedText.Lines[originalLine.LineNumber];
var currentSpan = CodeAnalysis.Text.TextSpan.FromBounds(currentLine.End, currentLine.EndIncludingLineBreak);
formattedText = formattedText.WithChanges(new TextChange(currentSpan, targetLineEnding));
}
}
IOUtilities.PerformIO(() =>
{
using var textWriter = new StreamWriter(filePath, append: false, encoding: formattedText.Encoding);
// We pass null here for cancellation, since cancelling in the middle of the file write would leave the file corrupted
formattedText.Write(textWriter, cancellationToken: CancellationToken.None);
});
}
}
}
| 1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicEditorFactory.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.FileHeaders
Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Imports Microsoft.CodeAnalysis.VisualBasic.FileHeaders
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.LanguageServices.Implementation
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
<Guid(Guids.VisualBasicEditorFactoryIdString)>
Friend Class VisualBasicEditorFactory
Inherits AbstractEditorFactory
Public Sub New(componentModel As IComponentModel)
MyBase.New(componentModel)
End Sub
Protected Overrides ReadOnly Property ContentTypeName As String = ContentTypeNames.VisualBasicContentType
Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic
Protected Overrides ReadOnly Property SyntaxGenerator As SyntaxGenerator = VisualBasicSyntaxGenerator.Instance
Protected Overrides ReadOnly Property SyntaxGeneratorInternal As SyntaxGeneratorInternal = VisualBasicSyntaxGeneratorInternal.Instance
Protected Overrides ReadOnly Property FileHeaderHelper As AbstractFileHeaderHelper = VisualBasicFileHeaderHelper.Instance
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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.FileHeaders
Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Imports Microsoft.CodeAnalysis.VisualBasic.FileHeaders
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.LanguageServices.Implementation
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
<Guid(Guids.VisualBasicEditorFactoryIdString)>
Friend Class VisualBasicEditorFactory
Inherits AbstractEditorFactory
Public Sub New(componentModel As IComponentModel)
MyBase.New(componentModel)
End Sub
Protected Overrides ReadOnly Property ContentTypeName As String = ContentTypeNames.VisualBasicContentType
Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/Core/Portable/InlineHints/IInlineParameterNameHintsService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.InlineHints
{
/// <summary>
/// Gets inline hints for type locations. This is an internal service only for C# and VB. Use <see
/// cref="IInlineHintsService"/> for other languages.
/// </summary>
internal interface IInlineParameterNameHintsService : ILanguageService
{
Task<ImmutableArray<InlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.InlineHints
{
/// <summary>
/// Gets inline hints for type locations. This is an internal service only for C# and VB. Use <see
/// cref="IInlineHintsService"/> for other languages.
/// </summary>
internal interface IInlineParameterNameHintsService : ILanguageService
{
Task<ImmutableArray<InlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AbstractAddAccessibilityModifiersCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddAccessibilityModifiers
{
internal abstract class AbstractAddAccessibilityModifiersCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
protected abstract SyntaxNode MapToDeclarator(SyntaxNode declaration);
public sealed override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.AddAccessibilityModifiersDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
#if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer.
var codeAction = new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c));
#else
var priority = diagnostic.Severity == DiagnosticSeverity.Hidden
? CodeActionPriority.Low
: CodeActionPriority.Medium;
var codeAction = new MyCodeAction(priority, c => FixAsync(context.Document, context.Diagnostics.First(), c));
#endif
context.RegisterCodeFix(
codeAction,
context.Diagnostics);
return Task.CompletedTask;
}
protected sealed override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics)
{
var declaration = diagnostic.AdditionalLocations[0].FindNode(cancellationToken);
var declarator = MapToDeclarator(declaration);
var symbol = semanticModel.GetDeclaredSymbol(declarator, cancellationToken);
Contract.ThrowIfNull(symbol);
AddAccessibilityModifiersHelpers.UpdateDeclaration(editor, symbol, declaration);
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
#if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer.
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Add_accessibility_modifiers, createChangedDocument, AnalyzersResources.Add_accessibility_modifiers)
{
}
#else
public MyCodeAction(CodeActionPriority priority, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Add_accessibility_modifiers, createChangedDocument, AnalyzersResources.Add_accessibility_modifiers)
{
Priority = priority;
}
internal override CodeActionPriority Priority { get; }
#endif
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddAccessibilityModifiers
{
internal abstract class AbstractAddAccessibilityModifiersCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
protected abstract SyntaxNode MapToDeclarator(SyntaxNode declaration);
public sealed override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.AddAccessibilityModifiersDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
#if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer.
var codeAction = new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c));
#else
var priority = diagnostic.Severity == DiagnosticSeverity.Hidden
? CodeActionPriority.Low
: CodeActionPriority.Medium;
var codeAction = new MyCodeAction(priority, c => FixAsync(context.Document, context.Diagnostics.First(), c));
#endif
context.RegisterCodeFix(
codeAction,
context.Diagnostics);
return Task.CompletedTask;
}
protected sealed override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics)
{
var declaration = diagnostic.AdditionalLocations[0].FindNode(cancellationToken);
var declarator = MapToDeclarator(declaration);
var symbol = semanticModel.GetDeclaredSymbol(declarator, cancellationToken);
Contract.ThrowIfNull(symbol);
AddAccessibilityModifiersHelpers.UpdateDeclaration(editor, symbol, declaration);
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
#if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer.
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Add_accessibility_modifiers, createChangedDocument, AnalyzersResources.Add_accessibility_modifiers)
{
}
#else
public MyCodeAction(CodeActionPriority priority, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(AnalyzersResources.Add_accessibility_modifiers, createChangedDocument, AnalyzersResources.Add_accessibility_modifiers)
{
Priority = priority;
}
internal override CodeActionPriority Priority { get; }
#endif
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundLValueToRValueWrapper.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundLValueToRValueWrapper
#If DEBUG Then
Private Sub Validate()
Debug.Assert(UnderlyingLValue.IsLValue)
Debug.Assert(UnderlyingLValue.Type.IsSameTypeIgnoringAll(Type))
End Sub
#End If
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundLValueToRValueWrapper
#If DEBUG Then
Private Sub Validate()
Debug.Assert(UnderlyingLValue.IsLValue)
Debug.Assert(UnderlyingLValue.Type.IsSameTypeIgnoringAll(Type))
End Sub
#End If
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Analyzers/CSharp/CodeFixes/UseObjectInitializer/CSharpUseObjectInitializerCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.UseObjectInitializer;
namespace Microsoft.CodeAnalysis.CSharp.UseObjectInitializer
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseObjectInitializer), Shared]
internal class CSharpUseObjectInitializerCodeFixProvider :
AbstractUseObjectInitializerCodeFixProvider<
SyntaxKind,
ExpressionSyntax,
StatementSyntax,
ObjectCreationExpressionSyntax,
MemberAccessExpressionSyntax,
ExpressionStatementSyntax,
VariableDeclaratorSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseObjectInitializerCodeFixProvider()
{
}
protected override StatementSyntax GetNewStatement(
StatementSyntax statement, ObjectCreationExpressionSyntax objectCreation,
ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches)
{
return statement.ReplaceNode(
objectCreation,
GetNewObjectCreation(objectCreation, matches));
}
private static ObjectCreationExpressionSyntax GetNewObjectCreation(
ObjectCreationExpressionSyntax objectCreation,
ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches)
{
return UseInitializerHelpers.GetNewObjectCreation(
objectCreation, CreateExpressions(matches));
}
private static SeparatedSyntaxList<ExpressionSyntax> CreateExpressions(
ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches)
{
var nodesAndTokens = new List<SyntaxNodeOrToken>();
for (var i = 0; i < matches.Length; i++)
{
var match = matches[i];
var expressionStatement = match.Statement;
var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;
var newAssignment = assignment.WithLeft(
match.MemberAccessExpression.Name.WithLeadingTrivia(match.MemberAccessExpression.GetLeadingTrivia()));
if (i < matches.Length - 1)
{
nodesAndTokens.Add(newAssignment);
var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken)
.WithTriviaFrom(expressionStatement.SemicolonToken);
nodesAndTokens.Add(commaToken);
}
else
{
newAssignment = newAssignment.WithTrailingTrivia(
expressionStatement.GetTrailingTrivia());
nodesAndTokens.Add(newAssignment);
}
}
return SyntaxFactory.SeparatedList<ExpressionSyntax>(nodesAndTokens);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.UseObjectInitializer;
namespace Microsoft.CodeAnalysis.CSharp.UseObjectInitializer
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseObjectInitializer), Shared]
internal class CSharpUseObjectInitializerCodeFixProvider :
AbstractUseObjectInitializerCodeFixProvider<
SyntaxKind,
ExpressionSyntax,
StatementSyntax,
ObjectCreationExpressionSyntax,
MemberAccessExpressionSyntax,
ExpressionStatementSyntax,
VariableDeclaratorSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseObjectInitializerCodeFixProvider()
{
}
protected override StatementSyntax GetNewStatement(
StatementSyntax statement, ObjectCreationExpressionSyntax objectCreation,
ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches)
{
return statement.ReplaceNode(
objectCreation,
GetNewObjectCreation(objectCreation, matches));
}
private static ObjectCreationExpressionSyntax GetNewObjectCreation(
ObjectCreationExpressionSyntax objectCreation,
ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches)
{
return UseInitializerHelpers.GetNewObjectCreation(
objectCreation, CreateExpressions(matches));
}
private static SeparatedSyntaxList<ExpressionSyntax> CreateExpressions(
ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches)
{
var nodesAndTokens = new List<SyntaxNodeOrToken>();
for (var i = 0; i < matches.Length; i++)
{
var match = matches[i];
var expressionStatement = match.Statement;
var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;
var newAssignment = assignment.WithLeft(
match.MemberAccessExpression.Name.WithLeadingTrivia(match.MemberAccessExpression.GetLeadingTrivia()));
if (i < matches.Length - 1)
{
nodesAndTokens.Add(newAssignment);
var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken)
.WithTriviaFrom(expressionStatement.SemicolonToken);
nodesAndTokens.Add(commaToken);
}
else
{
newAssignment = newAssignment.WithTrailingTrivia(
expressionStatement.GetTrailingTrivia());
nodesAndTokens.Add(newAssignment);
}
}
return SyntaxFactory.SeparatedList<ExpressionSyntax>(nodesAndTokens);
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/IDkmClrFormatter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Collections.ObjectModel;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
namespace Microsoft.VisualStudio.Debugger.ComponentInterfaces
{
public interface IDkmClrFormatter
{
string GetTypeName(DkmInspectionContext inspectionContext, DkmClrType clrType, DkmClrCustomTypeInfo CustomTypeInfo, ReadOnlyCollection<string> formatSpecifiers);
string GetUnderlyingString(DkmClrValue clrValue, DkmInspectionContext inspectionContext);
string GetValueString(DkmClrValue clrValue, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers);
bool HasUnderlyingString(DkmClrValue clrValue, DkmInspectionContext inspectionContext);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Collections.ObjectModel;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
namespace Microsoft.VisualStudio.Debugger.ComponentInterfaces
{
public interface IDkmClrFormatter
{
string GetTypeName(DkmInspectionContext inspectionContext, DkmClrType clrType, DkmClrCustomTypeInfo CustomTypeInfo, ReadOnlyCollection<string> formatSpecifiers);
string GetUnderlyingString(DkmClrValue clrValue, DkmInspectionContext inspectionContext);
string GetValueString(DkmClrValue clrValue, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers);
bool HasUnderlyingString(DkmClrValue clrValue, DkmInspectionContext inspectionContext);
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./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 | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Tools/ExternalAccess/FSharp/Internal/Structure/FSharpBlockStructureService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Structure;
using Microsoft.CodeAnalysis.Host.Mef;
using System;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Structure
{
[Shared]
[ExportLanguageService(typeof(BlockStructureService), LanguageNames.FSharp)]
internal class FSharpBlockStructureService : BlockStructureService
{
private readonly IFSharpBlockStructureService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpBlockStructureService(IFSharpBlockStructureService service)
{
_service = service;
}
public override string Language => LanguageNames.FSharp;
public override async Task<BlockStructure> GetBlockStructureAsync(Document document, CancellationToken cancellationToken)
{
var blockStructure = await _service.GetBlockStructureAsync(document, cancellationToken).ConfigureAwait(false);
if (blockStructure != null)
{
return new BlockStructure(blockStructure.Spans.SelectAsArray(x => new BlockSpan(x.Type, x.IsCollapsible, x.TextSpan, x.HintSpan, x.BannerText, x.AutoCollapse, x.IsDefaultCollapsed)));
}
else
{
return null;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Structure;
using Microsoft.CodeAnalysis.Host.Mef;
using System;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Structure
{
[Shared]
[ExportLanguageService(typeof(BlockStructureService), LanguageNames.FSharp)]
internal class FSharpBlockStructureService : BlockStructureService
{
private readonly IFSharpBlockStructureService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpBlockStructureService(IFSharpBlockStructureService service)
{
_service = service;
}
public override string Language => LanguageNames.FSharp;
public override async Task<BlockStructure> GetBlockStructureAsync(Document document, CancellationToken cancellationToken)
{
var blockStructure = await _service.GetBlockStructureAsync(document, cancellationToken).ConfigureAwait(false);
if (blockStructure != null)
{
return new BlockStructure(blockStructure.Spans.SelectAsArray(x => new BlockSpan(x.Type, x.IsCollapsible, x.TextSpan, x.HintSpan, x.BannerText, x.AutoCollapse, x.IsDefaultCollapsed)));
}
else
{
return null;
}
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.RuntimeMembers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter : BoundTreeRewriterWithStackGuard
{
private readonly CSharpCompilation _compilation;
private readonly SyntheticBoundNodeFactory _factory;
private readonly SynthesizedSubmissionFields _previousSubmissionFields;
private readonly bool _allowOmissionOfConditionalCalls;
private LoweredDynamicOperationFactory _dynamicFactory;
private bool _sawLambdas;
private int _availableLocalFunctionOrdinal;
private bool _inExpressionLambda;
private bool _sawAwait;
private bool _sawAwaitInExceptionHandler;
private bool _needsSpilling;
private readonly BindingDiagnosticBag _diagnostics;
private Instrumenter _instrumenter;
private readonly BoundStatement _rootStatement;
private Dictionary<BoundValuePlaceholderBase, BoundExpression>? _placeholderReplacementMapDoNotUseDirectly;
private LocalRewriter(
CSharpCompilation compilation,
MethodSymbol containingMethod,
int containingMethodOrdinal,
BoundStatement rootStatement,
NamedTypeSymbol? containingType,
SyntheticBoundNodeFactory factory,
SynthesizedSubmissionFields previousSubmissionFields,
bool allowOmissionOfConditionalCalls,
BindingDiagnosticBag diagnostics,
Instrumenter instrumenter)
{
_compilation = compilation;
_factory = factory;
_factory.CurrentFunction = containingMethod;
Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2));
_dynamicFactory = new LoweredDynamicOperationFactory(factory, containingMethodOrdinal);
_previousSubmissionFields = previousSubmissionFields;
_allowOmissionOfConditionalCalls = allowOmissionOfConditionalCalls;
_diagnostics = diagnostics;
Debug.Assert(instrumenter != null);
#if DEBUG
// Ensure that only expected kinds of instrumenters are in use
_ = RemoveDynamicAnalysisInjectors(instrumenter);
#endif
_instrumenter = instrumenter;
_rootStatement = rootStatement;
}
/// <summary>
/// Lower a block of code by performing local rewritings.
/// </summary>
public static BoundStatement Rewrite(
CSharpCompilation compilation,
MethodSymbol method,
int methodOrdinal,
NamedTypeSymbol containingType,
BoundStatement statement,
TypeCompilationState compilationState,
SynthesizedSubmissionFields previousSubmissionFields,
bool allowOmissionOfConditionalCalls,
bool instrumentForDynamicAnalysis,
ref ImmutableArray<SourceSpan> dynamicAnalysisSpans,
DebugDocumentProvider debugDocumentProvider,
BindingDiagnosticBag diagnostics,
out bool sawLambdas,
out bool sawLocalFunctions,
out bool sawAwaitInExceptionHandler)
{
Debug.Assert(statement != null);
Debug.Assert(compilationState != null);
try
{
var factory = new SyntheticBoundNodeFactory(method, statement.Syntax, compilationState, diagnostics);
DynamicAnalysisInjector? dynamicInstrumenter = instrumentForDynamicAnalysis ? DynamicAnalysisInjector.TryCreate(method, statement, factory, diagnostics, debugDocumentProvider, Instrumenter.NoOp) : null;
// We don’t want IL to differ based upon whether we write the PDB to a file/stream or not.
// Presence of sequence points in the tree affects final IL, therefore, we always generate them.
var localRewriter = new LocalRewriter(compilation, method, methodOrdinal, statement, containingType, factory, previousSubmissionFields, allowOmissionOfConditionalCalls, diagnostics,
dynamicInstrumenter != null ? new DebugInfoInjector(dynamicInstrumenter) : DebugInfoInjector.Singleton);
statement.CheckLocalsDefined();
var loweredStatement = localRewriter.VisitStatement(statement);
Debug.Assert(loweredStatement is { });
loweredStatement.CheckLocalsDefined();
sawLambdas = localRewriter._sawLambdas;
sawLocalFunctions = localRewriter._availableLocalFunctionOrdinal != 0;
sawAwaitInExceptionHandler = localRewriter._sawAwaitInExceptionHandler;
if (localRewriter._needsSpilling && !loweredStatement.HasErrors)
{
// Move spill sequences to a top-level statement. This handles "lifting" await and the switch expression.
var spilledStatement = SpillSequenceSpiller.Rewrite(loweredStatement, method, compilationState, diagnostics);
spilledStatement.CheckLocalsDefined();
loweredStatement = spilledStatement;
}
if (dynamicInstrumenter != null)
{
dynamicAnalysisSpans = dynamicInstrumenter.DynamicAnalysisSpans;
}
#if DEBUG
LocalRewritingValidator.Validate(loweredStatement);
#endif
return loweredStatement;
}
catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
{
diagnostics.Add(ex.Diagnostic);
sawLambdas = sawLocalFunctions = sawAwaitInExceptionHandler = false;
return new BoundBadStatement(statement.Syntax, ImmutableArray.Create<BoundNode>(statement), hasErrors: true);
}
}
private bool Instrument
{
get
{
return !_inExpressionLambda;
}
}
private PEModuleBuilder? EmitModule
{
get { return _factory.CompilationState.ModuleBuilderOpt; }
}
/// <summary>
/// Return the translated node, or null if no code is necessary in the translation.
/// </summary>
public override BoundNode? Visit(BoundNode? node)
{
if (node == null)
{
return node;
}
Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered");
BoundExpression? expr = node as BoundExpression;
if (expr != null)
{
return VisitExpressionImpl(expr);
}
return node.Accept(this);
}
[return: NotNullIfNotNull("node")]
private BoundExpression? VisitExpression(BoundExpression? node)
{
if (node == null)
{
return node;
}
Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered");
// https://github.com/dotnet/roslyn/issues/47682
return VisitExpressionImpl(node)!;
}
private BoundStatement? VisitStatement(BoundStatement? node)
{
if (node == null)
{
return node;
}
Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered");
return (BoundStatement?)node.Accept(this);
}
private BoundExpression? VisitExpressionImpl(BoundExpression node)
{
ConstantValue? constantValue = node.ConstantValue;
if (constantValue != null)
{
TypeSymbol? type = node.Type;
if (type?.IsNullableType() != true)
{
return MakeLiteral(node.Syntax, constantValue, type);
}
}
var visited = VisitExpressionWithStackGuard(node);
// If you *really* need to change the type, consider using an indirect method
// like compound assignment does (extra flag only passed when it is an expression
// statement means that this constraint is not violated).
// Dynamic type will be erased in emit phase. It is considered equivalent to Object in lowered bound trees.
// Unused deconstructions are lowered to produce a return value that isn't a tuple type.
Debug.Assert(visited == null || visited.HasErrors || ReferenceEquals(visited.Type, node.Type) ||
visited.Type is { } && visited.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) ||
IsUnusedDeconstruction(node));
if (visited != null &&
visited != node &&
node.Kind != BoundKind.ImplicitReceiver &&
node.Kind != BoundKind.ObjectOrCollectionValuePlaceholder)
{
if (!CanBePassedByReference(node) && CanBePassedByReference(visited))
{
visited = RefAccessMustMakeCopy(visited);
}
}
return visited;
}
private static BoundExpression RefAccessMustMakeCopy(BoundExpression visited)
{
visited = new BoundPassByCopy(
visited.Syntax,
visited,
type: visited.Type);
return visited;
}
private static bool IsUnusedDeconstruction(BoundExpression node)
{
return node.Kind == BoundKind.DeconstructionAssignmentOperator && !((BoundDeconstructionAssignmentOperator)node).IsUsed;
}
public override BoundNode VisitLambda(BoundLambda node)
{
_sawLambdas = true;
var lambda = node.Symbol;
CheckRefReadOnlySymbols(lambda);
var oldContainingSymbol = _factory.CurrentFunction;
var oldInstrumenter = _instrumenter;
try
{
_factory.CurrentFunction = lambda;
if (lambda.IsDirectlyExcludedFromCodeCoverage)
{
_instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter);
}
return base.VisitLambda(node)!;
}
finally
{
_factory.CurrentFunction = oldContainingSymbol;
_instrumenter = oldInstrumenter;
}
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
int localFunctionOrdinal = _availableLocalFunctionOrdinal++;
var localFunction = node.Symbol;
CheckRefReadOnlySymbols(localFunction);
if (_factory.CompilationState.ModuleBuilderOpt is { } moduleBuilder)
{
var typeParameters = localFunction.TypeParameters;
if (typeParameters.Any(typeParameter => typeParameter.HasUnmanagedTypeConstraint))
{
moduleBuilder.EnsureIsUnmanagedAttributeExists();
}
if (hasReturnTypeOrParameter(localFunction, t => t.ContainsNativeInteger()) ||
typeParameters.Any(t => t.ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger())))
{
moduleBuilder.EnsureNativeIntegerAttributeExists();
}
if (_factory.CompilationState.Compilation.ShouldEmitNullableAttributes(localFunction))
{
bool constraintsNeedNullableAttribute = typeParameters.Any(
typeParameter => ((SourceTypeParameterSymbolBase)typeParameter).ConstraintsNeedNullableAttribute());
if (constraintsNeedNullableAttribute || hasReturnTypeOrParameter(localFunction, t => t.NeedsNullableAttribute()))
{
moduleBuilder.EnsureNullableAttributeExists();
}
}
static bool hasReturnTypeOrParameter(LocalFunctionSymbol localFunction, Func<TypeWithAnnotations, bool> predicate) =>
predicate(localFunction.ReturnTypeWithAnnotations) || localFunction.ParameterTypesWithAnnotations.Any(predicate);
}
var oldContainingSymbol = _factory.CurrentFunction;
var oldInstrumenter = _instrumenter;
var oldDynamicFactory = _dynamicFactory;
try
{
_factory.CurrentFunction = localFunction;
if (localFunction.IsDirectlyExcludedFromCodeCoverage)
{
_instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter);
}
if (localFunction.IsGenericMethod)
{
// Each generic local function gets its own dynamic factory because it
// needs its own container to cache dynamic call-sites. That type (the container) "inherits"
// local function's type parameters as well as type parameters of all containing methods.
_dynamicFactory = new LoweredDynamicOperationFactory(_factory, _dynamicFactory.MethodOrdinal, localFunctionOrdinal);
}
return base.VisitLocalFunctionStatement(node)!;
}
finally
{
_factory.CurrentFunction = oldContainingSymbol;
_instrumenter = oldInstrumenter;
_dynamicFactory = oldDynamicFactory;
}
}
private static Instrumenter RemoveDynamicAnalysisInjectors(Instrumenter instrumenter)
{
switch (instrumenter)
{
case DynamicAnalysisInjector { Previous: var previous }:
return RemoveDynamicAnalysisInjectors(previous);
case DebugInfoInjector { Previous: var previous } injector:
var newPrevious = RemoveDynamicAnalysisInjectors(previous);
if ((object)newPrevious == previous)
{
return injector;
}
else if ((object)newPrevious == Instrumenter.NoOp)
{
return DebugInfoInjector.Singleton;
}
else
{
return new DebugInfoInjector(previous);
}
case CompoundInstrumenter compound:
// If we hit this it means a new kind of compound instrumenter is in use.
// Either add a new case or add an abstraction that lets us
// filter out the unwanted injectors in a more generalized way.
throw ExceptionUtilities.UnexpectedValue(compound);
default:
Debug.Assert((object)instrumenter == Instrumenter.NoOp);
return instrumenter;
}
}
public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node)
{
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node)
{
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node)
{
return PlaceholderReplacement(node);
}
public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node)
{
if (_inExpressionLambda)
{
// Expression trees do not include the 'this' argument for members.
return node;
}
return PlaceholderReplacement(node);
}
public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node)
=> PlaceholderReplacement(node);
public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node)
=> PlaceholderReplacement(node);
/// <summary>
/// Returns substitution currently used by the rewriter for a placeholder node.
/// Each occurrence of the placeholder node is replaced with the node returned.
/// Throws if there is no substitution.
/// </summary>
private BoundExpression PlaceholderReplacement(BoundValuePlaceholderBase placeholder)
{
Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { });
var value = _placeholderReplacementMapDoNotUseDirectly[placeholder];
AssertPlaceholderReplacement(placeholder, value);
return value;
}
[Conditional("DEBUG")]
private static void AssertPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value)
{
Debug.Assert(value.Type is { } && value.Type.Equals(placeholder.Type, TypeCompareKind.AllIgnoreOptions));
}
/// <summary>
/// Sets substitution used by the rewriter for a placeholder node.
/// Each occurrence of the placeholder node is replaced with the node returned.
/// Throws if there is already a substitution.
/// </summary>
private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value)
{
AssertPlaceholderReplacement(placeholder, value);
if (_placeholderReplacementMapDoNotUseDirectly is null)
{
_placeholderReplacementMapDoNotUseDirectly = new Dictionary<BoundValuePlaceholderBase, BoundExpression>();
}
_placeholderReplacementMapDoNotUseDirectly.Add(placeholder, value);
}
/// <summary>
/// Removes substitution currently used by the rewriter for a placeholder node.
/// Asserts if there isn't already a substitution.
/// </summary>
private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder)
{
Debug.Assert(placeholder is { });
Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { });
bool removed = _placeholderReplacementMapDoNotUseDirectly.Remove(placeholder);
Debug.Assert(removed);
}
public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node)
{
// OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node)
{
// DeconstructionVariablePendingInference nodes are only used within initial binding, but don't survive past that stage
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitBadExpression(BoundBadExpression node)
{
// Cannot recurse into BadExpression children since the BadExpression
// may represent being unable to use the child as an lvalue or rvalue.
return node;
}
private static BoundExpression BadExpression(BoundExpression node)
{
Debug.Assert(node.Type is { });
return BadExpression(node.Syntax, node.Type, ImmutableArray.Create(node));
}
private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child)
{
return BadExpression(syntax, resultType, ImmutableArray.Create(child));
}
private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child1, BoundExpression child2)
{
return BadExpression(syntax, resultType, ImmutableArray.Create(child1, child2));
}
private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, ImmutableArray<BoundExpression> children)
{
return new BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray<Symbol?>.Empty, children, resultType);
}
private bool TryGetWellKnownTypeMember<TSymbol>(SyntaxNode? syntax, WellKnownMember member, out TSymbol symbol, bool isOptional = false, Location? location = null) where TSymbol : Symbol
{
Debug.Assert((syntax != null) ^ (location != null));
symbol = (TSymbol)Binder.GetWellKnownTypeMember(_compilation, member, _diagnostics, syntax: syntax, isOptional: isOptional, location: location);
return symbol is { };
}
/// <summary>
/// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing.
/// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, out MethodSymbol)"/> instead!
/// If used, a unit-test with a missing member is absolutely a must have.
/// </summary>
private MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember)
{
return UnsafeGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics);
}
/// <summary>
/// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing.
/// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, CSharpCompilation, BindingDiagnosticBag, out MethodSymbol)"/> instead!
/// If used, a unit-test with a missing member is absolutely a must have.
/// </summary>
private static MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics)
{
MethodSymbol method;
if (TryGetSpecialTypeMethod(syntax, specialMember, compilation, diagnostics, out method))
{
return method;
}
else
{
MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember);
SpecialType type = (SpecialType)descriptor.DeclaringTypeId;
TypeSymbol container = compilation.Assembly.GetSpecialType(type);
TypeSymbol returnType = new ExtendedErrorTypeSymbol(compilation: compilation, name: descriptor.Name, errorInfo: null, arity: descriptor.Arity);
return new ErrorMethodSymbol(container, returnType, "Missing");
}
}
private bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, out MethodSymbol method)
{
return TryGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics, out method);
}
private static bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics, out MethodSymbol method)
{
return Binder.TryGetSpecialTypeMember(compilation, specialMember, syntax, diagnostics, out method);
}
public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node)
{
Debug.Assert(node.GetTypeFromHandle is null);
var sourceType = (BoundTypeExpression?)this.Visit(node.SourceType);
Debug.Assert(sourceType is { });
var type = this.VisitType(node.Type);
// Emit needs this helper
MethodSymbol getTypeFromHandle;
if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle))
{
return new BoundTypeOfOperator(node.Syntax, sourceType, null, type, hasErrors: true);
}
return node.Update(sourceType, getTypeFromHandle, type);
}
public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node)
{
Debug.Assert(node.GetTypeFromHandle is null);
var operand = this.VisitExpression(node.Operand);
var type = this.VisitType(node.Type);
// Emit needs this helper
MethodSymbol getTypeFromHandle;
if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle))
{
return new BoundRefTypeOperator(node.Syntax, operand, null, type, hasErrors: true);
}
return node.Update(operand, getTypeFromHandle, type);
}
public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node)
{
ImmutableArray<BoundStatement> originalStatements = node.Statements;
var statements = ArrayBuilder<BoundStatement?>.GetInstance(node.Statements.Length);
foreach (var initializer in originalStatements)
{
if (IsFieldOrPropertyInitializer(initializer))
{
if (initializer.Kind == BoundKind.Block)
{
var block = (BoundBlock)initializer;
var statement = RewriteExpressionStatement((BoundExpressionStatement)block.Statements.Single(), suppressInstrumentation: true);
Debug.Assert(statement is { });
statements.Add(block.Update(block.Locals, block.LocalFunctions, ImmutableArray.Create(statement)));
}
else
{
statements.Add(RewriteExpressionStatement((BoundExpressionStatement)initializer, suppressInstrumentation: true));
}
}
else
{
statements.Add(VisitStatement(initializer));
}
}
int optimizedInitializers = 0;
bool optimize = _compilation.Options.OptimizationLevel == OptimizationLevel.Release;
for (int i = 0; i < statements.Count; i++)
{
var stmt = statements[i];
if (stmt == null || (optimize && IsFieldOrPropertyInitializer(originalStatements[i]) && ShouldOptimizeOutInitializer(stmt)))
{
optimizedInitializers++;
if (_factory.CurrentFunction?.IsStatic == false)
{
// NOTE: Dev11 removes static initializers if ONLY all of them are optimized out
statements[i] = null;
}
}
}
ImmutableArray<BoundStatement> rewrittenStatements;
if (optimizedInitializers == statements.Count)
{
// all are optimized away
rewrittenStatements = ImmutableArray<BoundStatement>.Empty;
statements.Free();
}
else
{
// instrument remaining statements
int remaining = 0;
for (int i = 0; i < statements.Count; i++)
{
BoundStatement? rewritten = statements[i];
if (rewritten != null)
{
if (IsFieldOrPropertyInitializer(originalStatements[i]))
{
BoundStatement original = originalStatements[i];
if (Instrument && !original.WasCompilerGenerated)
{
rewritten = _instrumenter.InstrumentFieldOrPropertyInitializer(original, rewritten);
}
}
statements[remaining] = rewritten;
remaining++;
}
}
statements.Count = remaining; // trim any trailing nulls
rewrittenStatements = statements.ToImmutableAndFree()!;
}
return new BoundStatementList(node.Syntax, rewrittenStatements, node.HasErrors);
}
public override BoundNode VisitArrayAccess(BoundArrayAccess node)
{
// An array access expression can be indexed using any of the following types:
// * an integer primitive
// * a System.Index
// * a System.Range
// The last two are only supported on SZArrays. For those cases we need to
// lower into the appropriate helper methods.
if (node.Indices.Length != 1)
{
return base.VisitArrayAccess(node)!;
}
var indexType = VisitType(node.Indices[0].Type);
var F = _factory;
BoundNode resultExpr;
if (TypeSymbol.Equals(
indexType,
_compilation.GetWellKnownType(WellKnownType.System_Index),
TypeCompareKind.ConsiderEverything))
{
// array[Index] is treated like a pattern-based System.Index indexing
// expression, except that array indexers don't actually exist (they
// don't have symbols)
var arrayLocal = F.StoreToTemp(
VisitExpression(node.Expression),
out BoundAssignmentOperator arrayAssign);
var indexOffsetExpr = MakePatternIndexOffsetExpression(
node.Indices[0],
F.ArrayLength(arrayLocal),
out _);
resultExpr = F.Sequence(
ImmutableArray.Create(arrayLocal.LocalSymbol),
ImmutableArray.Create<BoundExpression>(arrayAssign),
F.ArrayAccess(
arrayLocal,
ImmutableArray.Create(indexOffsetExpr)));
}
else if (TypeSymbol.Equals(
indexType,
_compilation.GetWellKnownType(WellKnownType.System_Range),
TypeCompareKind.ConsiderEverything))
{
// array[Range] is compiled to:
// System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray(array, Range)
Debug.Assert(node.Expression.Type is { TypeKind: TypeKind.Array });
var elementType = ((ArrayTypeSymbol)node.Expression.Type).ElementTypeWithAnnotations;
resultExpr = F.Call(
receiver: null,
F.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T)
.Construct(ImmutableArray.Create(elementType)),
ImmutableArray.Create(
VisitExpression(node.Expression),
VisitExpression(node.Indices[0])));
}
else
{
resultExpr = base.VisitArrayAccess(node)!;
}
return resultExpr;
}
internal static bool IsFieldOrPropertyInitializer(BoundStatement initializer)
{
var syntax = initializer.Syntax;
if (syntax.IsKind(SyntaxKind.Parameter))
{
// This is an initialization of a generated property based on record parameter.
return true;
}
if (syntax is ExpressionSyntax { Parent: { } parent } && parent.Kind() == SyntaxKind.EqualsValueClause) // Should be the initial value.
{
Debug.Assert(parent.Parent is { });
switch (parent.Parent.Kind())
{
case SyntaxKind.VariableDeclarator:
case SyntaxKind.PropertyDeclaration:
switch (initializer.Kind)
{
case BoundKind.Block:
var block = (BoundBlock)initializer;
if (block.Statements.Length == 1)
{
initializer = (BoundStatement)block.Statements.First();
if (initializer.Kind == BoundKind.ExpressionStatement)
{
goto case BoundKind.ExpressionStatement;
}
}
break;
case BoundKind.ExpressionStatement:
return ((BoundExpressionStatement)initializer).Expression.Kind == BoundKind.AssignmentOperator;
}
break;
}
}
return false;
}
/// <summary>
/// Returns true if the initializer is a field initializer which should be optimized out
/// </summary>
private static bool ShouldOptimizeOutInitializer(BoundStatement initializer)
{
BoundStatement statement = initializer;
if (statement.Kind != BoundKind.ExpressionStatement)
{
return false;
}
BoundAssignmentOperator? assignment = ((BoundExpressionStatement)statement).Expression as BoundAssignmentOperator;
if (assignment == null)
{
return false;
}
Debug.Assert(assignment.Left.Kind == BoundKind.FieldAccess);
var lhsField = ((BoundFieldAccess)assignment.Left).FieldSymbol;
if (!lhsField.IsStatic && lhsField.ContainingType.IsStructType())
{
return false;
}
BoundExpression rhs = assignment.Right;
return rhs.IsDefaultValue();
}
// There are three situations in which the language permits passing rvalues by reference.
// (technically there are 5, but we can ignore COM and dynamic here, since that results in byval semantics regardless of the parameter ref kind)
//
// #1: Receiver of a struct/generic method call.
//
// The language only requires that receivers of method calls must be readable (RValues are ok).
//
// However the underlying implementation passes receivers of struct methods by reference.
// In such situations it may be possible for the call to cause or observe writes to the receiver variable.
// As a result it is not valid to replace receiver variable with a reference to it or the other way around.
//
// Example1:
// static int x = 123;
// async static Task<string> Test1()
// {
// // cannot capture "x" by value, since write in M1 is observable
// return x.ToString(await M1());
// }
//
// async static Task<string> M1()
// {
// x = 42;
// await Task.Yield();
// return "";
// }
//
// Example2:
// static int x = 123;
// static string Test1()
// {
// // cannot replace value of "x" with a reference to "x"
// // since that would make the method see the mutations in M1();
// return (x + 0).ToString(M1());
// }
//
// static string M1()
// {
// x = 42;
// return "";
// }
//
// #2: Ordinary byval argument passed to an "in" parameter.
//
// The language only requires that ordinary byval arguments must be readable (RValues are ok).
// However if the target parameter is an "in" parameter, the underlying implementation passes by reference.
//
// Example:
// static int x = 123;
// static void Main(string[] args)
// {
// // cannot replace value of "x" with a direct reference to x
// // since Test will see unexpected changes due to aliasing.
// Test(x + 0);
// }
//
// static void Test(in int y)
// {
// Console.WriteLine(y);
// x = 42;
// Console.WriteLine(y);
// }
//
// #3: Ordinary byval interpolated string expression passed to a "ref" interpolated string handler value type.
//
// Interpolated string expressions passed to a builder type are lowered into a handler form. When the handler type
// is a value type (struct, or type parameter constrained to struct (though the latter will fail to bind today because
// there's no constructor)), the final handler instance type is passed by reference if the parameter is by reference.
//
// Example:
// M($""); // Language lowers this to a sequence of creating CustomHandler, appending all values, and evaluating to the builder
// static void M(ref CustomHandler c) { }
//
// NB: The readonliness is not considered here.
// We only care about possible introduction of aliasing. I.E. RValue->LValue change.
// Even if we start with a readonly variable, it cannot be lowered into a writeable one,
// with one exception - spilling of the value into a local, which is ok.
//
internal static bool CanBePassedByReference(BoundExpression expr)
{
if (expr.ConstantValue != null)
{
return false;
}
switch (expr.Kind)
{
case BoundKind.Parameter:
case BoundKind.Local:
case BoundKind.ArrayAccess:
case BoundKind.ThisReference:
case BoundKind.PointerIndirectionOperator:
case BoundKind.PointerElementAccess:
case BoundKind.RefValueOperator:
case BoundKind.PseudoVariable:
case BoundKind.DiscardExpression:
return true;
case BoundKind.DeconstructValuePlaceholder:
// we will consider that placeholder always represents a temp local
// the assumption should be confirmed or changed when https://github.com/dotnet/roslyn/issues/24160 is fixed
return true;
case BoundKind.InterpolatedStringArgumentPlaceholder:
// An argument placeholder is always a reference to some type of temp local,
// either representing a user-typed expression that went through this path
// itself when it was originally visited, or the trailing out parameter that
// is passed by out.
return true;
case BoundKind.InterpolatedStringHandlerPlaceholder:
// A handler placeholder is the receiver of the interpolated string AppendLiteral
// or AppendFormatted calls, and should never be defensively copied.
return true;
case BoundKind.EventAccess:
var eventAccess = (BoundEventAccess)expr;
if (eventAccess.IsUsableAsField)
{
if (eventAccess.EventSymbol.IsStatic)
return true;
Debug.Assert(eventAccess.ReceiverOpt is { });
return CanBePassedByReference(eventAccess.ReceiverOpt);
}
return false;
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)expr;
if (!fieldAccess.FieldSymbol.IsStatic)
{
Debug.Assert(fieldAccess.ReceiverOpt is { });
return CanBePassedByReference(fieldAccess.ReceiverOpt);
}
return true;
case BoundKind.Sequence:
return CanBePassedByReference(((BoundSequence)expr).Value);
case BoundKind.AssignmentOperator:
return ((BoundAssignmentOperator)expr).IsRef;
case BoundKind.ConditionalOperator:
return ((BoundConditionalOperator)expr).IsRef;
case BoundKind.Call:
return ((BoundCall)expr).Method.RefKind != RefKind.None;
case BoundKind.PropertyAccess:
return ((BoundPropertyAccess)expr).PropertySymbol.RefKind != RefKind.None;
case BoundKind.IndexerAccess:
return ((BoundIndexerAccess)expr).Indexer.RefKind != RefKind.None;
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
var refKind = patternIndexer.PatternSymbol switch
{
PropertySymbol p => p.RefKind,
MethodSymbol m => m.RefKind,
_ => throw ExceptionUtilities.UnexpectedValue(patternIndexer.PatternSymbol)
};
return refKind != RefKind.None;
case BoundKind.Conversion:
var conversion = ((BoundConversion)expr);
return expr is BoundConversion { Conversion: { IsInterpolatedStringHandler: true }, Type: { IsValueType: true } };
}
return false;
}
private void CheckRefReadOnlySymbols(MethodSymbol symbol)
{
if (symbol.ReturnsByRefReadonly ||
symbol.Parameters.Any(p => p.RefKind == RefKind.In))
{
_factory.CompilationState.ModuleBuilderOpt?.EnsureIsReadOnlyAttributeExists();
}
}
private CompoundUseSiteInfo<AssemblySymbol> GetNewCompoundUseSiteInfo()
{
return new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly);
}
#if DEBUG
/// <summary>
/// Note: do not use a static/singleton instance of this type, as it holds state.
/// </summary>
private sealed class LocalRewritingValidator : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
/// <summary>
/// Asserts that no unexpected nodes survived local rewriting.
/// </summary>
public static void Validate(BoundNode node)
{
try
{
new LocalRewritingValidator().Visit(node);
}
catch (InsufficientExecutionStackException)
{
// Intentionally ignored to let the overflow get caught in a more crucial visitor
}
}
public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node)
{
Fail(node);
return null;
}
public override BoundNode? VisitUsingStatement(BoundUsingStatement node)
{
Fail(node);
return null;
}
public override BoundNode? VisitIfStatement(BoundIfStatement node)
{
Fail(node);
return null;
}
public override BoundNode? VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node)
{
Fail(node);
return null;
}
public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node)
{
Fail(node);
return null;
}
public override BoundNode? VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node)
{
Fail(node);
return null;
}
public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node)
{
Fail(node);
return null;
}
public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node)
{
Fail(node);
return null;
}
private void Fail(BoundNode node)
{
Debug.Assert(false, $"Bound nodes of kind {node.Kind} should not survive past local rewriting");
}
}
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.RuntimeMembers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter : BoundTreeRewriterWithStackGuard
{
private readonly CSharpCompilation _compilation;
private readonly SyntheticBoundNodeFactory _factory;
private readonly SynthesizedSubmissionFields _previousSubmissionFields;
private readonly bool _allowOmissionOfConditionalCalls;
private LoweredDynamicOperationFactory _dynamicFactory;
private bool _sawLambdas;
private int _availableLocalFunctionOrdinal;
private bool _inExpressionLambda;
private bool _sawAwait;
private bool _sawAwaitInExceptionHandler;
private bool _needsSpilling;
private readonly BindingDiagnosticBag _diagnostics;
private Instrumenter _instrumenter;
private readonly BoundStatement _rootStatement;
private Dictionary<BoundValuePlaceholderBase, BoundExpression>? _placeholderReplacementMapDoNotUseDirectly;
private LocalRewriter(
CSharpCompilation compilation,
MethodSymbol containingMethod,
int containingMethodOrdinal,
BoundStatement rootStatement,
NamedTypeSymbol? containingType,
SyntheticBoundNodeFactory factory,
SynthesizedSubmissionFields previousSubmissionFields,
bool allowOmissionOfConditionalCalls,
BindingDiagnosticBag diagnostics,
Instrumenter instrumenter)
{
_compilation = compilation;
_factory = factory;
_factory.CurrentFunction = containingMethod;
Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2));
_dynamicFactory = new LoweredDynamicOperationFactory(factory, containingMethodOrdinal);
_previousSubmissionFields = previousSubmissionFields;
_allowOmissionOfConditionalCalls = allowOmissionOfConditionalCalls;
_diagnostics = diagnostics;
Debug.Assert(instrumenter != null);
#if DEBUG
// Ensure that only expected kinds of instrumenters are in use
_ = RemoveDynamicAnalysisInjectors(instrumenter);
#endif
_instrumenter = instrumenter;
_rootStatement = rootStatement;
}
/// <summary>
/// Lower a block of code by performing local rewritings.
/// </summary>
public static BoundStatement Rewrite(
CSharpCompilation compilation,
MethodSymbol method,
int methodOrdinal,
NamedTypeSymbol containingType,
BoundStatement statement,
TypeCompilationState compilationState,
SynthesizedSubmissionFields previousSubmissionFields,
bool allowOmissionOfConditionalCalls,
bool instrumentForDynamicAnalysis,
ref ImmutableArray<SourceSpan> dynamicAnalysisSpans,
DebugDocumentProvider debugDocumentProvider,
BindingDiagnosticBag diagnostics,
out bool sawLambdas,
out bool sawLocalFunctions,
out bool sawAwaitInExceptionHandler)
{
Debug.Assert(statement != null);
Debug.Assert(compilationState != null);
try
{
var factory = new SyntheticBoundNodeFactory(method, statement.Syntax, compilationState, diagnostics);
DynamicAnalysisInjector? dynamicInstrumenter = instrumentForDynamicAnalysis ? DynamicAnalysisInjector.TryCreate(method, statement, factory, diagnostics, debugDocumentProvider, Instrumenter.NoOp) : null;
// We don’t want IL to differ based upon whether we write the PDB to a file/stream or not.
// Presence of sequence points in the tree affects final IL, therefore, we always generate them.
var localRewriter = new LocalRewriter(compilation, method, methodOrdinal, statement, containingType, factory, previousSubmissionFields, allowOmissionOfConditionalCalls, diagnostics,
dynamicInstrumenter != null ? new DebugInfoInjector(dynamicInstrumenter) : DebugInfoInjector.Singleton);
statement.CheckLocalsDefined();
var loweredStatement = localRewriter.VisitStatement(statement);
Debug.Assert(loweredStatement is { });
loweredStatement.CheckLocalsDefined();
sawLambdas = localRewriter._sawLambdas;
sawLocalFunctions = localRewriter._availableLocalFunctionOrdinal != 0;
sawAwaitInExceptionHandler = localRewriter._sawAwaitInExceptionHandler;
if (localRewriter._needsSpilling && !loweredStatement.HasErrors)
{
// Move spill sequences to a top-level statement. This handles "lifting" await and the switch expression.
var spilledStatement = SpillSequenceSpiller.Rewrite(loweredStatement, method, compilationState, diagnostics);
spilledStatement.CheckLocalsDefined();
loweredStatement = spilledStatement;
}
if (dynamicInstrumenter != null)
{
dynamicAnalysisSpans = dynamicInstrumenter.DynamicAnalysisSpans;
}
#if DEBUG
LocalRewritingValidator.Validate(loweredStatement);
#endif
return loweredStatement;
}
catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
{
diagnostics.Add(ex.Diagnostic);
sawLambdas = sawLocalFunctions = sawAwaitInExceptionHandler = false;
return new BoundBadStatement(statement.Syntax, ImmutableArray.Create<BoundNode>(statement), hasErrors: true);
}
}
private bool Instrument
{
get
{
return !_inExpressionLambda;
}
}
private PEModuleBuilder? EmitModule
{
get { return _factory.CompilationState.ModuleBuilderOpt; }
}
/// <summary>
/// Return the translated node, or null if no code is necessary in the translation.
/// </summary>
public override BoundNode? Visit(BoundNode? node)
{
if (node == null)
{
return node;
}
Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered");
BoundExpression? expr = node as BoundExpression;
if (expr != null)
{
return VisitExpressionImpl(expr);
}
return node.Accept(this);
}
[return: NotNullIfNotNull("node")]
private BoundExpression? VisitExpression(BoundExpression? node)
{
if (node == null)
{
return node;
}
Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered");
// https://github.com/dotnet/roslyn/issues/47682
return VisitExpressionImpl(node)!;
}
private BoundStatement? VisitStatement(BoundStatement? node)
{
if (node == null)
{
return node;
}
Debug.Assert(!node.HasErrors, "nodes with errors should not be lowered");
return (BoundStatement?)node.Accept(this);
}
private BoundExpression? VisitExpressionImpl(BoundExpression node)
{
ConstantValue? constantValue = node.ConstantValue;
if (constantValue != null)
{
TypeSymbol? type = node.Type;
if (type?.IsNullableType() != true)
{
return MakeLiteral(node.Syntax, constantValue, type);
}
}
var visited = VisitExpressionWithStackGuard(node);
// If you *really* need to change the type, consider using an indirect method
// like compound assignment does (extra flag only passed when it is an expression
// statement means that this constraint is not violated).
// Dynamic type will be erased in emit phase. It is considered equivalent to Object in lowered bound trees.
// Unused deconstructions are lowered to produce a return value that isn't a tuple type.
Debug.Assert(visited == null || visited.HasErrors || ReferenceEquals(visited.Type, node.Type) ||
visited.Type is { } && visited.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) ||
IsUnusedDeconstruction(node));
if (visited != null &&
visited != node &&
node.Kind != BoundKind.ImplicitReceiver &&
node.Kind != BoundKind.ObjectOrCollectionValuePlaceholder)
{
if (!CanBePassedByReference(node) && CanBePassedByReference(visited))
{
visited = RefAccessMustMakeCopy(visited);
}
}
return visited;
}
private static BoundExpression RefAccessMustMakeCopy(BoundExpression visited)
{
visited = new BoundPassByCopy(
visited.Syntax,
visited,
type: visited.Type);
return visited;
}
private static bool IsUnusedDeconstruction(BoundExpression node)
{
return node.Kind == BoundKind.DeconstructionAssignmentOperator && !((BoundDeconstructionAssignmentOperator)node).IsUsed;
}
public override BoundNode VisitLambda(BoundLambda node)
{
_sawLambdas = true;
var lambda = node.Symbol;
CheckRefReadOnlySymbols(lambda);
var oldContainingSymbol = _factory.CurrentFunction;
var oldInstrumenter = _instrumenter;
try
{
_factory.CurrentFunction = lambda;
if (lambda.IsDirectlyExcludedFromCodeCoverage)
{
_instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter);
}
return base.VisitLambda(node)!;
}
finally
{
_factory.CurrentFunction = oldContainingSymbol;
_instrumenter = oldInstrumenter;
}
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
int localFunctionOrdinal = _availableLocalFunctionOrdinal++;
var localFunction = node.Symbol;
CheckRefReadOnlySymbols(localFunction);
if (_factory.CompilationState.ModuleBuilderOpt is { } moduleBuilder)
{
var typeParameters = localFunction.TypeParameters;
if (typeParameters.Any(typeParameter => typeParameter.HasUnmanagedTypeConstraint))
{
moduleBuilder.EnsureIsUnmanagedAttributeExists();
}
if (hasReturnTypeOrParameter(localFunction, t => t.ContainsNativeInteger()) ||
typeParameters.Any(t => t.ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger())))
{
moduleBuilder.EnsureNativeIntegerAttributeExists();
}
if (_factory.CompilationState.Compilation.ShouldEmitNullableAttributes(localFunction))
{
bool constraintsNeedNullableAttribute = typeParameters.Any(
typeParameter => ((SourceTypeParameterSymbolBase)typeParameter).ConstraintsNeedNullableAttribute());
if (constraintsNeedNullableAttribute || hasReturnTypeOrParameter(localFunction, t => t.NeedsNullableAttribute()))
{
moduleBuilder.EnsureNullableAttributeExists();
}
}
static bool hasReturnTypeOrParameter(LocalFunctionSymbol localFunction, Func<TypeWithAnnotations, bool> predicate) =>
predicate(localFunction.ReturnTypeWithAnnotations) || localFunction.ParameterTypesWithAnnotations.Any(predicate);
}
var oldContainingSymbol = _factory.CurrentFunction;
var oldInstrumenter = _instrumenter;
var oldDynamicFactory = _dynamicFactory;
try
{
_factory.CurrentFunction = localFunction;
if (localFunction.IsDirectlyExcludedFromCodeCoverage)
{
_instrumenter = RemoveDynamicAnalysisInjectors(oldInstrumenter);
}
if (localFunction.IsGenericMethod)
{
// Each generic local function gets its own dynamic factory because it
// needs its own container to cache dynamic call-sites. That type (the container) "inherits"
// local function's type parameters as well as type parameters of all containing methods.
_dynamicFactory = new LoweredDynamicOperationFactory(_factory, _dynamicFactory.MethodOrdinal, localFunctionOrdinal);
}
return base.VisitLocalFunctionStatement(node)!;
}
finally
{
_factory.CurrentFunction = oldContainingSymbol;
_instrumenter = oldInstrumenter;
_dynamicFactory = oldDynamicFactory;
}
}
private static Instrumenter RemoveDynamicAnalysisInjectors(Instrumenter instrumenter)
{
switch (instrumenter)
{
case DynamicAnalysisInjector { Previous: var previous }:
return RemoveDynamicAnalysisInjectors(previous);
case DebugInfoInjector { Previous: var previous } injector:
var newPrevious = RemoveDynamicAnalysisInjectors(previous);
if ((object)newPrevious == previous)
{
return injector;
}
else if ((object)newPrevious == Instrumenter.NoOp)
{
return DebugInfoInjector.Singleton;
}
else
{
return new DebugInfoInjector(previous);
}
case CompoundInstrumenter compound:
// If we hit this it means a new kind of compound instrumenter is in use.
// Either add a new case or add an abstraction that lets us
// filter out the unwanted injectors in a more generalized way.
throw ExceptionUtilities.UnexpectedValue(compound);
default:
Debug.Assert((object)instrumenter == Instrumenter.NoOp);
return instrumenter;
}
}
public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node)
{
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node)
{
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node)
{
return PlaceholderReplacement(node);
}
public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node)
{
if (_inExpressionLambda)
{
// Expression trees do not include the 'this' argument for members.
return node;
}
return PlaceholderReplacement(node);
}
public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node)
=> PlaceholderReplacement(node);
public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node)
=> PlaceholderReplacement(node);
/// <summary>
/// Returns substitution currently used by the rewriter for a placeholder node.
/// Each occurrence of the placeholder node is replaced with the node returned.
/// Throws if there is no substitution.
/// </summary>
private BoundExpression PlaceholderReplacement(BoundValuePlaceholderBase placeholder)
{
Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { });
var value = _placeholderReplacementMapDoNotUseDirectly[placeholder];
AssertPlaceholderReplacement(placeholder, value);
return value;
}
[Conditional("DEBUG")]
private static void AssertPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value)
{
Debug.Assert(value.Type is { } && value.Type.Equals(placeholder.Type, TypeCompareKind.AllIgnoreOptions));
}
/// <summary>
/// Sets substitution used by the rewriter for a placeholder node.
/// Each occurrence of the placeholder node is replaced with the node returned.
/// Throws if there is already a substitution.
/// </summary>
private void AddPlaceholderReplacement(BoundValuePlaceholderBase placeholder, BoundExpression value)
{
AssertPlaceholderReplacement(placeholder, value);
if (_placeholderReplacementMapDoNotUseDirectly is null)
{
_placeholderReplacementMapDoNotUseDirectly = new Dictionary<BoundValuePlaceholderBase, BoundExpression>();
}
_placeholderReplacementMapDoNotUseDirectly.Add(placeholder, value);
}
/// <summary>
/// Removes substitution currently used by the rewriter for a placeholder node.
/// Asserts if there isn't already a substitution.
/// </summary>
private void RemovePlaceholderReplacement(BoundValuePlaceholderBase placeholder)
{
Debug.Assert(placeholder is { });
Debug.Assert(_placeholderReplacementMapDoNotUseDirectly is { });
bool removed = _placeholderReplacementMapDoNotUseDirectly.Remove(placeholder);
Debug.Assert(removed);
}
public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node)
{
// OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node)
{
// DeconstructionVariablePendingInference nodes are only used within initial binding, but don't survive past that stage
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitBadExpression(BoundBadExpression node)
{
// Cannot recurse into BadExpression children since the BadExpression
// may represent being unable to use the child as an lvalue or rvalue.
return node;
}
private static BoundExpression BadExpression(BoundExpression node)
{
Debug.Assert(node.Type is { });
return BadExpression(node.Syntax, node.Type, ImmutableArray.Create(node));
}
private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child)
{
return BadExpression(syntax, resultType, ImmutableArray.Create(child));
}
private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, BoundExpression child1, BoundExpression child2)
{
return BadExpression(syntax, resultType, ImmutableArray.Create(child1, child2));
}
private static BoundExpression BadExpression(SyntaxNode syntax, TypeSymbol resultType, ImmutableArray<BoundExpression> children)
{
return new BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray<Symbol?>.Empty, children, resultType);
}
private bool TryGetWellKnownTypeMember<TSymbol>(SyntaxNode? syntax, WellKnownMember member, out TSymbol symbol, bool isOptional = false, Location? location = null) where TSymbol : Symbol
{
Debug.Assert((syntax != null) ^ (location != null));
symbol = (TSymbol)Binder.GetWellKnownTypeMember(_compilation, member, _diagnostics, syntax: syntax, isOptional: isOptional, location: location);
return symbol is { };
}
/// <summary>
/// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing.
/// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, out MethodSymbol)"/> instead!
/// If used, a unit-test with a missing member is absolutely a must have.
/// </summary>
private MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember)
{
return UnsafeGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics);
}
/// <summary>
/// This function provides a false sense of security, it is likely going to surprise you when the requested member is missing.
/// Recommendation: Do not use, use <see cref="TryGetSpecialTypeMethod(SyntaxNode, SpecialMember, CSharpCompilation, BindingDiagnosticBag, out MethodSymbol)"/> instead!
/// If used, a unit-test with a missing member is absolutely a must have.
/// </summary>
private static MethodSymbol UnsafeGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics)
{
MethodSymbol method;
if (TryGetSpecialTypeMethod(syntax, specialMember, compilation, diagnostics, out method))
{
return method;
}
else
{
MemberDescriptor descriptor = SpecialMembers.GetDescriptor(specialMember);
SpecialType type = (SpecialType)descriptor.DeclaringTypeId;
TypeSymbol container = compilation.Assembly.GetSpecialType(type);
TypeSymbol returnType = new ExtendedErrorTypeSymbol(compilation: compilation, name: descriptor.Name, errorInfo: null, arity: descriptor.Arity);
return new ErrorMethodSymbol(container, returnType, "Missing");
}
}
private bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, out MethodSymbol method)
{
return TryGetSpecialTypeMethod(syntax, specialMember, _compilation, _diagnostics, out method);
}
private static bool TryGetSpecialTypeMethod(SyntaxNode syntax, SpecialMember specialMember, CSharpCompilation compilation, BindingDiagnosticBag diagnostics, out MethodSymbol method)
{
return Binder.TryGetSpecialTypeMember(compilation, specialMember, syntax, diagnostics, out method);
}
public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node)
{
Debug.Assert(node.GetTypeFromHandle is null);
var sourceType = (BoundTypeExpression?)this.Visit(node.SourceType);
Debug.Assert(sourceType is { });
var type = this.VisitType(node.Type);
// Emit needs this helper
MethodSymbol getTypeFromHandle;
if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle))
{
return new BoundTypeOfOperator(node.Syntax, sourceType, null, type, hasErrors: true);
}
return node.Update(sourceType, getTypeFromHandle, type);
}
public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node)
{
Debug.Assert(node.GetTypeFromHandle is null);
var operand = this.VisitExpression(node.Operand);
var type = this.VisitType(node.Type);
// Emit needs this helper
MethodSymbol getTypeFromHandle;
if (!TryGetWellKnownTypeMember(node.Syntax, WellKnownMember.System_Type__GetTypeFromHandle, out getTypeFromHandle))
{
return new BoundRefTypeOperator(node.Syntax, operand, null, type, hasErrors: true);
}
return node.Update(operand, getTypeFromHandle, type);
}
public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node)
{
ImmutableArray<BoundStatement> originalStatements = node.Statements;
var statements = ArrayBuilder<BoundStatement?>.GetInstance(node.Statements.Length);
foreach (var initializer in originalStatements)
{
if (IsFieldOrPropertyInitializer(initializer))
{
if (initializer.Kind == BoundKind.Block)
{
var block = (BoundBlock)initializer;
var statement = RewriteExpressionStatement((BoundExpressionStatement)block.Statements.Single(), suppressInstrumentation: true);
Debug.Assert(statement is { });
statements.Add(block.Update(block.Locals, block.LocalFunctions, ImmutableArray.Create(statement)));
}
else
{
statements.Add(RewriteExpressionStatement((BoundExpressionStatement)initializer, suppressInstrumentation: true));
}
}
else
{
statements.Add(VisitStatement(initializer));
}
}
int optimizedInitializers = 0;
bool optimize = _compilation.Options.OptimizationLevel == OptimizationLevel.Release;
for (int i = 0; i < statements.Count; i++)
{
var stmt = statements[i];
if (stmt == null || (optimize && IsFieldOrPropertyInitializer(originalStatements[i]) && ShouldOptimizeOutInitializer(stmt)))
{
optimizedInitializers++;
if (_factory.CurrentFunction?.IsStatic == false)
{
// NOTE: Dev11 removes static initializers if ONLY all of them are optimized out
statements[i] = null;
}
}
}
ImmutableArray<BoundStatement> rewrittenStatements;
if (optimizedInitializers == statements.Count)
{
// all are optimized away
rewrittenStatements = ImmutableArray<BoundStatement>.Empty;
statements.Free();
}
else
{
// instrument remaining statements
int remaining = 0;
for (int i = 0; i < statements.Count; i++)
{
BoundStatement? rewritten = statements[i];
if (rewritten != null)
{
if (IsFieldOrPropertyInitializer(originalStatements[i]))
{
BoundStatement original = originalStatements[i];
if (Instrument && !original.WasCompilerGenerated)
{
rewritten = _instrumenter.InstrumentFieldOrPropertyInitializer(original, rewritten);
}
}
statements[remaining] = rewritten;
remaining++;
}
}
statements.Count = remaining; // trim any trailing nulls
rewrittenStatements = statements.ToImmutableAndFree()!;
}
return new BoundStatementList(node.Syntax, rewrittenStatements, node.HasErrors);
}
public override BoundNode VisitArrayAccess(BoundArrayAccess node)
{
// An array access expression can be indexed using any of the following types:
// * an integer primitive
// * a System.Index
// * a System.Range
// The last two are only supported on SZArrays. For those cases we need to
// lower into the appropriate helper methods.
if (node.Indices.Length != 1)
{
return base.VisitArrayAccess(node)!;
}
var indexType = VisitType(node.Indices[0].Type);
var F = _factory;
BoundNode resultExpr;
if (TypeSymbol.Equals(
indexType,
_compilation.GetWellKnownType(WellKnownType.System_Index),
TypeCompareKind.ConsiderEverything))
{
// array[Index] is treated like a pattern-based System.Index indexing
// expression, except that array indexers don't actually exist (they
// don't have symbols)
var arrayLocal = F.StoreToTemp(
VisitExpression(node.Expression),
out BoundAssignmentOperator arrayAssign);
var indexOffsetExpr = MakePatternIndexOffsetExpression(
node.Indices[0],
F.ArrayLength(arrayLocal),
out _);
resultExpr = F.Sequence(
ImmutableArray.Create(arrayLocal.LocalSymbol),
ImmutableArray.Create<BoundExpression>(arrayAssign),
F.ArrayAccess(
arrayLocal,
ImmutableArray.Create(indexOffsetExpr)));
}
else if (TypeSymbol.Equals(
indexType,
_compilation.GetWellKnownType(WellKnownType.System_Range),
TypeCompareKind.ConsiderEverything))
{
// array[Range] is compiled to:
// System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray(array, Range)
Debug.Assert(node.Expression.Type is { TypeKind: TypeKind.Array });
var elementType = ((ArrayTypeSymbol)node.Expression.Type).ElementTypeWithAnnotations;
resultExpr = F.Call(
receiver: null,
F.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T)
.Construct(ImmutableArray.Create(elementType)),
ImmutableArray.Create(
VisitExpression(node.Expression),
VisitExpression(node.Indices[0])));
}
else
{
resultExpr = base.VisitArrayAccess(node)!;
}
return resultExpr;
}
internal static bool IsFieldOrPropertyInitializer(BoundStatement initializer)
{
var syntax = initializer.Syntax;
if (syntax.IsKind(SyntaxKind.Parameter))
{
// This is an initialization of a generated property based on record parameter.
return true;
}
if (syntax is ExpressionSyntax { Parent: { } parent } && parent.Kind() == SyntaxKind.EqualsValueClause) // Should be the initial value.
{
Debug.Assert(parent.Parent is { });
switch (parent.Parent.Kind())
{
case SyntaxKind.VariableDeclarator:
case SyntaxKind.PropertyDeclaration:
switch (initializer.Kind)
{
case BoundKind.Block:
var block = (BoundBlock)initializer;
if (block.Statements.Length == 1)
{
initializer = (BoundStatement)block.Statements.First();
if (initializer.Kind == BoundKind.ExpressionStatement)
{
goto case BoundKind.ExpressionStatement;
}
}
break;
case BoundKind.ExpressionStatement:
return ((BoundExpressionStatement)initializer).Expression.Kind == BoundKind.AssignmentOperator;
}
break;
}
}
return false;
}
/// <summary>
/// Returns true if the initializer is a field initializer which should be optimized out
/// </summary>
private static bool ShouldOptimizeOutInitializer(BoundStatement initializer)
{
BoundStatement statement = initializer;
if (statement.Kind != BoundKind.ExpressionStatement)
{
return false;
}
BoundAssignmentOperator? assignment = ((BoundExpressionStatement)statement).Expression as BoundAssignmentOperator;
if (assignment == null)
{
return false;
}
Debug.Assert(assignment.Left.Kind == BoundKind.FieldAccess);
var lhsField = ((BoundFieldAccess)assignment.Left).FieldSymbol;
if (!lhsField.IsStatic && lhsField.ContainingType.IsStructType())
{
return false;
}
BoundExpression rhs = assignment.Right;
return rhs.IsDefaultValue();
}
// There are three situations in which the language permits passing rvalues by reference.
// (technically there are 5, but we can ignore COM and dynamic here, since that results in byval semantics regardless of the parameter ref kind)
//
// #1: Receiver of a struct/generic method call.
//
// The language only requires that receivers of method calls must be readable (RValues are ok).
//
// However the underlying implementation passes receivers of struct methods by reference.
// In such situations it may be possible for the call to cause or observe writes to the receiver variable.
// As a result it is not valid to replace receiver variable with a reference to it or the other way around.
//
// Example1:
// static int x = 123;
// async static Task<string> Test1()
// {
// // cannot capture "x" by value, since write in M1 is observable
// return x.ToString(await M1());
// }
//
// async static Task<string> M1()
// {
// x = 42;
// await Task.Yield();
// return "";
// }
//
// Example2:
// static int x = 123;
// static string Test1()
// {
// // cannot replace value of "x" with a reference to "x"
// // since that would make the method see the mutations in M1();
// return (x + 0).ToString(M1());
// }
//
// static string M1()
// {
// x = 42;
// return "";
// }
//
// #2: Ordinary byval argument passed to an "in" parameter.
//
// The language only requires that ordinary byval arguments must be readable (RValues are ok).
// However if the target parameter is an "in" parameter, the underlying implementation passes by reference.
//
// Example:
// static int x = 123;
// static void Main(string[] args)
// {
// // cannot replace value of "x" with a direct reference to x
// // since Test will see unexpected changes due to aliasing.
// Test(x + 0);
// }
//
// static void Test(in int y)
// {
// Console.WriteLine(y);
// x = 42;
// Console.WriteLine(y);
// }
//
// #3: Ordinary byval interpolated string expression passed to a "ref" interpolated string handler value type.
//
// Interpolated string expressions passed to a builder type are lowered into a handler form. When the handler type
// is a value type (struct, or type parameter constrained to struct (though the latter will fail to bind today because
// there's no constructor)), the final handler instance type is passed by reference if the parameter is by reference.
//
// Example:
// M($""); // Language lowers this to a sequence of creating CustomHandler, appending all values, and evaluating to the builder
// static void M(ref CustomHandler c) { }
//
// NB: The readonliness is not considered here.
// We only care about possible introduction of aliasing. I.E. RValue->LValue change.
// Even if we start with a readonly variable, it cannot be lowered into a writeable one,
// with one exception - spilling of the value into a local, which is ok.
//
internal static bool CanBePassedByReference(BoundExpression expr)
{
if (expr.ConstantValue != null)
{
return false;
}
switch (expr.Kind)
{
case BoundKind.Parameter:
case BoundKind.Local:
case BoundKind.ArrayAccess:
case BoundKind.ThisReference:
case BoundKind.PointerIndirectionOperator:
case BoundKind.PointerElementAccess:
case BoundKind.RefValueOperator:
case BoundKind.PseudoVariable:
case BoundKind.DiscardExpression:
return true;
case BoundKind.DeconstructValuePlaceholder:
// we will consider that placeholder always represents a temp local
// the assumption should be confirmed or changed when https://github.com/dotnet/roslyn/issues/24160 is fixed
return true;
case BoundKind.InterpolatedStringArgumentPlaceholder:
// An argument placeholder is always a reference to some type of temp local,
// either representing a user-typed expression that went through this path
// itself when it was originally visited, or the trailing out parameter that
// is passed by out.
return true;
case BoundKind.InterpolatedStringHandlerPlaceholder:
// A handler placeholder is the receiver of the interpolated string AppendLiteral
// or AppendFormatted calls, and should never be defensively copied.
return true;
case BoundKind.EventAccess:
var eventAccess = (BoundEventAccess)expr;
if (eventAccess.IsUsableAsField)
{
if (eventAccess.EventSymbol.IsStatic)
return true;
Debug.Assert(eventAccess.ReceiverOpt is { });
return CanBePassedByReference(eventAccess.ReceiverOpt);
}
return false;
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)expr;
if (!fieldAccess.FieldSymbol.IsStatic)
{
Debug.Assert(fieldAccess.ReceiverOpt is { });
return CanBePassedByReference(fieldAccess.ReceiverOpt);
}
return true;
case BoundKind.Sequence:
return CanBePassedByReference(((BoundSequence)expr).Value);
case BoundKind.AssignmentOperator:
return ((BoundAssignmentOperator)expr).IsRef;
case BoundKind.ConditionalOperator:
return ((BoundConditionalOperator)expr).IsRef;
case BoundKind.Call:
return ((BoundCall)expr).Method.RefKind != RefKind.None;
case BoundKind.PropertyAccess:
return ((BoundPropertyAccess)expr).PropertySymbol.RefKind != RefKind.None;
case BoundKind.IndexerAccess:
return ((BoundIndexerAccess)expr).Indexer.RefKind != RefKind.None;
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
var refKind = patternIndexer.PatternSymbol switch
{
PropertySymbol p => p.RefKind,
MethodSymbol m => m.RefKind,
_ => throw ExceptionUtilities.UnexpectedValue(patternIndexer.PatternSymbol)
};
return refKind != RefKind.None;
case BoundKind.Conversion:
var conversion = ((BoundConversion)expr);
return expr is BoundConversion { Conversion: { IsInterpolatedStringHandler: true }, Type: { IsValueType: true } };
}
return false;
}
private void CheckRefReadOnlySymbols(MethodSymbol symbol)
{
if (symbol.ReturnsByRefReadonly ||
symbol.Parameters.Any(p => p.RefKind == RefKind.In))
{
_factory.CompilationState.ModuleBuilderOpt?.EnsureIsReadOnlyAttributeExists();
}
}
private CompoundUseSiteInfo<AssemblySymbol> GetNewCompoundUseSiteInfo()
{
return new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly);
}
#if DEBUG
/// <summary>
/// Note: do not use a static/singleton instance of this type, as it holds state.
/// </summary>
private sealed class LocalRewritingValidator : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
/// <summary>
/// Asserts that no unexpected nodes survived local rewriting.
/// </summary>
public static void Validate(BoundNode node)
{
try
{
new LocalRewritingValidator().Visit(node);
}
catch (InsufficientExecutionStackException)
{
// Intentionally ignored to let the overflow get caught in a more crucial visitor
}
}
public override BoundNode? VisitDefaultLiteral(BoundDefaultLiteral node)
{
Fail(node);
return null;
}
public override BoundNode? VisitUsingStatement(BoundUsingStatement node)
{
Fail(node);
return null;
}
public override BoundNode? VisitIfStatement(BoundIfStatement node)
{
Fail(node);
return null;
}
public override BoundNode? VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node)
{
Fail(node);
return null;
}
public override BoundNode? VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node)
{
Fail(node);
return null;
}
public override BoundNode? VisitDisposableValuePlaceholder(BoundDisposableValuePlaceholder node)
{
Fail(node);
return null;
}
public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node)
{
Fail(node);
return null;
}
public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node)
{
Fail(node);
return null;
}
private void Fail(BoundNode node)
{
Debug.Assert(false, $"Bound nodes of kind {node.Kind} should not survive past local rewriting");
}
}
#endif
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/Core/Portable/CodeLens/ReferenceLocationDescriptor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.CodeLens
{
/// <summary>
/// Holds information required to display and navigate to individual references
/// </summary>
[DataContract]
internal sealed class ReferenceLocationDescriptor
{
/// <summary>
/// Fully qualified name of the symbol containing the reference location
/// </summary>
[DataMember(Order = 0)]
public string LongDescription { get; }
/// <summary>
/// Language of the reference location
/// </summary>
[DataMember(Order = 1)]
public string Language { get; }
/// <summary>
/// The kind of symbol containing the reference location (such as type, method, property, etc.)
/// </summary>
[DataMember(Order = 2)]
public Glyph? Glyph { get; }
/// <summary>
/// Reference's span start based on the document content
/// </summary>
[DataMember(Order = 3)]
public int SpanStart { get; }
/// <summary>
/// Reference's span length based on the document content
/// </summary>
[DataMember(Order = 4)]
public int SpanLength { get; }
/// <summary>
/// Reference's line based on the document content
/// </summary>
[DataMember(Order = 5)]
public int LineNumber { get; }
/// <summary>
/// Reference's character based on the document content
/// </summary>
[DataMember(Order = 6)]
public int ColumnNumber { get; }
[DataMember(Order = 7)]
public Guid ProjectGuid { get; }
[DataMember(Order = 8)]
public Guid DocumentGuid { get; }
/// <summary>
/// Document's file path
/// </summary>
[DataMember(Order = 9)]
public string FilePath { get; }
/// <summary>
/// the full line of source that contained the reference
/// </summary>
[DataMember(Order = 10)]
public string ReferenceLineText { get; }
/// <summary>
/// the beginning of the span within reference text that was the use of the reference
/// </summary>
[DataMember(Order = 11)]
public int ReferenceStart { get; }
/// <summary>
/// the length of the span of the reference
/// </summary>
[DataMember(Order = 12)]
public int ReferenceLength { get; }
/// <summary>
/// Text above the line with the reference
/// </summary>
[DataMember(Order = 13)]
public string BeforeReferenceText1 { get; }
/// <summary>
/// Text above the line with the reference
/// </summary>
[DataMember(Order = 14)]
public string BeforeReferenceText2 { get; }
/// <summary>
/// Text below the line with the reference
/// </summary>
[DataMember(Order = 15)]
public string AfterReferenceText1 { get; }
/// <summary>
/// Text below the line with the reference
/// </summary>
[DataMember(Order = 16)]
public string AfterReferenceText2 { get; }
public ReferenceLocationDescriptor(
string longDescription,
string language,
Glyph? glyph,
int spanStart,
int spanLength,
int lineNumber,
int columnNumber,
Guid projectGuid,
Guid documentGuid,
string filePath,
string referenceLineText,
int referenceStart,
int referenceLength,
string beforeReferenceText1,
string beforeReferenceText2,
string afterReferenceText1,
string afterReferenceText2)
{
LongDescription = longDescription;
Language = language;
Glyph = glyph;
SpanStart = spanStart;
SpanLength = spanLength;
LineNumber = lineNumber;
ColumnNumber = columnNumber;
// We want to keep track of the location's document if it comes from a file in your solution.
ProjectGuid = projectGuid;
DocumentGuid = documentGuid;
FilePath = filePath;
ReferenceLineText = referenceLineText;
ReferenceStart = referenceStart;
ReferenceLength = referenceLength;
BeforeReferenceText1 = beforeReferenceText1;
BeforeReferenceText2 = beforeReferenceText2;
AfterReferenceText1 = afterReferenceText1;
AfterReferenceText2 = afterReferenceText2;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.CodeLens
{
/// <summary>
/// Holds information required to display and navigate to individual references
/// </summary>
[DataContract]
internal sealed class ReferenceLocationDescriptor
{
/// <summary>
/// Fully qualified name of the symbol containing the reference location
/// </summary>
[DataMember(Order = 0)]
public string LongDescription { get; }
/// <summary>
/// Language of the reference location
/// </summary>
[DataMember(Order = 1)]
public string Language { get; }
/// <summary>
/// The kind of symbol containing the reference location (such as type, method, property, etc.)
/// </summary>
[DataMember(Order = 2)]
public Glyph? Glyph { get; }
/// <summary>
/// Reference's span start based on the document content
/// </summary>
[DataMember(Order = 3)]
public int SpanStart { get; }
/// <summary>
/// Reference's span length based on the document content
/// </summary>
[DataMember(Order = 4)]
public int SpanLength { get; }
/// <summary>
/// Reference's line based on the document content
/// </summary>
[DataMember(Order = 5)]
public int LineNumber { get; }
/// <summary>
/// Reference's character based on the document content
/// </summary>
[DataMember(Order = 6)]
public int ColumnNumber { get; }
[DataMember(Order = 7)]
public Guid ProjectGuid { get; }
[DataMember(Order = 8)]
public Guid DocumentGuid { get; }
/// <summary>
/// Document's file path
/// </summary>
[DataMember(Order = 9)]
public string FilePath { get; }
/// <summary>
/// the full line of source that contained the reference
/// </summary>
[DataMember(Order = 10)]
public string ReferenceLineText { get; }
/// <summary>
/// the beginning of the span within reference text that was the use of the reference
/// </summary>
[DataMember(Order = 11)]
public int ReferenceStart { get; }
/// <summary>
/// the length of the span of the reference
/// </summary>
[DataMember(Order = 12)]
public int ReferenceLength { get; }
/// <summary>
/// Text above the line with the reference
/// </summary>
[DataMember(Order = 13)]
public string BeforeReferenceText1 { get; }
/// <summary>
/// Text above the line with the reference
/// </summary>
[DataMember(Order = 14)]
public string BeforeReferenceText2 { get; }
/// <summary>
/// Text below the line with the reference
/// </summary>
[DataMember(Order = 15)]
public string AfterReferenceText1 { get; }
/// <summary>
/// Text below the line with the reference
/// </summary>
[DataMember(Order = 16)]
public string AfterReferenceText2 { get; }
public ReferenceLocationDescriptor(
string longDescription,
string language,
Glyph? glyph,
int spanStart,
int spanLength,
int lineNumber,
int columnNumber,
Guid projectGuid,
Guid documentGuid,
string filePath,
string referenceLineText,
int referenceStart,
int referenceLength,
string beforeReferenceText1,
string beforeReferenceText2,
string afterReferenceText1,
string afterReferenceText2)
{
LongDescription = longDescription;
Language = language;
Glyph = glyph;
SpanStart = spanStart;
SpanLength = spanLength;
LineNumber = lineNumber;
ColumnNumber = columnNumber;
// We want to keep track of the location's document if it comes from a file in your solution.
ProjectGuid = projectGuid;
DocumentGuid = documentGuid;
FilePath = filePath;
ReferenceLineText = referenceLineText;
ReferenceStart = referenceStart;
ReferenceLength = referenceLength;
BeforeReferenceText1 = beforeReferenceText1;
BeforeReferenceText2 = beforeReferenceText2;
AfterReferenceText1 = afterReferenceText1;
AfterReferenceText2 = afterReferenceText2;
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/TestUtilities/Classification/AbstractClassifierTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification
{
[UseExportProvider]
public abstract class AbstractClassifierTests
{
protected AbstractClassifierTests() { }
protected abstract Task<ImmutableArray<ClassifiedSpan>> GetClassificationSpansAsync(string text, TextSpan span, ParseOptions parseOptions, TestHost testHost);
protected abstract string WrapInClass(string className, string code);
protected abstract string WrapInExpression(string code);
protected abstract string WrapInMethod(string className, string methodName, string code);
protected abstract string WrapInNamespace(string code);
protected abstract Task DefaultTestAsync(string code, string allCode, TestHost testHost, FormattedClassification[] expected);
protected async Task TestAsync(
string code,
string allCode,
TestHost testHost,
ParseOptions parseOptions,
params FormattedClassification[] expected)
{
var start = allCode.IndexOf(code, StringComparison.Ordinal);
var length = code.Length;
var span = new TextSpan(start, length);
var actual = await GetClassificationSpansAsync(allCode, span, parseOptions, testHost);
var actualOrdered = actual.OrderBy((t1, t2) => t1.TextSpan.Start - t2.TextSpan.Start);
var actualFormatted = actualOrdered.Select(a => new FormattedClassification(allCode.Substring(a.TextSpan.Start, a.TextSpan.Length), a.ClassificationType));
AssertEx.Equal(expected, actualFormatted);
}
private async Task TestAsync(
string code,
string allCode,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
foreach (var parseOptions in parseOptionsSet)
{
await TestAsync(code, allCode, testHost, parseOptions, expected);
}
}
protected async Task TestAsync(
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
await TestAsync(code, code, testHost, parseOptionsSet, expected);
}
protected async Task TestAsync(
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
await DefaultTestAsync(code, code, testHost, expected);
}
protected async Task TestAsync(
string code,
string allCode,
TestHost testHost,
params FormattedClassification[] expected)
{
await DefaultTestAsync(code, allCode, testHost, expected);
}
protected async Task TestInClassAsync(
string className,
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
var allCode = WrapInClass(className, code);
await TestAsync(code, allCode, testHost, parseOptionsSet, expected);
}
protected async Task TestInClassAsync(
string className,
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
var allCode = WrapInClass(className, code);
await DefaultTestAsync(code, allCode, testHost, expected);
}
protected Task TestInClassAsync(
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
return TestInClassAsync("C", code, testHost, parseOptionsSet, expected);
}
protected Task TestInClassAsync(
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
return TestInClassAsync("C", code, testHost, expected);
}
protected async Task TestInExpressionAsync(
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
var allCode = WrapInExpression(code);
await DefaultTestAsync(code, allCode, testHost, expected);
}
protected async Task TestInExpressionAsync(
string code,
ParseOptions[] parseOptionsSet,
TestHost testHost,
params FormattedClassification[] expected)
{
var allCode = WrapInExpression(code);
await TestAsync(code, allCode, testHost, parseOptionsSet, expected);
}
protected async Task TestInMethodAsync(
string className,
string methodName,
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
var allCode = WrapInMethod(className, methodName, code);
await TestAsync(code, allCode, testHost, parseOptionsSet, expected);
}
protected async Task TestInMethodAsync(
string className,
string methodName,
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
var allCode = WrapInMethod(className, methodName, code);
await DefaultTestAsync(code, allCode, testHost, expected);
}
protected Task TestInMethodAsync(
string methodName,
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
return TestInMethodAsync("C", methodName, code, testHost, parseOptionsSet, expected);
}
protected Task TestInMethodAsync(
string methodName,
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
return TestInMethodAsync("C", methodName, code, testHost, expected);
}
protected Task TestInMethodAsync(
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
return TestInMethodAsync("C", "M", code, testHost, parseOptionsSet, expected);
}
protected Task TestInMethodAsync(
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
return TestInMethodAsync("C", "M", code, testHost, expected);
}
protected async Task TestInNamespaceAsync(
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
var allCode = WrapInNamespace(code);
await TestAsync(code, allCode, testHost, parseOptionsSet, expected);
}
protected async Task TestInNamespaceAsync(
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
var allCode = WrapInNamespace(code);
await DefaultTestAsync(code, allCode, testHost, expected);
}
[DebuggerStepThrough]
protected static FormattedClassification[] Classifications(params FormattedClassification[] expected) => expected;
[DebuggerStepThrough]
protected static ParseOptions[] ParseOptions(params ParseOptions[] options) => options;
protected static async Task<ImmutableArray<ClassifiedSpan>> GetSemanticClassificationsAsync(Document document, TextSpan span)
{
var service = document.GetRequiredLanguageService<IClassificationService>();
using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var result);
await service.AddSemanticClassificationsAsync(document, span, result, CancellationToken.None);
return result.ToImmutable();
}
protected static async Task<ImmutableArray<ClassifiedSpan>> GetSyntacticClassificationsAsync(Document document, TextSpan span)
{
var root = await document.GetSyntaxRootAsync();
var service = document.GetLanguageService<ISyntaxClassificationService>();
using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var results);
service.AddSyntacticClassifications(root, span, results, CancellationToken.None);
return results.ToImmutable();
}
protected static async Task<ImmutableArray<ClassifiedSpan>> GetAllClassificationsAsync(Document document, TextSpan span)
{
var semanticClassifications = await GetSemanticClassificationsAsync(document, span);
var syntacticClassifications = await GetSyntacticClassificationsAsync(document, span);
var classificationsSpans = new HashSet<TextSpan>();
// Add all the semantic classifications in.
var allClassifications = new List<ClassifiedSpan>(semanticClassifications);
classificationsSpans.AddRange(allClassifications.Select(t => t.TextSpan));
// Add the syntactic classifications. But only if they don't conflict with a semantic classification.
allClassifications.AddRange(
from t in syntacticClassifications
where !classificationsSpans.Contains(t.TextSpan)
select t);
return allClassifications.ToImmutableArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification
{
[UseExportProvider]
public abstract class AbstractClassifierTests
{
protected AbstractClassifierTests() { }
protected abstract Task<ImmutableArray<ClassifiedSpan>> GetClassificationSpansAsync(string text, TextSpan span, ParseOptions parseOptions, TestHost testHost);
protected abstract string WrapInClass(string className, string code);
protected abstract string WrapInExpression(string code);
protected abstract string WrapInMethod(string className, string methodName, string code);
protected abstract string WrapInNamespace(string code);
protected abstract Task DefaultTestAsync(string code, string allCode, TestHost testHost, FormattedClassification[] expected);
protected async Task TestAsync(
string code,
string allCode,
TestHost testHost,
ParseOptions parseOptions,
params FormattedClassification[] expected)
{
var start = allCode.IndexOf(code, StringComparison.Ordinal);
var length = code.Length;
var span = new TextSpan(start, length);
var actual = await GetClassificationSpansAsync(allCode, span, parseOptions, testHost);
var actualOrdered = actual.OrderBy((t1, t2) => t1.TextSpan.Start - t2.TextSpan.Start);
var actualFormatted = actualOrdered.Select(a => new FormattedClassification(allCode.Substring(a.TextSpan.Start, a.TextSpan.Length), a.ClassificationType));
AssertEx.Equal(expected, actualFormatted);
}
private async Task TestAsync(
string code,
string allCode,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
foreach (var parseOptions in parseOptionsSet)
{
await TestAsync(code, allCode, testHost, parseOptions, expected);
}
}
protected async Task TestAsync(
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
await TestAsync(code, code, testHost, parseOptionsSet, expected);
}
protected async Task TestAsync(
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
await DefaultTestAsync(code, code, testHost, expected);
}
protected async Task TestAsync(
string code,
string allCode,
TestHost testHost,
params FormattedClassification[] expected)
{
await DefaultTestAsync(code, allCode, testHost, expected);
}
protected async Task TestInClassAsync(
string className,
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
var allCode = WrapInClass(className, code);
await TestAsync(code, allCode, testHost, parseOptionsSet, expected);
}
protected async Task TestInClassAsync(
string className,
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
var allCode = WrapInClass(className, code);
await DefaultTestAsync(code, allCode, testHost, expected);
}
protected Task TestInClassAsync(
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
return TestInClassAsync("C", code, testHost, parseOptionsSet, expected);
}
protected Task TestInClassAsync(
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
return TestInClassAsync("C", code, testHost, expected);
}
protected async Task TestInExpressionAsync(
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
var allCode = WrapInExpression(code);
await DefaultTestAsync(code, allCode, testHost, expected);
}
protected async Task TestInExpressionAsync(
string code,
ParseOptions[] parseOptionsSet,
TestHost testHost,
params FormattedClassification[] expected)
{
var allCode = WrapInExpression(code);
await TestAsync(code, allCode, testHost, parseOptionsSet, expected);
}
protected async Task TestInMethodAsync(
string className,
string methodName,
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
var allCode = WrapInMethod(className, methodName, code);
await TestAsync(code, allCode, testHost, parseOptionsSet, expected);
}
protected async Task TestInMethodAsync(
string className,
string methodName,
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
var allCode = WrapInMethod(className, methodName, code);
await DefaultTestAsync(code, allCode, testHost, expected);
}
protected Task TestInMethodAsync(
string methodName,
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
return TestInMethodAsync("C", methodName, code, testHost, parseOptionsSet, expected);
}
protected Task TestInMethodAsync(
string methodName,
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
return TestInMethodAsync("C", methodName, code, testHost, expected);
}
protected Task TestInMethodAsync(
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
return TestInMethodAsync("C", "M", code, testHost, parseOptionsSet, expected);
}
protected Task TestInMethodAsync(
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
return TestInMethodAsync("C", "M", code, testHost, expected);
}
protected async Task TestInNamespaceAsync(
string code,
TestHost testHost,
ParseOptions[] parseOptionsSet,
params FormattedClassification[] expected)
{
var allCode = WrapInNamespace(code);
await TestAsync(code, allCode, testHost, parseOptionsSet, expected);
}
protected async Task TestInNamespaceAsync(
string code,
TestHost testHost,
params FormattedClassification[] expected)
{
var allCode = WrapInNamespace(code);
await DefaultTestAsync(code, allCode, testHost, expected);
}
[DebuggerStepThrough]
protected static FormattedClassification[] Classifications(params FormattedClassification[] expected) => expected;
[DebuggerStepThrough]
protected static ParseOptions[] ParseOptions(params ParseOptions[] options) => options;
protected static async Task<ImmutableArray<ClassifiedSpan>> GetSemanticClassificationsAsync(Document document, TextSpan span)
{
var service = document.GetRequiredLanguageService<IClassificationService>();
using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var result);
await service.AddSemanticClassificationsAsync(document, span, result, CancellationToken.None);
return result.ToImmutable();
}
protected static async Task<ImmutableArray<ClassifiedSpan>> GetSyntacticClassificationsAsync(Document document, TextSpan span)
{
var root = await document.GetSyntaxRootAsync();
var service = document.GetLanguageService<ISyntaxClassificationService>();
using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var results);
service.AddSyntacticClassifications(root, span, results, CancellationToken.None);
return results.ToImmutable();
}
protected static async Task<ImmutableArray<ClassifiedSpan>> GetAllClassificationsAsync(Document document, TextSpan span)
{
var semanticClassifications = await GetSemanticClassificationsAsync(document, span);
var syntacticClassifications = await GetSyntacticClassificationsAsync(document, span);
var classificationsSpans = new HashSet<TextSpan>();
// Add all the semantic classifications in.
var allClassifications = new List<ClassifiedSpan>(semanticClassifications);
classificationsSpans.AddRange(allClassifications.Select(t => t.TextSpan));
// Add the syntactic classifications. But only if they don't conflict with a semantic classification.
allClassifications.AddRange(
from t in syntacticClassifications
where !classificationsSpans.Contains(t.TextSpan)
select t);
return allClassifications.ToImmutableArray();
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/CSharp/Portable/SplitOrMergeIfStatements/CSharpSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.SplitOrMergeIfStatements;
namespace Microsoft.CodeAnalysis.CSharp.SplitOrMergeIfStatements
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.SplitIntoConsecutiveIfStatements), Shared]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.InvertLogical, Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)]
internal sealed class CSharpSplitIntoConsecutiveIfStatementsCodeRefactoringProvider
: AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpSplitIntoConsecutiveIfStatementsCodeRefactoringProvider()
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.SplitOrMergeIfStatements;
namespace Microsoft.CodeAnalysis.CSharp.SplitOrMergeIfStatements
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.SplitIntoConsecutiveIfStatements), Shared]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.InvertLogical, Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)]
internal sealed class CSharpSplitIntoConsecutiveIfStatementsCodeRefactoringProvider
: AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpSplitIntoConsecutiveIfStatementsCodeRefactoringProvider()
{
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
internal static class GenerateEqualsAndGetHashCodeFromMembersOptions
{
public static readonly PerLanguageOption2<bool> GenerateOperators = new(
nameof(GenerateEqualsAndGetHashCodeFromMembersOptions),
nameof(GenerateOperators), defaultValue: false,
storageLocations: new RoamingProfileStorageLocation(
$"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(GenerateOperators)}"));
public static readonly PerLanguageOption2<bool> ImplementIEquatable = new(
nameof(GenerateEqualsAndGetHashCodeFromMembersOptions),
nameof(ImplementIEquatable), defaultValue: false,
storageLocations: new RoamingProfileStorageLocation(
$"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(ImplementIEquatable)}"));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
internal static class GenerateEqualsAndGetHashCodeFromMembersOptions
{
public static readonly PerLanguageOption2<bool> GenerateOperators = new(
nameof(GenerateEqualsAndGetHashCodeFromMembersOptions),
nameof(GenerateOperators), defaultValue: false,
storageLocations: new RoamingProfileStorageLocation(
$"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(GenerateOperators)}"));
public static readonly PerLanguageOption2<bool> ImplementIEquatable = new(
nameof(GenerateEqualsAndGetHashCodeFromMembersOptions),
nameof(ImplementIEquatable), defaultValue: false,
storageLocations: new RoamingProfileStorageLocation(
$"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(ImplementIEquatable)}"));
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Workspaces/CSharp/Portable/Classification/CSharpClassificationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Classification
{
[ExportLanguageService(typeof(IClassificationService), LanguageNames.CSharp), Shared]
internal class CSharpEditorClassificationService : AbstractClassificationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpEditorClassificationService()
{
}
public override void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken)
=> ClassificationHelpers.AddLexicalClassifications(text, textSpan, result, cancellationToken);
public override ClassifiedSpan AdjustStaleClassification(SourceText text, ClassifiedSpan classifiedSpan)
=> ClassificationHelpers.AdjustStaleClassification(text, 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.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Classification
{
[ExportLanguageService(typeof(IClassificationService), LanguageNames.CSharp), Shared]
internal class CSharpEditorClassificationService : AbstractClassificationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpEditorClassificationService()
{
}
public override void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken)
=> ClassificationHelpers.AddLexicalClassifications(text, textSpan, result, cancellationToken);
public override ClassifiedSpan AdjustStaleClassification(SourceText text, ClassifiedSpan classifiedSpan)
=> ClassificationHelpers.AdjustStaleClassification(text, classifiedSpan);
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/CSharp/Portable/MakeMethodSynchronous/CSharpMakeMethodSynchronousCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MakeMethodSynchronous;
using Microsoft.CodeAnalysis.Shared.Extensions;
using static Microsoft.CodeAnalysis.MakeMethodAsynchronous.AbstractMakeMethodAsynchronousCodeFixProvider;
namespace Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeMethodSynchronous), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.AddImport)]
internal class CSharpMakeMethodSynchronousCodeFixProvider : AbstractMakeMethodSynchronousCodeFixProvider
{
private const string CS1998 = nameof(CS1998); // This async method lacks 'await' operators and will run synchronously.
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpMakeMethodSynchronousCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS1998);
protected override bool IsAsyncSupportingFunctionSyntax(SyntaxNode node)
=> node.IsAsyncSupportingFunctionSyntax();
protected override SyntaxNode RemoveAsyncTokenAndFixReturnType(IMethodSymbol methodSymbolOpt, SyntaxNode node, KnownTypes knownTypes)
{
switch (node)
{
case MethodDeclarationSyntax method: return FixMethod(methodSymbolOpt, method, knownTypes);
case LocalFunctionStatementSyntax localFunction: return FixLocalFunction(methodSymbolOpt, localFunction, knownTypes);
case AnonymousMethodExpressionSyntax method: return RemoveAsyncModifierHelpers.WithoutAsyncModifier(method);
case ParenthesizedLambdaExpressionSyntax lambda: return RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda);
case SimpleLambdaExpressionSyntax lambda: return RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda);
default: return node;
}
}
private static SyntaxNode FixMethod(IMethodSymbol methodSymbol, MethodDeclarationSyntax method, KnownTypes knownTypes)
{
var newReturnType = FixMethodReturnType(methodSymbol, method.ReturnType, knownTypes);
return RemoveAsyncModifierHelpers.WithoutAsyncModifier(method, newReturnType);
}
private static SyntaxNode FixLocalFunction(IMethodSymbol methodSymbol, LocalFunctionStatementSyntax localFunction, KnownTypes knownTypes)
{
var newReturnType = FixMethodReturnType(methodSymbol, localFunction.ReturnType, knownTypes);
return RemoveAsyncModifierHelpers.WithoutAsyncModifier(localFunction, newReturnType);
}
private static TypeSyntax FixMethodReturnType(IMethodSymbol methodSymbol, TypeSyntax returnTypeSyntax, KnownTypes knownTypes)
{
var newReturnType = returnTypeSyntax;
var returnType = methodSymbol.ReturnType;
if (returnType.OriginalDefinition.Equals(knownTypes._taskType))
{
// If the return type is Task, then make the new return type "void".
newReturnType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)).WithTriviaFrom(returnTypeSyntax);
}
else if (returnType.OriginalDefinition.Equals(knownTypes._taskOfTType))
{
// If the return type is Task<T>, then make the new return type "T".
newReturnType = returnType.GetTypeArguments()[0].GenerateTypeSyntax().WithTriviaFrom(returnTypeSyntax);
}
else if (returnType.OriginalDefinition.Equals(knownTypes._iAsyncEnumerableOfTTypeOpt))
{
// If the return type is IAsyncEnumerable<T>, then make the new return type IEnumerable<T>.
newReturnType = knownTypes._iEnumerableOfTType.Construct(methodSymbol.ReturnType.GetTypeArguments()[0]).GenerateTypeSyntax();
}
else if (returnType.OriginalDefinition.Equals(knownTypes._iAsyncEnumeratorOfTTypeOpt))
{
// If the return type is IAsyncEnumerator<T>, then make the new return type IEnumerator<T>.
newReturnType = knownTypes._iEnumeratorOfTType.Construct(methodSymbol.ReturnType.GetTypeArguments()[0]).GenerateTypeSyntax();
}
return newReturnType;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MakeMethodSynchronous;
using Microsoft.CodeAnalysis.Shared.Extensions;
using static Microsoft.CodeAnalysis.MakeMethodAsynchronous.AbstractMakeMethodAsynchronousCodeFixProvider;
namespace Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeMethodSynchronous), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.AddImport)]
internal class CSharpMakeMethodSynchronousCodeFixProvider : AbstractMakeMethodSynchronousCodeFixProvider
{
private const string CS1998 = nameof(CS1998); // This async method lacks 'await' operators and will run synchronously.
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpMakeMethodSynchronousCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS1998);
protected override bool IsAsyncSupportingFunctionSyntax(SyntaxNode node)
=> node.IsAsyncSupportingFunctionSyntax();
protected override SyntaxNode RemoveAsyncTokenAndFixReturnType(IMethodSymbol methodSymbolOpt, SyntaxNode node, KnownTypes knownTypes)
{
switch (node)
{
case MethodDeclarationSyntax method: return FixMethod(methodSymbolOpt, method, knownTypes);
case LocalFunctionStatementSyntax localFunction: return FixLocalFunction(methodSymbolOpt, localFunction, knownTypes);
case AnonymousMethodExpressionSyntax method: return RemoveAsyncModifierHelpers.WithoutAsyncModifier(method);
case ParenthesizedLambdaExpressionSyntax lambda: return RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda);
case SimpleLambdaExpressionSyntax lambda: return RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda);
default: return node;
}
}
private static SyntaxNode FixMethod(IMethodSymbol methodSymbol, MethodDeclarationSyntax method, KnownTypes knownTypes)
{
var newReturnType = FixMethodReturnType(methodSymbol, method.ReturnType, knownTypes);
return RemoveAsyncModifierHelpers.WithoutAsyncModifier(method, newReturnType);
}
private static SyntaxNode FixLocalFunction(IMethodSymbol methodSymbol, LocalFunctionStatementSyntax localFunction, KnownTypes knownTypes)
{
var newReturnType = FixMethodReturnType(methodSymbol, localFunction.ReturnType, knownTypes);
return RemoveAsyncModifierHelpers.WithoutAsyncModifier(localFunction, newReturnType);
}
private static TypeSyntax FixMethodReturnType(IMethodSymbol methodSymbol, TypeSyntax returnTypeSyntax, KnownTypes knownTypes)
{
var newReturnType = returnTypeSyntax;
var returnType = methodSymbol.ReturnType;
if (returnType.OriginalDefinition.Equals(knownTypes._taskType))
{
// If the return type is Task, then make the new return type "void".
newReturnType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)).WithTriviaFrom(returnTypeSyntax);
}
else if (returnType.OriginalDefinition.Equals(knownTypes._taskOfTType))
{
// If the return type is Task<T>, then make the new return type "T".
newReturnType = returnType.GetTypeArguments()[0].GenerateTypeSyntax().WithTriviaFrom(returnTypeSyntax);
}
else if (returnType.OriginalDefinition.Equals(knownTypes._iAsyncEnumerableOfTTypeOpt))
{
// If the return type is IAsyncEnumerable<T>, then make the new return type IEnumerable<T>.
newReturnType = knownTypes._iEnumerableOfTType.Construct(methodSymbol.ReturnType.GetTypeArguments()[0]).GenerateTypeSyntax();
}
else if (returnType.OriginalDefinition.Equals(knownTypes._iAsyncEnumeratorOfTTypeOpt))
{
// If the return type is IAsyncEnumerator<T>, then make the new return type IEnumerator<T>.
newReturnType = knownTypes._iEnumeratorOfTType.Construct(methodSymbol.ReturnType.GetTypeArguments()[0]).GenerateTypeSyntax();
}
return newReturnType;
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/Core/Portable/IncrementalCaches/MetadataInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.FindSymbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.IncrementalCaches
{
internal partial class SymbolTreeInfoIncrementalAnalyzerProvider
{
private readonly struct MetadataInfo
{
/// <summary>
/// Can't be null. Even if we weren't able to read in metadata, we'll still create an empty
/// index.
/// </summary>
public readonly SymbolTreeInfo SymbolTreeInfo;
/// <summary>
/// The set of projects that are referencing this metadata-index. When this becomes empty we can dump the
/// index from memory.
/// </summary>
/// <remarks>
/// <para>Accesses to this collection must lock the set.</para>
/// </remarks>
public readonly HashSet<ProjectId> ReferencingProjects;
public MetadataInfo(SymbolTreeInfo info, HashSet<ProjectId> referencingProjects)
{
Contract.ThrowIfNull(info);
SymbolTreeInfo = info;
ReferencingProjects = referencingProjects;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.FindSymbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.IncrementalCaches
{
internal partial class SymbolTreeInfoIncrementalAnalyzerProvider
{
private readonly struct MetadataInfo
{
/// <summary>
/// Can't be null. Even if we weren't able to read in metadata, we'll still create an empty
/// index.
/// </summary>
public readonly SymbolTreeInfo SymbolTreeInfo;
/// <summary>
/// The set of projects that are referencing this metadata-index. When this becomes empty we can dump the
/// index from memory.
/// </summary>
/// <remarks>
/// <para>Accesses to this collection must lock the set.</para>
/// </remarks>
public readonly HashSet<ProjectId> ReferencingProjects;
public MetadataInfo(SymbolTreeInfo info, HashSet<ProjectId> referencingProjects)
{
Contract.ThrowIfNull(info);
SymbolTreeInfo = info;
ReferencingProjects = referencingProjects;
}
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/Core/Portable/Wrapping/SeparatedSyntaxList/SeparatedSyntaxListCodeActionComputer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Wrapping.SeparatedSyntaxList
{
internal abstract partial class AbstractSeparatedSyntaxListWrapper<TListSyntax, TListItemSyntax>
{
/// <summary>
/// Class responsible for actually computing the entire set of code actions to offer the user.
/// </summary>
private class SeparatedSyntaxListCodeActionComputer : AbstractCodeActionComputer<AbstractSeparatedSyntaxListWrapper<TListSyntax, TListItemSyntax>>
{
private readonly TListSyntax _listSyntax;
private readonly SeparatedSyntaxList<TListItemSyntax> _listItems;
/// <summary>
/// The indentation string necessary to indent an item in a list such that the start of
/// that item will exact start at the end of the open-token for the containing list. i.e.
///
/// void Goobar(
/// ^
/// |
///
/// This is the indentation we want when we're aligning wrapped items with the first item
/// in the list.
/// </summary>
private readonly SyntaxTrivia _afterOpenTokenIndentationTrivia;
/// <summary>
/// Indentation amount for any items that have been wrapped to a new line. Valid if we're
/// not aligning with the first item. i.e.
///
/// void Goobar(
/// ^
/// |
/// </summary>
private readonly SyntaxTrivia _singleIndentationTrivia;
public SeparatedSyntaxListCodeActionComputer(
AbstractSeparatedSyntaxListWrapper<TListSyntax, TListItemSyntax> service,
Document document, SourceText sourceText, DocumentOptionSet options,
TListSyntax listSyntax, SeparatedSyntaxList<TListItemSyntax> listItems,
CancellationToken cancellationToken)
: base(service, document, sourceText, options, cancellationToken)
{
_listSyntax = listSyntax;
_listItems = listItems;
var generator = SyntaxGenerator.GetGenerator(OriginalDocument);
_afterOpenTokenIndentationTrivia = generator.Whitespace(GetAfterOpenTokenIdentation());
_singleIndentationTrivia = generator.Whitespace(GetSingleIdentation());
}
private void AddTextChangeBetweenOpenAndFirstItem(
WrappingStyle wrappingStyle, ArrayBuilder<Edit> result)
{
result.Add(wrappingStyle == WrappingStyle.WrapFirst_IndentRest
? Edit.UpdateBetween(_listSyntax.GetFirstToken(), NewLineTrivia, _singleIndentationTrivia, _listItems[0])
: Edit.DeleteBetween(_listSyntax.GetFirstToken(), _listItems[0]));
}
private string GetAfterOpenTokenIdentation()
{
var openToken = _listSyntax.GetFirstToken();
var afterOpenTokenOffset = OriginalSourceText.GetOffset(openToken.Span.End);
var indentString = afterOpenTokenOffset.CreateIndentationString(UseTabs, TabSize);
return indentString;
}
private string GetSingleIdentation()
{
// Insert a newline after the open token of the list. Then ask the
// ISynchronousIndentationService where it thinks that the next line should be
// indented.
var openToken = _listSyntax.GetFirstToken();
return GetSmartIndentationAfter(openToken);
}
private SyntaxTrivia GetIndentationTrivia(WrappingStyle wrappingStyle)
{
return wrappingStyle == WrappingStyle.UnwrapFirst_AlignRest
? _afterOpenTokenIndentationTrivia
: _singleIndentationTrivia;
}
protected override async Task<ImmutableArray<WrappingGroup>> ComputeWrappingGroupsAsync()
{
using var _ = ArrayBuilder<WrappingGroup>.GetInstance(out var result);
await AddWrappingGroupsAsync(result).ConfigureAwait(false);
return result.ToImmutable();
}
private async Task AddWrappingGroupsAsync(ArrayBuilder<WrappingGroup> result)
{
result.Add(await GetWrapEveryGroupAsync().ConfigureAwait(false));
result.Add(await GetUnwrapGroupAsync().ConfigureAwait(false));
result.Add(await GetWrapLongGroupAsync().ConfigureAwait(false));
}
#region unwrap group
private async Task<WrappingGroup> GetUnwrapGroupAsync()
{
using var _ = ArrayBuilder<WrapItemsAction>.GetInstance(out var unwrapActions);
var parentTitle = Wrapper.Unwrap_list;
// MethodName(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j)
unwrapActions.Add(await GetUnwrapAllCodeActionAsync(parentTitle, WrappingStyle.UnwrapFirst_IndentRest).ConfigureAwait(false));
// MethodName(
// int a, int b, int c, int d, int e, int f, int g, int h, int i, int j)
unwrapActions.Add(await GetUnwrapAllCodeActionAsync(parentTitle, WrappingStyle.WrapFirst_IndentRest).ConfigureAwait(false));
// The 'unwrap' title strings are unique and do not collide with any other code
// actions we're computing. So they can be inlined if possible.
return new WrappingGroup(isInlinable: true, unwrapActions.ToImmutable());
}
private async Task<WrapItemsAction> GetUnwrapAllCodeActionAsync(string parentTitle, WrappingStyle wrappingStyle)
{
var edits = GetUnwrapAllEdits(wrappingStyle);
var title = wrappingStyle == WrappingStyle.WrapFirst_IndentRest
? Wrapper.Unwrap_and_indent_all_items
: Wrapper.Unwrap_all_items;
return await TryCreateCodeActionAsync(edits, parentTitle, title).ConfigureAwait(false);
}
private ImmutableArray<Edit> GetUnwrapAllEdits(WrappingStyle wrappingStyle)
{
using var _ = ArrayBuilder<Edit>.GetInstance(out var result);
AddTextChangeBetweenOpenAndFirstItem(wrappingStyle, result);
foreach (var comma in _listItems.GetSeparators())
{
result.Add(Edit.DeleteBetween(comma.GetPreviousToken(), comma));
result.Add(Edit.DeleteBetween(comma, comma.GetNextToken()));
}
result.Add(Edit.DeleteBetween(_listItems.Last(), _listSyntax.GetLastToken()));
return result.ToImmutable();
}
#endregion
#region wrap long line
private async Task<WrappingGroup> GetWrapLongGroupAsync()
{
var parentTitle = Wrapper.Wrap_long_list;
using var _ = ArrayBuilder<WrapItemsAction>.GetInstance(out var codeActions);
// MethodName(int a, int b, int c,
// int d, int e, int f,
// int g, int h, int i,
// int j)
codeActions.Add(await GetWrapLongLineCodeActionAsync(
parentTitle, WrappingStyle.UnwrapFirst_AlignRest).ConfigureAwait(false));
// MethodName(
// int a, int b, int c, int d, int e,
// int f, int g, int h, int i, int j)
codeActions.Add(await GetWrapLongLineCodeActionAsync(
parentTitle, WrappingStyle.WrapFirst_IndentRest).ConfigureAwait(false));
// MethodName(int a, int b, int c,
// int d, int e, int f, int g,
// int h, int i, int j)
codeActions.Add(await GetWrapLongLineCodeActionAsync(
parentTitle, WrappingStyle.UnwrapFirst_IndentRest).ConfigureAwait(false));
// The wrap-all and wrap-long code action titles are not unique. i.e. we show them
// as:
// Wrap every parameter:
// Align parameters
// Indent wrapped parameters
// Wrap long parameter list:
// Align parameters
// Indent wrapped parameters
//
// We can't in-line these nested actions because the parent title is necessary to
// determine which situation each child action applies to.
return new WrappingGroup(isInlinable: false, codeActions.ToImmutable());
}
private async Task<WrapItemsAction> GetWrapLongLineCodeActionAsync(
string parentTitle, WrappingStyle wrappingStyle)
{
var indentationTrivia = GetIndentationTrivia(wrappingStyle);
var edits = GetWrapLongLinesEdits(wrappingStyle, indentationTrivia);
var title = GetNestedCodeActionTitle(wrappingStyle);
return await TryCreateCodeActionAsync(edits, parentTitle, title).ConfigureAwait(false);
}
private ImmutableArray<Edit> GetWrapLongLinesEdits(
WrappingStyle wrappingStyle, SyntaxTrivia indentationTrivia)
{
using var _ = ArrayBuilder<Edit>.GetInstance(out var result);
AddTextChangeBetweenOpenAndFirstItem(wrappingStyle, result);
var currentOffset = wrappingStyle == WrappingStyle.WrapFirst_IndentRest
? indentationTrivia.FullWidth()
: _afterOpenTokenIndentationTrivia.FullWidth();
var itemsAndSeparators = _listItems.GetWithSeparators();
for (var i = 0; i < itemsAndSeparators.Count; i += 2)
{
var item = itemsAndSeparators[i].AsNode();
// Figure out where we'd be after this item.
currentOffset += item.Span.Length;
if (i > 0)
{
if (currentOffset < WrappingColumn)
{
// this item would not make us go pass our preferred wrapping column. So
// keep it on this line, making sure there's a space between the previous
// comma and us.
result.Add(Edit.UpdateBetween(itemsAndSeparators[i - 1], SingleWhitespaceTrivia, NoTrivia, item));
currentOffset += " ".Length;
}
else
{
// not the first item on the line and this item makes us go past the wrapping
// limit. We want to wrap before this item.
result.Add(Edit.UpdateBetween(itemsAndSeparators[i - 1], NewLineTrivia, indentationTrivia, item));
currentOffset = indentationTrivia.FullWidth() + item.Span.Length;
}
}
// Get rid of any spaces between the list item and the following token (a
// comma or close token).
var nextToken = item.GetLastToken().GetNextToken();
result.Add(Edit.DeleteBetween(item, nextToken));
currentOffset += nextToken.Span.Length;
}
return result.ToImmutable();
}
#endregion
#region wrap every
private async Task<WrappingGroup> GetWrapEveryGroupAsync()
{
var parentTitle = Wrapper.Wrap_every_item;
using var _ = ArrayBuilder<WrapItemsAction>.GetInstance(out var codeActions);
// MethodName(int a,
// int b,
// ...
// int j);
codeActions.Add(await GetWrapEveryNestedCodeActionAsync(
parentTitle, WrappingStyle.UnwrapFirst_AlignRest).ConfigureAwait(false));
// MethodName(
// int a,
// int b,
// ...
// int j)
codeActions.Add(await GetWrapEveryNestedCodeActionAsync(
parentTitle, WrappingStyle.WrapFirst_IndentRest).ConfigureAwait(false));
// MethodName(int a,
// int b,
// ...
// int j)
codeActions.Add(await GetWrapEveryNestedCodeActionAsync(
parentTitle, WrappingStyle.UnwrapFirst_IndentRest).ConfigureAwait(false));
// See comment in GetWrapLongTopLevelCodeActionAsync for explanation of why we're
// not inlinable.
return new WrappingGroup(isInlinable: false, codeActions.ToImmutable());
}
private async Task<WrapItemsAction> GetWrapEveryNestedCodeActionAsync(
string parentTitle, WrappingStyle wrappingStyle)
{
var indentationTrivia = GetIndentationTrivia(wrappingStyle);
var edits = GetWrapEachEdits(wrappingStyle, indentationTrivia);
var title = GetNestedCodeActionTitle(wrappingStyle);
return await TryCreateCodeActionAsync(edits, parentTitle, title).ConfigureAwait(false);
}
private string GetNestedCodeActionTitle(WrappingStyle wrappingStyle)
=> wrappingStyle switch
{
WrappingStyle.WrapFirst_IndentRest => Wrapper.Indent_all_items,
WrappingStyle.UnwrapFirst_AlignRest => Wrapper.Align_wrapped_items,
WrappingStyle.UnwrapFirst_IndentRest => Wrapper.Indent_wrapped_items,
_ => throw ExceptionUtilities.UnexpectedValue(wrappingStyle),
};
private ImmutableArray<Edit> GetWrapEachEdits(
WrappingStyle wrappingStyle, SyntaxTrivia indentationTrivia)
{
using var _ = ArrayBuilder<Edit>.GetInstance(out var result);
AddTextChangeBetweenOpenAndFirstItem(wrappingStyle, result);
var itemsAndSeparators = _listItems.GetWithSeparators();
for (var i = 0; i < itemsAndSeparators.Count; i += 2)
{
var item = itemsAndSeparators[i].AsNode();
if (i < itemsAndSeparators.Count - 1)
{
// intermediary item
var comma = itemsAndSeparators[i + 1].AsToken();
result.Add(Edit.DeleteBetween(item, comma));
// Always wrap between this comma and the next item.
result.Add(Edit.UpdateBetween(
comma, NewLineTrivia, indentationTrivia, itemsAndSeparators[i + 2]));
}
}
// last item. Delete whatever is between it and the close token of the list.
result.Add(Edit.DeleteBetween(_listItems.Last(), _listSyntax.GetLastToken()));
return result.ToImmutable();
}
#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.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Wrapping.SeparatedSyntaxList
{
internal abstract partial class AbstractSeparatedSyntaxListWrapper<TListSyntax, TListItemSyntax>
{
/// <summary>
/// Class responsible for actually computing the entire set of code actions to offer the user.
/// </summary>
private class SeparatedSyntaxListCodeActionComputer : AbstractCodeActionComputer<AbstractSeparatedSyntaxListWrapper<TListSyntax, TListItemSyntax>>
{
private readonly TListSyntax _listSyntax;
private readonly SeparatedSyntaxList<TListItemSyntax> _listItems;
/// <summary>
/// The indentation string necessary to indent an item in a list such that the start of
/// that item will exact start at the end of the open-token for the containing list. i.e.
///
/// void Goobar(
/// ^
/// |
///
/// This is the indentation we want when we're aligning wrapped items with the first item
/// in the list.
/// </summary>
private readonly SyntaxTrivia _afterOpenTokenIndentationTrivia;
/// <summary>
/// Indentation amount for any items that have been wrapped to a new line. Valid if we're
/// not aligning with the first item. i.e.
///
/// void Goobar(
/// ^
/// |
/// </summary>
private readonly SyntaxTrivia _singleIndentationTrivia;
public SeparatedSyntaxListCodeActionComputer(
AbstractSeparatedSyntaxListWrapper<TListSyntax, TListItemSyntax> service,
Document document, SourceText sourceText, DocumentOptionSet options,
TListSyntax listSyntax, SeparatedSyntaxList<TListItemSyntax> listItems,
CancellationToken cancellationToken)
: base(service, document, sourceText, options, cancellationToken)
{
_listSyntax = listSyntax;
_listItems = listItems;
var generator = SyntaxGenerator.GetGenerator(OriginalDocument);
_afterOpenTokenIndentationTrivia = generator.Whitespace(GetAfterOpenTokenIdentation());
_singleIndentationTrivia = generator.Whitespace(GetSingleIdentation());
}
private void AddTextChangeBetweenOpenAndFirstItem(
WrappingStyle wrappingStyle, ArrayBuilder<Edit> result)
{
result.Add(wrappingStyle == WrappingStyle.WrapFirst_IndentRest
? Edit.UpdateBetween(_listSyntax.GetFirstToken(), NewLineTrivia, _singleIndentationTrivia, _listItems[0])
: Edit.DeleteBetween(_listSyntax.GetFirstToken(), _listItems[0]));
}
private string GetAfterOpenTokenIdentation()
{
var openToken = _listSyntax.GetFirstToken();
var afterOpenTokenOffset = OriginalSourceText.GetOffset(openToken.Span.End);
var indentString = afterOpenTokenOffset.CreateIndentationString(UseTabs, TabSize);
return indentString;
}
private string GetSingleIdentation()
{
// Insert a newline after the open token of the list. Then ask the
// ISynchronousIndentationService where it thinks that the next line should be
// indented.
var openToken = _listSyntax.GetFirstToken();
return GetSmartIndentationAfter(openToken);
}
private SyntaxTrivia GetIndentationTrivia(WrappingStyle wrappingStyle)
{
return wrappingStyle == WrappingStyle.UnwrapFirst_AlignRest
? _afterOpenTokenIndentationTrivia
: _singleIndentationTrivia;
}
protected override async Task<ImmutableArray<WrappingGroup>> ComputeWrappingGroupsAsync()
{
using var _ = ArrayBuilder<WrappingGroup>.GetInstance(out var result);
await AddWrappingGroupsAsync(result).ConfigureAwait(false);
return result.ToImmutable();
}
private async Task AddWrappingGroupsAsync(ArrayBuilder<WrappingGroup> result)
{
result.Add(await GetWrapEveryGroupAsync().ConfigureAwait(false));
result.Add(await GetUnwrapGroupAsync().ConfigureAwait(false));
result.Add(await GetWrapLongGroupAsync().ConfigureAwait(false));
}
#region unwrap group
private async Task<WrappingGroup> GetUnwrapGroupAsync()
{
using var _ = ArrayBuilder<WrapItemsAction>.GetInstance(out var unwrapActions);
var parentTitle = Wrapper.Unwrap_list;
// MethodName(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j)
unwrapActions.Add(await GetUnwrapAllCodeActionAsync(parentTitle, WrappingStyle.UnwrapFirst_IndentRest).ConfigureAwait(false));
// MethodName(
// int a, int b, int c, int d, int e, int f, int g, int h, int i, int j)
unwrapActions.Add(await GetUnwrapAllCodeActionAsync(parentTitle, WrappingStyle.WrapFirst_IndentRest).ConfigureAwait(false));
// The 'unwrap' title strings are unique and do not collide with any other code
// actions we're computing. So they can be inlined if possible.
return new WrappingGroup(isInlinable: true, unwrapActions.ToImmutable());
}
private async Task<WrapItemsAction> GetUnwrapAllCodeActionAsync(string parentTitle, WrappingStyle wrappingStyle)
{
var edits = GetUnwrapAllEdits(wrappingStyle);
var title = wrappingStyle == WrappingStyle.WrapFirst_IndentRest
? Wrapper.Unwrap_and_indent_all_items
: Wrapper.Unwrap_all_items;
return await TryCreateCodeActionAsync(edits, parentTitle, title).ConfigureAwait(false);
}
private ImmutableArray<Edit> GetUnwrapAllEdits(WrappingStyle wrappingStyle)
{
using var _ = ArrayBuilder<Edit>.GetInstance(out var result);
AddTextChangeBetweenOpenAndFirstItem(wrappingStyle, result);
foreach (var comma in _listItems.GetSeparators())
{
result.Add(Edit.DeleteBetween(comma.GetPreviousToken(), comma));
result.Add(Edit.DeleteBetween(comma, comma.GetNextToken()));
}
result.Add(Edit.DeleteBetween(_listItems.Last(), _listSyntax.GetLastToken()));
return result.ToImmutable();
}
#endregion
#region wrap long line
private async Task<WrappingGroup> GetWrapLongGroupAsync()
{
var parentTitle = Wrapper.Wrap_long_list;
using var _ = ArrayBuilder<WrapItemsAction>.GetInstance(out var codeActions);
// MethodName(int a, int b, int c,
// int d, int e, int f,
// int g, int h, int i,
// int j)
codeActions.Add(await GetWrapLongLineCodeActionAsync(
parentTitle, WrappingStyle.UnwrapFirst_AlignRest).ConfigureAwait(false));
// MethodName(
// int a, int b, int c, int d, int e,
// int f, int g, int h, int i, int j)
codeActions.Add(await GetWrapLongLineCodeActionAsync(
parentTitle, WrappingStyle.WrapFirst_IndentRest).ConfigureAwait(false));
// MethodName(int a, int b, int c,
// int d, int e, int f, int g,
// int h, int i, int j)
codeActions.Add(await GetWrapLongLineCodeActionAsync(
parentTitle, WrappingStyle.UnwrapFirst_IndentRest).ConfigureAwait(false));
// The wrap-all and wrap-long code action titles are not unique. i.e. we show them
// as:
// Wrap every parameter:
// Align parameters
// Indent wrapped parameters
// Wrap long parameter list:
// Align parameters
// Indent wrapped parameters
//
// We can't in-line these nested actions because the parent title is necessary to
// determine which situation each child action applies to.
return new WrappingGroup(isInlinable: false, codeActions.ToImmutable());
}
private async Task<WrapItemsAction> GetWrapLongLineCodeActionAsync(
string parentTitle, WrappingStyle wrappingStyle)
{
var indentationTrivia = GetIndentationTrivia(wrappingStyle);
var edits = GetWrapLongLinesEdits(wrappingStyle, indentationTrivia);
var title = GetNestedCodeActionTitle(wrappingStyle);
return await TryCreateCodeActionAsync(edits, parentTitle, title).ConfigureAwait(false);
}
private ImmutableArray<Edit> GetWrapLongLinesEdits(
WrappingStyle wrappingStyle, SyntaxTrivia indentationTrivia)
{
using var _ = ArrayBuilder<Edit>.GetInstance(out var result);
AddTextChangeBetweenOpenAndFirstItem(wrappingStyle, result);
var currentOffset = wrappingStyle == WrappingStyle.WrapFirst_IndentRest
? indentationTrivia.FullWidth()
: _afterOpenTokenIndentationTrivia.FullWidth();
var itemsAndSeparators = _listItems.GetWithSeparators();
for (var i = 0; i < itemsAndSeparators.Count; i += 2)
{
var item = itemsAndSeparators[i].AsNode();
// Figure out where we'd be after this item.
currentOffset += item.Span.Length;
if (i > 0)
{
if (currentOffset < WrappingColumn)
{
// this item would not make us go pass our preferred wrapping column. So
// keep it on this line, making sure there's a space between the previous
// comma and us.
result.Add(Edit.UpdateBetween(itemsAndSeparators[i - 1], SingleWhitespaceTrivia, NoTrivia, item));
currentOffset += " ".Length;
}
else
{
// not the first item on the line and this item makes us go past the wrapping
// limit. We want to wrap before this item.
result.Add(Edit.UpdateBetween(itemsAndSeparators[i - 1], NewLineTrivia, indentationTrivia, item));
currentOffset = indentationTrivia.FullWidth() + item.Span.Length;
}
}
// Get rid of any spaces between the list item and the following token (a
// comma or close token).
var nextToken = item.GetLastToken().GetNextToken();
result.Add(Edit.DeleteBetween(item, nextToken));
currentOffset += nextToken.Span.Length;
}
return result.ToImmutable();
}
#endregion
#region wrap every
private async Task<WrappingGroup> GetWrapEveryGroupAsync()
{
var parentTitle = Wrapper.Wrap_every_item;
using var _ = ArrayBuilder<WrapItemsAction>.GetInstance(out var codeActions);
// MethodName(int a,
// int b,
// ...
// int j);
codeActions.Add(await GetWrapEveryNestedCodeActionAsync(
parentTitle, WrappingStyle.UnwrapFirst_AlignRest).ConfigureAwait(false));
// MethodName(
// int a,
// int b,
// ...
// int j)
codeActions.Add(await GetWrapEveryNestedCodeActionAsync(
parentTitle, WrappingStyle.WrapFirst_IndentRest).ConfigureAwait(false));
// MethodName(int a,
// int b,
// ...
// int j)
codeActions.Add(await GetWrapEveryNestedCodeActionAsync(
parentTitle, WrappingStyle.UnwrapFirst_IndentRest).ConfigureAwait(false));
// See comment in GetWrapLongTopLevelCodeActionAsync for explanation of why we're
// not inlinable.
return new WrappingGroup(isInlinable: false, codeActions.ToImmutable());
}
private async Task<WrapItemsAction> GetWrapEveryNestedCodeActionAsync(
string parentTitle, WrappingStyle wrappingStyle)
{
var indentationTrivia = GetIndentationTrivia(wrappingStyle);
var edits = GetWrapEachEdits(wrappingStyle, indentationTrivia);
var title = GetNestedCodeActionTitle(wrappingStyle);
return await TryCreateCodeActionAsync(edits, parentTitle, title).ConfigureAwait(false);
}
private string GetNestedCodeActionTitle(WrappingStyle wrappingStyle)
=> wrappingStyle switch
{
WrappingStyle.WrapFirst_IndentRest => Wrapper.Indent_all_items,
WrappingStyle.UnwrapFirst_AlignRest => Wrapper.Align_wrapped_items,
WrappingStyle.UnwrapFirst_IndentRest => Wrapper.Indent_wrapped_items,
_ => throw ExceptionUtilities.UnexpectedValue(wrappingStyle),
};
private ImmutableArray<Edit> GetWrapEachEdits(
WrappingStyle wrappingStyle, SyntaxTrivia indentationTrivia)
{
using var _ = ArrayBuilder<Edit>.GetInstance(out var result);
AddTextChangeBetweenOpenAndFirstItem(wrappingStyle, result);
var itemsAndSeparators = _listItems.GetWithSeparators();
for (var i = 0; i < itemsAndSeparators.Count; i += 2)
{
var item = itemsAndSeparators[i].AsNode();
if (i < itemsAndSeparators.Count - 1)
{
// intermediary item
var comma = itemsAndSeparators[i + 1].AsToken();
result.Add(Edit.DeleteBetween(item, comma));
// Always wrap between this comma and the next item.
result.Add(Edit.UpdateBetween(
comma, NewLineTrivia, indentationTrivia, itemsAndSeparators[i + 2]));
}
}
// last item. Delete whatever is between it and the close token of the list.
result.Add(Edit.DeleteBetween(_listItems.Last(), _listSyntax.GetLastToken()));
return result.ToImmutable();
}
#endregion
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/RecentItemsManager.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion
{
[Export]
internal class RecentItemsManager
{
private const int MaxMRUSize = 10;
/// <summary>
/// Guard for <see cref="RecentItems"/>
/// </summary>
private readonly object _mruUpdateLock = new();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RecentItemsManager()
{
}
public ImmutableArray<string> RecentItems { get; private set; } = ImmutableArray<string>.Empty;
public void MakeMostRecentItem(string item)
{
lock (_mruUpdateLock)
{
var items = RecentItems;
items = items.Remove(item);
if (items.Length == MaxMRUSize)
{
// Remove the least recent item.
items = items.RemoveAt(0);
}
RecentItems = items.Add(item);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion
{
[Export]
internal class RecentItemsManager
{
private const int MaxMRUSize = 10;
/// <summary>
/// Guard for <see cref="RecentItems"/>
/// </summary>
private readonly object _mruUpdateLock = new();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RecentItemsManager()
{
}
public ImmutableArray<string> RecentItems { get; private set; } = ImmutableArray<string>.Empty;
public void MakeMostRecentItem(string item)
{
lock (_mruUpdateLock)
{
var items = RecentItems;
items = items.Remove(item);
if (items.Length == MaxMRUSize)
{
// Remove the least recent item.
items = items.RemoveAt(0);
}
RecentItems = items.Add(item);
}
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxNodeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax;
using System.Text;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class SyntaxNodeTests
{
[Fact]
[WorkItem(565382, "https://developercommunity.visualstudio.com/content/problem/565382/compiling-causes-a-stack-overflow-error.html")]
public void TestLargeFluentCallWithDirective()
{
var builder = new StringBuilder();
builder.AppendLine(
@"
class C {
C M(string x) { return this; }
void M2() {
new C()
#region Region
");
for (int i = 0; i < 20000; i++)
{
builder.AppendLine(@" .M(""test"")");
}
builder.AppendLine(
@" .M(""test"");
#endregion
}
}");
var tree = SyntaxFactory.ParseSyntaxTree(builder.ToString());
var directives = tree.GetRoot().GetDirectives();
Assert.Equal(2, directives.Count);
}
[Fact]
public void TestQualifiedNameSyntaxWith()
{
// this is just a test to prove that at least one generate With method exists and functions correctly. :-)
var qname = (QualifiedNameSyntax)SyntaxFactory.ParseName("A.B");
var qname2 = qname.WithRight(SyntaxFactory.IdentifierName("C"));
var text = qname2.ToString();
Assert.Equal("A.C", text);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TestAddBaseListTypes()
{
var cls = SyntaxFactory.ParseCompilationUnit("class C { }").Members[0] as ClassDeclarationSyntax;
var cls2 = cls.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("B")));
}
[Fact]
public void TestChildNodes()
{
var text = "m(a,b,c)";
var expression = SyntaxFactory.ParseExpression(text);
var nodes = expression.ChildNodes().ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind());
Assert.Equal(SyntaxKind.ArgumentList, nodes[1].Kind());
}
[Fact]
public void TestAncestors()
{
var text = "a + (b - (c * (d / e)))";
var expression = SyntaxFactory.ParseExpression(text);
var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e");
var nodes = e.Ancestors().ToList();
Assert.Equal(7, nodes.Count);
Assert.Equal(SyntaxKind.DivideExpression, nodes[0].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[1].Kind());
Assert.Equal(SyntaxKind.MultiplyExpression, nodes[2].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[3].Kind());
Assert.Equal(SyntaxKind.SubtractExpression, nodes[4].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[5].Kind());
Assert.Equal(SyntaxKind.AddExpression, nodes[6].Kind());
}
[Fact]
public void TestAncestorsAndSelf()
{
var text = "a + (b - (c * (d / e)))";
var expression = SyntaxFactory.ParseExpression(text);
var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e");
var nodes = e.AncestorsAndSelf().ToList();
Assert.Equal(8, nodes.Count);
Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind());
Assert.Equal(SyntaxKind.DivideExpression, nodes[1].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[2].Kind());
Assert.Equal(SyntaxKind.MultiplyExpression, nodes[3].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[4].Kind());
Assert.Equal(SyntaxKind.SubtractExpression, nodes[5].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[6].Kind());
Assert.Equal(SyntaxKind.AddExpression, nodes[7].Kind());
}
[Fact]
public void TestFirstAncestorOrSelf()
{
var text = "a + (b - (c * (d / e)))";
var expression = SyntaxFactory.ParseExpression(text);
var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e");
var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression);
Assert.NotNull(firstParens);
Assert.Equal("(d / e)", firstParens.ToString());
}
[Fact]
public void TestDescendantNodes()
{
var text = "#if true\r\n return true;";
var statement = SyntaxFactory.ParseStatement(text);
var nodes = statement.DescendantNodes().ToList();
Assert.Equal(1, nodes.Count);
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind());
nodes = statement.DescendantNodes(descendIntoTrivia: true).ToList();
Assert.Equal(3, nodes.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
nodes = statement.DescendantNodes(n => n is StatementSyntax).ToList();
Assert.Equal(1, nodes.Count);
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind());
nodes = statement.DescendantNodes(n => n is StatementSyntax, descendIntoTrivia: true).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
// all over again with spans
nodes = statement.DescendantNodes(statement.FullSpan).ToList();
Assert.Equal(1, nodes.Count);
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind());
nodes = statement.DescendantNodes(statement.FullSpan, descendIntoTrivia: true).ToList();
Assert.Equal(3, nodes.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax).ToList();
Assert.Equal(1, nodes.Count);
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind());
nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
}
[Fact]
public void TestDescendantNodesAndSelf()
{
var text = "#if true\r\n return true;";
var statement = SyntaxFactory.ParseStatement(text);
var nodes = statement.DescendantNodesAndSelf().ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
nodes = statement.DescendantNodesAndSelf(descendIntoTrivia: true).ToList();
Assert.Equal(4, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind());
nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax, descendIntoTrivia: true).ToList();
Assert.Equal(3, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
// all over again with spans
nodes = statement.DescendantNodesAndSelf(statement.FullSpan).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
nodes = statement.DescendantNodesAndSelf(statement.FullSpan, descendIntoTrivia: true).ToList();
Assert.Equal(4, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind());
nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList();
Assert.Equal(3, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
}
[Fact]
public void TestDescendantNodesAndTokens()
{
var text = "#if true\r\n return true;";
var statement = SyntaxFactory.ParseStatement(text);
var nodesAndTokens = statement.DescendantNodesAndTokens().ToList();
Assert.Equal(4, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind());
nodesAndTokens = statement.DescendantNodesAndTokens(descendIntoTrivia: true).ToList();
Assert.Equal(10, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[3].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[4].Kind());
Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[5].Kind());
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[6].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[7].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[8].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[9].Kind());
// with span
nodesAndTokens = statement.DescendantNodesAndTokens(statement.FullSpan).ToList();
Assert.Equal(4, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind());
}
[Fact]
public void TestDescendantNodesAndTokensAndSelf()
{
var text = "#if true\r\n return true;";
var statement = SyntaxFactory.ParseStatement(text);
var nodesAndTokens = statement.DescendantNodesAndTokensAndSelf().ToList();
Assert.Equal(5, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind());
nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList();
Assert.Equal(11, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[3].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[4].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[5].Kind());
Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[6].Kind());
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[7].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[8].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[9].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[10].Kind());
// with span
nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(statement.FullSpan).ToList();
Assert.Equal(5, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind());
}
[Fact]
public void TestDescendantNodesAndTokensAndSelfForEmptyCompilationUnit()
{
var text = "";
var cu = SyntaxFactory.ParseCompilationUnit(text);
var nodesAndTokens = cu.DescendantNodesAndTokensAndSelf().ToList();
Assert.Equal(2, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.CompilationUnit, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.EndOfFileToken, nodesAndTokens[1].Kind());
}
[Fact]
public void TestDescendantNodesAndTokensAndSelfForDocumentationComment()
{
var text = "/// Goo\r\n x";
var expr = SyntaxFactory.ParseExpression(text);
var nodesAndTokens = expr.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList();
Assert.Equal(7, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.IdentifierName, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.XmlText, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.XmlTextLiteralToken, nodesAndTokens[3].Kind());
Assert.Equal(SyntaxKind.XmlTextLiteralNewLineToken, nodesAndTokens[4].Kind());
Assert.Equal(SyntaxKind.EndOfDocumentationCommentToken, nodesAndTokens[5].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, nodesAndTokens[6].Kind());
}
[Fact]
public void TestGetAllDirectivesUsingDescendantNodes()
{
var text = "#if false\r\n eat a sandwich\r\n#endif\r\n x";
var expr = SyntaxFactory.ParseExpression(text);
var directives = expr.GetDirectives();
var descendantDirectives = expr.DescendantNodesAndSelf(n => n.ContainsDirectives, descendIntoTrivia: true).OfType<DirectiveTriviaSyntax>().ToList();
Assert.Equal(directives.Count, descendantDirectives.Count);
for (int i = 0; i < directives.Count; i++)
{
Assert.Equal(directives[i], descendantDirectives[i]);
}
}
[Fact]
public void TestGetAllAnnotatedNodesUsingDescendantNodes()
{
var text = "a + (b - (c * (d / e)))";
var expr = SyntaxFactory.ParseExpression(text);
var myAnnotation = new SyntaxAnnotation();
var identifierNodes = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList();
var exprWithAnnotations = expr.ReplaceNodes(identifierNodes, (e, e2) => e2.WithAdditionalAnnotations(myAnnotation));
var nodesWithMyAnnotations = exprWithAnnotations.DescendantNodesAndSelf(n => n.ContainsAnnotations).Where(n => n.HasAnnotation(myAnnotation)).ToList();
Assert.Equal(identifierNodes.Count, nodesWithMyAnnotations.Count);
for (int i = 0; i < identifierNodes.Count; i++)
{
// compare text because node identity changed when adding the annotation
Assert.Equal(identifierNodes[i].ToString(), nodesWithMyAnnotations[i].ToString());
}
}
[Fact]
public void TestDescendantTokens()
{
var s1 = "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList();
Assert.Equal(4, tokens.Count);
Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind());
Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind());
}
[Fact]
public void TestDescendantTokensWithExtraWhitespace()
{
var s1 = " using Goo ; ";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList();
Assert.Equal(4, tokens.Count);
Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind());
Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind());
}
[Fact]
public void TestDescendantTokensEntireRange()
{
var s1 = "extern alias Bar;\r\n" + "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList();
Assert.Equal(8, tokens.Count);
Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[3].Kind());
Assert.Equal(SyntaxKind.UsingKeyword, tokens[4].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[5].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[6].Kind());
Assert.Equal(SyntaxKind.EndOfFileToken, tokens[7].Kind());
}
[Fact]
public void TestDescendantTokensOverFullSpan()
{
var s1 = "extern alias Bar;\r\n" + "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(0, 16)).ToList();
Assert.Equal(3, tokens.Count);
Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind());
}
[Fact]
public void TestDescendantTokensOverInsideSpan()
{
var s1 = "extern alias Bar;\r\n" + "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(1, 14)).ToList();
Assert.Equal(3, tokens.Count);
Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind());
}
[Fact]
public void TestDescendantTokensOverFullSpanOffset()
{
var s1 = "extern alias Bar;\r\n" + "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(7, 17)).ToList();
Assert.Equal(4, tokens.Count);
Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind());
Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind());
}
[Fact]
public void TestDescendantTokensOverInsideSpanOffset()
{
var s1 = "extern alias Bar;\r\n" + "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(8, 15)).ToList();
Assert.Equal(4, tokens.Count);
Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind());
Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind());
}
[Fact]
public void TestDescendantTrivia()
{
var text = "// goo\r\na + b";
var expr = SyntaxFactory.ParseExpression(text);
var list = expr.DescendantTrivia().ToList();
Assert.Equal(4, list.Count);
Assert.Equal(SyntaxKind.SingleLineCommentTrivia, list[0].Kind());
Assert.Equal(SyntaxKind.EndOfLineTrivia, list[1].Kind());
Assert.Equal(SyntaxKind.WhitespaceTrivia, list[2].Kind());
Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind());
}
[Fact]
public void TestDescendantTriviaIntoStructuredTrivia()
{
var text = @"
/// <goo >
/// </goo>
a + b";
var expr = SyntaxFactory.ParseExpression(text);
var list = expr.DescendantTrivia(descendIntoTrivia: true).ToList();
Assert.Equal(7, list.Count);
Assert.Equal(SyntaxKind.EndOfLineTrivia, list[0].Kind());
Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, list[1].Kind());
Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[2].Kind());
Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind());
Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[4].Kind());
Assert.Equal(SyntaxKind.WhitespaceTrivia, list[5].Kind());
Assert.Equal(SyntaxKind.WhitespaceTrivia, list[6].Kind());
}
[Fact]
public void Bug877223()
{
var s1 = "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
// var node = t1.GetCompilationUnitRoot().Usings[0].GetTokens(new TextSpan(6, 3)).First();
var node = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(6, 3)).First();
Assert.Equal("Goo", node.ToString());
}
[Fact]
public void TestFindToken()
{
var text = "class\n #if XX\n#endif\n goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
var token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length);
Assert.Equal(SyntaxKind.IdentifierToken, token.Kind());
Assert.Equal("goo", token.ToString());
token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length, findInsideTrivia: true);
Assert.Equal(SyntaxKind.IfKeyword, token.Kind());
}
[Fact]
public void TestFindTokenInLargeList()
{
var identifier = SyntaxFactory.Identifier("x");
var missingIdentifier = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken);
var name = SyntaxFactory.IdentifierName(identifier);
var missingName = SyntaxFactory.IdentifierName(missingIdentifier);
var comma = SyntaxFactory.Token(SyntaxKind.CommaToken);
var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken);
var argument = SyntaxFactory.Argument(name);
var missingArgument = SyntaxFactory.Argument(missingName);
// make a large list that has lots of zero-length nodes (that shouldn't be found)
var nodesAndTokens = SyntaxFactory.NodeOrTokenList(
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
argument);
var argumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(SyntaxFactory.NodeOrTokenList(nodesAndTokens)));
var invocation = SyntaxFactory.InvocationExpression(name, argumentList);
CheckFindToken(invocation);
}
private void CheckFindToken(SyntaxNode node)
{
for (int i = 0; i < node.FullSpan.End; i++)
{
var token = node.FindToken(i);
Assert.True(token.FullSpan.Contains(i));
}
}
[WorkItem(755236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755236")]
[Fact]
public void TestFindNode()
{
var text = "class\n #if XX\n#endif\n goo { }\n class bar { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
var root = tree.GetRoot();
Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: false));
Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: true));
var classDecl = (TypeDeclarationSyntax)root.ChildNodes().First();
// IdentifierNameSyntax in trivia.
var identifier = root.DescendantNodes(descendIntoTrivia: true).Single(n => n is IdentifierNameSyntax);
var position = identifier.Span.Start + 1;
Assert.Equal(classDecl, root.FindNode(identifier.Span, findInsideTrivia: false));
Assert.Equal(identifier, root.FindNode(identifier.Span, findInsideTrivia: true));
// Token span.
Assert.Equal(classDecl, root.FindNode(classDecl.Identifier.Span, findInsideTrivia: false));
// EOF Token span.
var EOFSpan = new TextSpan(root.FullSpan.End, 0);
Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: false));
Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: true));
// EOF Invalid span for childnode
var classDecl2 = (TypeDeclarationSyntax)root.ChildNodes().Last();
Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(EOFSpan));
// Check end position included in node span
var nodeEndPositionSpan = new TextSpan(classDecl.FullSpan.End, 0);
Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: false));
Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: true));
Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: false));
Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: true));
Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(nodeEndPositionSpan));
// Invalid spans.
var invalidSpan = new TextSpan(100, 100);
Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan));
invalidSpan = new TextSpan(root.FullSpan.End - 1, 2);
Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan));
invalidSpan = new TextSpan(classDecl2.FullSpan.Start - 1, root.FullSpan.End);
Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan));
invalidSpan = new TextSpan(classDecl.FullSpan.End, root.FullSpan.End);
Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan));
// Parent node's span.
Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(root.FullSpan));
}
[WorkItem(539941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539941")]
[Fact]
public void TestFindTriviaNoTriviaExistsAtPosition()
{
var code = @"class Goo
{
void Bar()
{
}
}";
var tree = SyntaxFactory.ParseSyntaxTree(code);
var position = tree.GetText().Lines[2].End - 1;
// position points to the closing parenthesis on the line that has "void Bar()"
// There should be no trivia at this position
var trivia = tree.GetCompilationUnitRoot().FindTrivia(position);
Assert.Equal(SyntaxKind.None, trivia.Kind());
Assert.Equal(0, trivia.SpanStart);
Assert.Equal(0, trivia.Span.End);
Assert.Equal(default(SyntaxTrivia), trivia);
}
[Fact]
public void TestTreeEquivalentToSelf()
{
var text = "class goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.True(tree.GetCompilationUnitRoot().IsEquivalentTo(tree.GetCompilationUnitRoot()));
}
[Fact]
public void TestTreeNotEquivalentToNull()
{
var text = "class goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.False(tree.GetCompilationUnitRoot().IsEquivalentTo(null));
}
[Fact]
public void TestTreesFromSameSourceEquivalent()
{
var text = "class goo { }";
var tree1 = SyntaxFactory.ParseSyntaxTree(text);
var tree2 = SyntaxFactory.ParseSyntaxTree(text);
Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot());
Assert.True(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot()));
}
[Fact]
public void TestDifferentTreesNotEquivalent()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }");
var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { }");
Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot());
Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot()));
}
[Fact]
public void TestVastlyDifferentTreesNotEquivalent()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }");
var tree2 = SyntaxFactory.ParseSyntaxTree(string.Empty);
Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot());
Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot()));
}
[Fact]
public void TestSimilarSubtreesEquivalent()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }");
var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { void M() { } }");
var m1 = ((TypeDeclarationSyntax)tree1.GetCompilationUnitRoot().Members[0]).Members[0];
var m2 = ((TypeDeclarationSyntax)tree2.GetCompilationUnitRoot().Members[0]).Members[0];
Assert.Equal(SyntaxKind.MethodDeclaration, m1.Kind());
Assert.Equal(SyntaxKind.MethodDeclaration, m2.Kind());
Assert.NotEqual(m1, m2);
Assert.True(m1.IsEquivalentTo(m2));
}
[Fact]
public void TestTreesWithDifferentTriviaAreNotEquivalent()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class goo {void M() { }}");
var tree2 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }");
Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot()));
}
[Fact]
public void TestNodeIncrementallyEquivalentToSelf()
{
var text = "class goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.True(tree.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot()));
}
[Fact]
public void TestTokenIncrementallyEquivalentToSelf()
{
var text = "class goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.True(tree.GetCompilationUnitRoot().EndOfFileToken.IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().EndOfFileToken));
}
[Fact]
public void TestDifferentTokensFromSameTreeNotIncrementallyEquivalentToSelf()
{
var text = "class goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.False(tree.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().GetFirstToken().GetNextToken()));
}
[Fact]
public void TestCachedTokensFromDifferentTreesIncrementallyEquivalentToSelf()
{
var text = "class goo { }";
var tree1 = SyntaxFactory.ParseSyntaxTree(text);
var tree2 = SyntaxFactory.ParseSyntaxTree(text);
Assert.True(tree1.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot().GetFirstToken()));
}
[Fact]
public void TestNodesFromSameContentNotIncrementallyParsedNotIncrementallyEquivalent()
{
var text = "class goo { }";
var tree1 = SyntaxFactory.ParseSyntaxTree(text);
var tree2 = SyntaxFactory.ParseSyntaxTree(text);
Assert.False(tree1.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot()));
}
[Fact]
public void TestNodesFromIncrementalParseIncrementallyEquivalent1()
{
var text = "class goo { void M() { } }";
var tree1 = SyntaxFactory.ParseSyntaxTree(text);
var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(default, " ")));
Assert.True(
tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo(
tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single()));
}
[Fact]
public void TestNodesFromIncrementalParseNotIncrementallyEquivalent1()
{
var text = "class goo { void M() { } }";
var tree1 = SyntaxFactory.ParseSyntaxTree(text);
var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(new TextSpan(22, 0), " return; ")));
Assert.False(
tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo(
tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single()));
}
[Fact, WorkItem(536664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536664")]
public void TestTriviaNodeCached()
{
var tree = SyntaxFactory.ParseSyntaxTree(" class goo {}");
// get to the trivia node
var trivia = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0];
// we get the trivia again
var triviaAgain = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0];
// should NOT return two distinct objects for trivia and triviaAgain - struct now.
Assert.True(SyntaxTrivia.Equals(trivia, triviaAgain));
}
[Fact]
public void TestGetFirstToken()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var first = tree.GetCompilationUnitRoot().GetFirstToken();
Assert.Equal(SyntaxKind.PublicKeyword, first.Kind());
}
[Fact]
public void TestGetFirstTokenIncludingZeroWidth()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var first = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true);
Assert.Equal(SyntaxKind.PublicKeyword, first.Kind());
}
[Fact]
public void TestGetLastToken()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var last = tree.GetCompilationUnitRoot().GetLastToken();
Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind());
}
[Fact]
public void TestGetLastTokenIncludingZeroWidth()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { ");
var last = tree.GetCompilationUnitRoot().GetLastToken(includeZeroWidth: true);
Assert.Equal(SyntaxKind.EndOfFileToken, last.Kind());
last = tree.GetCompilationUnitRoot().Members[0].GetLastToken(includeZeroWidth: true);
Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind());
Assert.True(last.IsMissing);
Assert.Equal(26, last.FullSpan.Start);
}
[Fact]
public void TestReverseChildSyntaxList()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class A {} public class B {} public static class C {}");
var root1 = tree1.GetCompilationUnitRoot();
TestReverse(root1.ChildNodesAndTokens());
TestReverse(root1.Members[0].ChildNodesAndTokens());
TestReverse(root1.Members[1].ChildNodesAndTokens());
TestReverse(root1.Members[2].ChildNodesAndTokens());
}
private void TestReverse(ChildSyntaxList children)
{
var list1 = children.AsEnumerable().Reverse().ToList();
var list2 = children.Reverse().ToList();
Assert.Equal(list1.Count, list2.Count);
for (int i = 0; i < list1.Count; i++)
{
Assert.Equal(list1[i], list2[i]);
Assert.Equal(list1[i].FullSpan.Start, list2[i].FullSpan.Start);
}
}
[Fact]
public void TestGetNextToken()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
var list = new List<SyntaxToken>();
var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetNextToken(includeSkipped: true);
}
// descendant tokens include EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetNextTokenIncludingSkippedTokens()
{
var text =
@"garbage
using goo.bar;
";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString());
var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList();
Assert.Equal(6, tokens.Count);
Assert.Equal("garbage", tokens[0].Text);
var list = new List<SyntaxToken>(tokens.Count);
var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetNextToken(includeSkipped: true);
}
Assert.Equal(tokens.Count, list.Count);
for (int i = 0; i < tokens.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetNextTokenExcludingSkippedTokens()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"garbage
using goo.bar;
");
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
Assert.Equal(6, tokens.Count);
var list = new List<SyntaxToken>(tokens.Count);
var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: false);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetNextToken(includeSkipped: false);
}
// descendant tokens includes EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetNextTokenCommon()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList();
List<SyntaxToken> list = new List<SyntaxToken>();
SyntaxToken token = syntaxTree.GetRoot().GetFirstToken();
while (token.RawKind != 0)
{
list.Add(token);
token = token.GetNextToken();
}
// descendant tokens includes EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetPreviousToken()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
var list = new List<SyntaxToken>();
var token = tree.GetCompilationUnitRoot().GetLastToken(); // skip EOF
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetPreviousToken();
}
list.Reverse();
// descendant tokens includes EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetPreviousTokenIncludingSkippedTokens()
{
var text =
@"garbage
using goo.bar;
";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString());
var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList();
Assert.Equal(6, tokens.Count);
Assert.Equal("garbage", tokens[0].Text);
var list = new List<SyntaxToken>(tokens.Count);
var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: true);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetPreviousToken(includeSkipped: true);
}
list.Reverse();
Assert.Equal(tokens.Count, list.Count);
for (int i = 0; i < tokens.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetPreviousTokenExcludingSkippedTokens()
{
var text =
@"garbage
using goo.bar;
";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString());
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
Assert.Equal(6, tokens.Count);
var list = new List<SyntaxToken>(tokens.Count);
var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: false);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetPreviousToken(includeSkipped: false);
}
list.Reverse();
// descendant tokens includes EOF
Assert.Equal(tokens.Count, list.Count + 1);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(tokens[i], list[i]);
}
}
[Fact]
public void TestGetPreviousTokenCommon()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList();
List<SyntaxToken> list = new List<SyntaxToken>();
var token = syntaxTree.GetRoot().GetLastToken(includeZeroWidth: false); // skip EOF
while (token.RawKind != 0)
{
list.Add(token);
token = token.GetPreviousToken();
}
list.Reverse();
// descendant tokens include EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetNextTokenIncludingZeroWidth()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {");
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
var list = new List<SyntaxToken>();
var token = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetNextToken(includeZeroWidth: true);
}
Assert.Equal(tokens.Count, list.Count);
for (int i = 0; i < tokens.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetNextTokenIncludingZeroWidthCommon()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {");
List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList();
List<SyntaxToken> list = new List<SyntaxToken>();
SyntaxToken token = syntaxTree.GetRoot().GetFirstToken(includeZeroWidth: true);
while (token.RawKind != 0)
{
list.Add(token);
token = token.GetNextToken(includeZeroWidth: true);
}
Assert.Equal(tokens.Count, list.Count);
for (int i = 0; i < tokens.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetPreviousTokenIncludingZeroWidth()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {");
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
var list = new List<SyntaxToken>();
var token = tree.GetCompilationUnitRoot().EndOfFileToken.GetPreviousToken(includeZeroWidth: true);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetPreviousToken(includeZeroWidth: true);
}
list.Reverse();
// descendant tokens include EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetPreviousTokenIncludingZeroWidthCommon()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {");
List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList();
List<SyntaxToken> list = new List<SyntaxToken>();
SyntaxToken token = ((SyntaxToken)((SyntaxTree)syntaxTree).GetCompilationUnitRoot().EndOfFileToken).GetPreviousToken(includeZeroWidth: true);
while (token.RawKind != 0)
{
list.Add(token);
token = token.GetPreviousToken(includeZeroWidth: true);
}
list.Reverse();
// descendant tokens includes EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(tokens[i], list[i]);
}
}
[Fact]
public void TestGetNextSibling()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList();
var list = new List<SyntaxNodeOrToken>();
for (var child = children[0]; child.Kind() != SyntaxKind.None; child = child.GetNextSibling())
{
list.Add(child);
}
Assert.Equal(children.Count, list.Count);
for (int i = 0; i < children.Count; i++)
{
Assert.Equal(list[i], children[i]);
}
}
[Fact]
public void TestGetPreviousSibling()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList();
var reversed = children.AsEnumerable().Reverse().ToList();
var list = new List<SyntaxNodeOrToken>();
for (var child = children[children.Count - 1]; child.Kind() != SyntaxKind.None; child = child.GetPreviousSibling())
{
list.Add(child);
}
Assert.Equal(children.Count, list.Count);
for (int i = 0; i < reversed.Count; i++)
{
Assert.Equal(list[i], reversed[i]);
}
}
[Fact]
public void TestSyntaxNodeOrTokenEquality()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var child = tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0];
var member = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0];
Assert.Equal((SyntaxNodeOrToken)member, child);
var name = member.Identifier;
var nameChild = member.ChildNodesAndTokens()[3];
Assert.Equal((SyntaxNodeOrToken)name, nameChild);
var closeBraceToken = member.CloseBraceToken;
var closeBraceChild = member.GetLastToken();
Assert.Equal((SyntaxNodeOrToken)closeBraceToken, closeBraceChild);
}
[Fact]
public void TestStructuredTriviaHasNoParent()
{
var tree = SyntaxFactory.ParseSyntaxTree("#define GOO");
var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0];
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind());
Assert.True(trivia.HasStructure);
Assert.NotNull(trivia.GetStructure());
Assert.Null(trivia.GetStructure().Parent);
}
[Fact]
public void TestStructuredTriviaHasParentTrivia()
{
var tree = SyntaxFactory.ParseSyntaxTree("#define GOO");
var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0];
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind());
Assert.True(trivia.HasStructure);
Assert.NotNull(trivia.GetStructure());
var parentTrivia = trivia.GetStructure().ParentTrivia;
Assert.NotEqual(SyntaxKind.None, parentTrivia.Kind());
Assert.Equal(trivia, parentTrivia);
}
[Fact]
public void TestStructuredTriviaParentTrivia()
{
var def = SyntaxFactory.DefineDirectiveTrivia(SyntaxFactory.Identifier("GOO"), false);
// unrooted structured trivia should report parent trivia as default
Assert.Equal(default(SyntaxTrivia), def.ParentTrivia);
var trivia = SyntaxFactory.Trivia(def);
var structure = trivia.GetStructure();
Assert.NotEqual(def, structure); // these should not be identity equals
Assert.True(def.IsEquivalentTo(structure)); // they should be equivalent though
Assert.Equal(trivia, structure.ParentTrivia); // parent trivia should be equal to original trivia
// attach trivia to token and walk down to structured trivia and back up again
var token = SyntaxFactory.Identifier(default(SyntaxTriviaList), "x", SyntaxTriviaList.Create(trivia));
var tokenTrivia = token.TrailingTrivia[0];
var tokenStructuredTrivia = tokenTrivia.GetStructure();
var tokenStructuredParentTrivia = tokenStructuredTrivia.ParentTrivia;
Assert.Equal(tokenTrivia, tokenStructuredParentTrivia);
Assert.Equal(token, tokenStructuredParentTrivia.Token);
}
[Fact]
public void TestGetFirstDirective()
{
var tree = SyntaxFactory.ParseSyntaxTree("#define GOO");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind());
}
[Fact]
public void TestGetLastDirective()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#undef GOO
");
var d = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.UndefDirectiveTrivia, d.Kind());
}
[Fact]
public void TestGetNextDirective()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#define BAR
class C {
#if GOO
void M() { }
#endif
}
");
var d1 = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d1);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d1.Kind());
var d2 = d1.GetNextDirective();
Assert.NotNull(d2);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d2.Kind());
var d3 = d2.GetNextDirective();
Assert.NotNull(d3);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d3.Kind());
var d4 = d3.GetNextDirective();
Assert.NotNull(d4);
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d4.Kind());
var d5 = d4.GetNextDirective();
Assert.Null(d5);
}
[Fact]
public void TestGetPreviousDirective()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#define BAR
class C {
#if GOO
void M() { }
#endif
}
");
var d1 = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d1);
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d1.Kind());
var d2 = d1.GetPreviousDirective();
Assert.NotNull(d2);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d2.Kind());
var d3 = d2.GetPreviousDirective();
Assert.NotNull(d3);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d3.Kind());
var d4 = d3.GetPreviousDirective();
Assert.NotNull(d4);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d4.Kind());
var d5 = d4.GetPreviousDirective();
Assert.Null(d5);
}
[Fact]
public void TestGetDirectivesRelatedToIf()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind());
d = d.GetNextDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToIfElements()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind());
d = d.GetNextDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
// get directives related to elif
var related2 = related[1].GetRelatedDirectives();
Assert.True(related.SequenceEqual(related2));
// get directives related to else
var related3 = related[3].GetRelatedDirectives();
Assert.True(related.SequenceEqual(related3));
}
[Fact]
public void TestGetDirectivesRelatedToEndIf()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToIfWithNestedIfEndIF()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#if ZED
class A1 { }
#endif
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind());
d = d.GetNextDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToIfWithNestedRegionEndRegion()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#region some region
class A1 { }
#endregion
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind());
d = d.GetNextDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToEndIfWithNestedIfEndIf()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#if ZED
class A1 { }
#endif
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToEndIfWithNestedRegionEndRegion()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
#region some region
class A { }
#endregion
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToRegion()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#region Some Region
class A { }
#endregion
#if GOO
#endif
");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.RegionDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(2, related.Count);
Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToEndRegion()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"
#if GOO
#endif
#region Some Region
class A { }
#endregion
");
var d = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(2, related.Count);
Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind());
}
[WorkItem(536995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536995")]
[Fact]
public void TestTextAndSpanWithTrivia1()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"/*START*/namespace Microsoft.CSharp.Test
{
}/*END*/");
var rootNode = tree.GetCompilationUnitRoot();
Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length);
Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length);
Assert.True(rootNode.ToString().Contains("/*END*/"));
Assert.False(rootNode.ToString().Contains("/*START*/"));
}
[WorkItem(536996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536996")]
[Fact]
public void TestTextAndSpanWithTrivia2()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"/*START*/
namespace Microsoft.CSharp.Test
{
}
/*END*/");
var rootNode = tree.GetCompilationUnitRoot();
Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length);
Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length);
Assert.True(rootNode.ToString().Contains("/*END*/"));
Assert.False(rootNode.ToString().Contains("/*START*/"));
}
[Fact]
public void TestCreateCommonSyntaxNode()
{
var rootNode = SyntaxFactory.ParseSyntaxTree("using X; namespace Y { }").GetCompilationUnitRoot();
var namespaceNode = rootNode.ChildNodesAndTokens()[1].AsNode();
var nodeOrToken = (SyntaxNodeOrToken)namespaceNode;
Assert.True(nodeOrToken.IsNode);
Assert.Equal(namespaceNode, nodeOrToken.AsNode());
Assert.Equal(rootNode, nodeOrToken.Parent);
Assert.Equal(namespaceNode.FullSpan, nodeOrToken.FullSpan);
Assert.Equal(namespaceNode.Span, nodeOrToken.Span);
}
[Fact, WorkItem(537070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537070")]
public void TestTraversalUsingCommonSyntaxNodeOrToken()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(@"class c1
{
}");
var nodeOrToken = (SyntaxNodeOrToken)syntaxTree.GetRoot();
Assert.Equal(0, syntaxTree.GetDiagnostics().Count());
Action<SyntaxNodeOrToken> walk = null;
walk = (SyntaxNodeOrToken nOrT) =>
{
Assert.Equal(0, syntaxTree.GetDiagnostics(nOrT).Count());
foreach (var child in nOrT.ChildNodesAndTokens())
{
walk(child);
}
};
walk(nodeOrToken);
}
[WorkItem(537747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537747")]
[Fact]
public void SyntaxTriviaDefaultIsDirective()
{
SyntaxTrivia trivia = new SyntaxTrivia();
Assert.False(trivia.IsDirective);
}
[Fact]
public void SyntaxNames()
{
var cc = SyntaxFactory.Token(SyntaxKind.ColonColonToken);
var lt = SyntaxFactory.Token(SyntaxKind.LessThanToken);
var gt = SyntaxFactory.Token(SyntaxKind.GreaterThanToken);
var dot = SyntaxFactory.Token(SyntaxKind.DotToken);
var gp = SyntaxFactory.SingletonSeparatedList<TypeSyntax>(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)));
var externAlias = SyntaxFactory.IdentifierName("alias");
var goo = SyntaxFactory.IdentifierName("Goo");
var bar = SyntaxFactory.IdentifierName("Bar");
// Goo.Bar
var qualified = SyntaxFactory.QualifiedName(goo, dot, bar);
Assert.Equal("Goo.Bar", qualified.ToString());
Assert.Equal("Bar", qualified.GetUnqualifiedName().Identifier.ValueText);
// Bar<int>
var generic = SyntaxFactory.GenericName(bar.Identifier, SyntaxFactory.TypeArgumentList(lt, gp, gt));
Assert.Equal("Bar<int>", generic.ToString());
Assert.Equal("Bar", generic.GetUnqualifiedName().Identifier.ValueText);
// Goo.Bar<int>
var qualifiedGeneric = SyntaxFactory.QualifiedName(goo, dot, generic);
Assert.Equal("Goo.Bar<int>", qualifiedGeneric.ToString());
Assert.Equal("Bar", qualifiedGeneric.GetUnqualifiedName().Identifier.ValueText);
// alias::Goo
var alias = SyntaxFactory.AliasQualifiedName(externAlias, cc, goo);
Assert.Equal("alias::Goo", alias.ToString());
Assert.Equal("Goo", alias.GetUnqualifiedName().Identifier.ValueText);
// alias::Bar<int>
var aliasGeneric = SyntaxFactory.AliasQualifiedName(externAlias, cc, generic);
Assert.Equal("alias::Bar<int>", aliasGeneric.ToString());
Assert.Equal("Bar", aliasGeneric.GetUnqualifiedName().Identifier.ValueText);
// alias::Goo.Bar
var aliasQualified = SyntaxFactory.QualifiedName(alias, dot, bar);
Assert.Equal("alias::Goo.Bar", aliasQualified.ToString());
Assert.Equal("Bar", aliasQualified.GetUnqualifiedName().Identifier.ValueText);
// alias::Goo.Bar<int>
var aliasQualifiedGeneric = SyntaxFactory.QualifiedName(alias, dot, generic);
Assert.Equal("alias::Goo.Bar<int>", aliasQualifiedGeneric.ToString());
Assert.Equal("Bar", aliasQualifiedGeneric.GetUnqualifiedName().Identifier.ValueText);
}
[Fact]
public void ZeroWidthTokensInListAreUnique()
{
var someToken = SyntaxFactory.MissingToken(SyntaxKind.IntKeyword);
var list = SyntaxFactory.TokenList(someToken, someToken);
Assert.Equal(someToken, someToken);
Assert.NotEqual(list[0], list[1]);
}
[Fact]
public void ZeroWidthTokensInParentAreUnique()
{
var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken);
var omittedArraySize = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken));
var spec = SyntaxFactory.ArrayRankSpecifier(
SyntaxFactory.Token(SyntaxKind.OpenBracketToken),
SyntaxFactory.SeparatedList<ExpressionSyntax>(new SyntaxNodeOrToken[] { omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize }),
SyntaxFactory.Token(SyntaxKind.CloseBracketToken)
);
var sizes = spec.Sizes;
Assert.Equal(4, sizes.Count);
Assert.Equal(3, sizes.SeparatorCount);
Assert.NotEqual(sizes[0], sizes[1]);
Assert.NotEqual(sizes[0], sizes[2]);
Assert.NotEqual(sizes[0], sizes[3]);
Assert.NotEqual(sizes[1], sizes[2]);
Assert.NotEqual(sizes[1], sizes[3]);
Assert.NotEqual(sizes[2], sizes[3]);
Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(1));
Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(2));
Assert.NotEqual(sizes.GetSeparator(1), sizes.GetSeparator(2));
}
[Fact]
public void ZeroWidthStructuredTrivia()
{
// create zero width structured trivia (not sure how these come about but its not impossible)
var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false);
Assert.Equal(0, zeroWidth.Width);
// create token with more than one instance of same zero width structured trivia!
var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "goo", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth)));
// create node with this token
var someNode = SyntaxFactory.IdentifierName(someToken);
Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count);
Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure);
Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure);
// prove that trivia have different identity
Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1]));
var tt0 = someNode.Identifier.TrailingTrivia[0];
var tt1 = someNode.Identifier.TrailingTrivia[1];
var str0 = tt0.GetStructure();
var str1 = tt1.GetStructure();
// prove that structures have different identity
Assert.NotEqual(str0, str1);
// prove that structured trivia can get back to original trivia with correct identity
var tr0 = str0.ParentTrivia;
Assert.Equal(tt0, tr0);
var tr1 = str1.ParentTrivia;
Assert.Equal(tt1, tr1);
}
[Fact]
public void ZeroWidthStructuredTriviaOnZeroWidthToken()
{
// create zero width structured trivia (not sure how these come about but its not impossible)
var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false);
Assert.Equal(0, zeroWidth.Width);
// create token with more than one instance of same zero width structured trivia!
var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth)));
// create node with this token
var someNode = SyntaxFactory.IdentifierName(someToken);
Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count);
Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure);
Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure);
// prove that trivia have different identity
Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1]));
var tt0 = someNode.Identifier.TrailingTrivia[0];
var tt1 = someNode.Identifier.TrailingTrivia[1];
var str0 = tt0.GetStructure();
var str1 = tt1.GetStructure();
// prove that structures have different identity
Assert.NotEqual(str0, str1);
// prove that structured trivia can get back to original trivia with correct identity
var tr0 = str0.ParentTrivia;
Assert.Equal(tt0, tr0);
var tr1 = str1.ParentTrivia;
Assert.Equal(tt1, tr1);
}
[WorkItem(537059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537059")]
[Fact]
public void TestIncompleteDeclWithDotToken()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"
class Test
{
int IX.GOO
");
// Verify the kind of the CSharpSyntaxNode "int IX.GOO" is MethodDeclaration and NOT FieldDeclaration
Assert.Equal(SyntaxKind.MethodDeclaration, tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].ChildNodesAndTokens()[3].Kind());
}
[WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")]
[Fact]
public void TestGetTokensLanguageAny()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}");
var actualTokens = syntaxTree.GetCompilationUnitRoot().DescendantTokens();
var expectedTokenKinds = new SyntaxKind[]
{
SyntaxKind.ClassKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenBraceToken,
SyntaxKind.CloseBraceToken,
SyntaxKind.EndOfFileToken,
};
Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug
Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => t.Kind())));
}
[WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")]
[Fact]
public void TestGetTokensCommonAny()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}");
var actualTokens = syntaxTree.GetRoot().DescendantTokens(syntaxTree.GetRoot().FullSpan);
var expectedTokenKinds = new SyntaxKind[]
{
SyntaxKind.ClassKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenBraceToken,
SyntaxKind.CloseBraceToken,
SyntaxKind.EndOfFileToken,
};
Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug
Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => (SyntaxKind)t.RawKind)));
}
[Fact]
public void TestGetLocation()
{
var tree = SyntaxFactory.ParseSyntaxTree("class C { void F() { } }");
dynamic root = tree.GetCompilationUnitRoot();
MethodDeclarationSyntax method = root.Members[0].Members[0];
var nodeLocation = method.GetLocation();
Assert.True(nodeLocation.IsInSource);
Assert.Equal(tree, nodeLocation.SourceTree);
Assert.Equal(method.Span, nodeLocation.SourceSpan);
var tokenLocation = method.Identifier.GetLocation();
Assert.True(tokenLocation.IsInSource);
Assert.Equal(tree, tokenLocation.SourceTree);
Assert.Equal(method.Identifier.Span, tokenLocation.SourceSpan);
var triviaLocation = method.ReturnType.GetLastToken().TrailingTrivia[0].GetLocation();
Assert.True(triviaLocation.IsInSource);
Assert.Equal(tree, triviaLocation.SourceTree);
Assert.Equal(method.ReturnType.GetLastToken().TrailingTrivia[0].Span, triviaLocation.SourceSpan);
var textSpan = new TextSpan(5, 10);
var spanLocation = tree.GetLocation(textSpan);
Assert.True(spanLocation.IsInSource);
Assert.Equal(tree, spanLocation.SourceTree);
Assert.Equal(textSpan, spanLocation.SourceSpan);
}
[Fact]
public void TestReplaceNode()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var bex = (BinaryExpressionSyntax)expr;
var expr2 = bex.ReplaceNode(bex.Right, SyntaxFactory.ParseExpression("c"));
Assert.Equal("a + c", expr2.ToFullString());
}
[Fact]
public void TestReplaceNodes()
{
var expr = SyntaxFactory.ParseExpression("a + b + c + d");
// replace each expression with a parenthesized expression
var replaced = expr.ReplaceNodes(
expr.DescendantNodes().OfType<ExpressionSyntax>(),
(node, rewritten) => SyntaxFactory.ParenthesizedExpression(rewritten));
var replacedText = replaced.ToFullString();
Assert.Equal("(((a )+ (b ))+ (c ))+ (d)", replacedText);
}
[Fact]
public void TestReplaceNodeInListWithMultiple()
{
var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)");
var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c"));
var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d"));
// replace first with multiple
var newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD });
Assert.Equal("m(c,d, b)", newNode.ToFullString());
// replace last with multiple
newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD });
Assert.Equal("m(a, c,d)", newNode.ToFullString());
// replace first with empty list
newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { });
Assert.Equal("m(b)", newNode.ToFullString());
// replace last with empty list
newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { });
Assert.Equal("m(a)", newNode.ToFullString());
}
[Fact]
public void TestReplaceNonListNodeWithMultiple()
{
var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)");
var then = ifstatement.Statement;
var stat1 = SyntaxFactory.ParseStatement("m1(x)");
var stat2 = SyntaxFactory.ParseStatement("m2(y)");
// you cannot replace a node that is a single node member with multiple nodes
Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new[] { stat1, stat2 }));
// you cannot replace a node that is a single node member with an empty list
Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new StatementSyntax[] { }));
}
[Fact]
public void TestInsertNodesInList()
{
var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)");
var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c"));
var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d"));
// insert before first
var newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD });
Assert.Equal("m(c,d,a, b)", newNode.ToFullString());
// insert after first
newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD });
Assert.Equal("m(a,c,d, b)", newNode.ToFullString());
// insert before last
newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD });
Assert.Equal("m(a,c,d, b)", newNode.ToFullString());
// insert after last
newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD });
Assert.Equal("m(a, b,c,d)", newNode.ToFullString());
}
[Fact]
public void TestInsertNodesRelativeToNonListNode()
{
var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)");
var then = ifstatement.Statement;
var stat1 = SyntaxFactory.ParseStatement("m1(x)");
var stat2 = SyntaxFactory.ParseStatement("m2(y)");
// you cannot insert nodes before/after a node that is not part of a list
Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesBefore(then, new[] { stat1, stat2 }));
// you cannot insert nodes before/after a node that is not part of a list
Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesAfter(then, new StatementSyntax[] { }));
}
[Fact]
public void TestReplaceStatementInListWithMultiple()
{
var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }");
var stmt1 = SyntaxFactory.ParseStatement("var z = 30; ");
var stmt2 = SyntaxFactory.ParseStatement("var q = 40; ");
// replace first with multiple
var newBlock = block.ReplaceNode(block.Statements[0], new[] { stmt1, stmt2 });
Assert.Equal("{ var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString());
// replace second with multiple
newBlock = block.ReplaceNode(block.Statements[1], new[] { stmt1, stmt2 });
Assert.Equal("{ var x = 10; var z = 30; var q = 40; }", newBlock.ToFullString());
// replace first with empty list
newBlock = block.ReplaceNode(block.Statements[0], new SyntaxNode[] { });
Assert.Equal("{ var y = 20; }", newBlock.ToFullString());
// replace second with empty list
newBlock = block.ReplaceNode(block.Statements[1], new SyntaxNode[] { });
Assert.Equal("{ var x = 10; }", newBlock.ToFullString());
}
[Fact]
public void TestInsertStatementsInList()
{
var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }");
var stmt1 = SyntaxFactory.ParseStatement("var z = 30; ");
var stmt2 = SyntaxFactory.ParseStatement("var q = 40; ");
// insert before first
var newBlock = block.InsertNodesBefore(block.Statements[0], new[] { stmt1, stmt2 });
Assert.Equal("{ var z = 30; var q = 40; var x = 10; var y = 20; }", newBlock.ToFullString());
// insert after first
newBlock = block.InsertNodesAfter(block.Statements[0], new[] { stmt1, stmt2 });
Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString());
// insert before last
newBlock = block.InsertNodesBefore(block.Statements[1], new[] { stmt1, stmt2 });
Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString());
// insert after last
newBlock = block.InsertNodesAfter(block.Statements[1], new[] { stmt1, stmt2 });
Assert.Equal("{ var x = 10; var y = 20; var z = 30; var q = 40; }", newBlock.ToFullString());
}
[Fact]
public void TestReplaceSingleToken()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var bToken = expr.DescendantTokens().First(t => t.Text == "b");
var expr2 = expr.ReplaceToken(bToken, SyntaxFactory.ParseToken("c"));
Assert.Equal("a + c", expr2.ToString());
}
[Fact]
public void TestReplaceMultipleTokens()
{
var expr = SyntaxFactory.ParseExpression("a + b + c");
var d = SyntaxFactory.ParseToken("d ");
var tokens = expr.DescendantTokens().Where(t => t.IsKind(SyntaxKind.IdentifierToken)).ToList();
var replaced = expr.ReplaceTokens(tokens, (tok, tok2) => d);
Assert.Equal("d + d + d ", replaced.ToFullString());
}
[Fact]
public void TestReplaceSingleTokenWithMultipleTokens()
{
var cu = SyntaxFactory.ParseCompilationUnit("private class C { }");
var privateToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0];
var publicToken = SyntaxFactory.ParseToken("public ");
var partialToken = SyntaxFactory.ParseToken("partial ");
var cu1 = cu.ReplaceToken(privateToken, publicToken);
Assert.Equal("public class C { }", cu1.ToFullString());
var cu2 = cu.ReplaceToken(privateToken, new[] { publicToken, partialToken });
Assert.Equal("public partial class C { }", cu2.ToFullString());
var cu3 = cu.ReplaceToken(privateToken, new SyntaxToken[] { });
Assert.Equal("class C { }", cu3.ToFullString());
}
[Fact]
public void TestReplaceNonListTokenWithMultipleTokensFails()
{
var cu = SyntaxFactory.ParseCompilationUnit("private class C { }");
var identifierC = cu.DescendantTokens().First(t => t.Text == "C");
var identifierA = SyntaxFactory.ParseToken("A");
var identifierB = SyntaxFactory.ParseToken("B");
// you cannot replace a token that is a single token member with multiple tokens
Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new[] { identifierA, identifierB }));
// you cannot replace a token that is a single token member with an empty list of tokens
Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new SyntaxToken[] { }));
}
[Fact]
public void TestInsertTokens()
{
var cu = SyntaxFactory.ParseCompilationUnit("public class C { }");
var publicToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0];
var partialToken = SyntaxFactory.ParseToken("partial ");
var staticToken = SyntaxFactory.ParseToken("static ");
var cu1 = cu.InsertTokensBefore(publicToken, new[] { staticToken });
Assert.Equal("static public class C { }", cu1.ToFullString());
var cu2 = cu.InsertTokensAfter(publicToken, new[] { staticToken });
Assert.Equal("public static class C { }", cu2.ToFullString());
}
[Fact]
public void TestInsertTokensRelativeToNonListToken()
{
var cu = SyntaxFactory.ParseCompilationUnit("public class C { }");
var identifierC = cu.DescendantTokens().First(t => t.Text == "C");
var identifierA = SyntaxFactory.ParseToken("A");
var identifierB = SyntaxFactory.ParseToken("B");
// you cannot insert a token before/after a token that is not part of a list of tokens
Assert.Throws<InvalidOperationException>(() => cu.InsertTokensBefore(identifierC, new[] { identifierA, identifierB }));
// you cannot insert a token before/after a token that is not part of a list of tokens
Assert.Throws<InvalidOperationException>(() => cu.InsertTokensAfter(identifierC, new[] { identifierA, identifierB }));
}
[Fact]
public void ReplaceMissingToken()
{
var text = "return x";
var expr = SyntaxFactory.ParseStatement(text);
var token = expr.DescendantTokens().First(t => t.IsMissing);
var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(token.Kind()));
var text2 = expr2.ToFullString();
Assert.Equal("return x;", text2);
}
[Fact]
public void ReplaceEndOfCommentToken()
{
var text = "/// Goo\r\n return x;";
var expr = SyntaxFactory.ParseStatement(text);
var tokens = expr.DescendantTokens(descendIntoTrivia: true).ToList();
var token = tokens.First(t => t.Kind() == SyntaxKind.EndOfDocumentationCommentToken);
var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace("garbage")), token.Kind(), default(SyntaxTriviaList)));
var text2 = expr2.ToFullString();
Assert.Equal("/// Goo\r\ngarbage return x;", text2);
}
[Fact]
public void ReplaceEndOfFileToken()
{
var text = "";
var cu = SyntaxFactory.ParseCompilationUnit(text);
var token = cu.DescendantTokens().Single(t => t.Kind() == SyntaxKind.EndOfFileToken);
var cu2 = cu.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace(" ")), token.Kind(), default(SyntaxTriviaList)));
var text2 = cu2.ToFullString();
Assert.Equal(" ", text2);
}
[Fact]
public void TestReplaceTriviaDeep()
{
var expr = SyntaxFactory.ParseExpression("#if true\r\na + \r\n#endif\r\n + b");
// get whitespace trivia inside structured directive trivia
var deepTrivia = expr.GetDirectives().SelectMany(d => d.DescendantTrivia().Where(tr => tr.Kind() == SyntaxKind.WhitespaceTrivia)).ToList();
// replace deep trivia with double-whitespace trivia
var twoSpace = SyntaxFactory.Whitespace(" ");
var expr2 = expr.ReplaceTrivia(deepTrivia, (tr, tr2) => twoSpace);
Assert.Equal("#if true\r\na + \r\n#endif\r\n + b", expr2.ToFullString());
}
[Fact]
public void TestReplaceSingleTriviaInNode()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var trivia = expr.DescendantTokens().First(t => t.Text == "a").TrailingTrivia[0];
var twoSpaces = SyntaxFactory.Whitespace(" ");
var expr2 = expr.ReplaceTrivia(trivia, twoSpaces);
Assert.Equal("a + b", expr2.ToFullString());
}
[Fact]
public void TestReplaceMultipleTriviaInNode()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var twoSpaces = SyntaxFactory.Whitespace(" ");
var trivia = expr.DescendantTrivia().Where(tr => tr.IsKind(SyntaxKind.WhitespaceTrivia)).ToList();
var replaced = expr.ReplaceTrivia(trivia, (tr, tr2) => twoSpaces);
Assert.Equal("a + b", replaced.ToFullString());
}
[Fact]
public void TestReplaceSingleTriviaWithMultipleTriviaInNode()
{
var ex = SyntaxFactory.ParseExpression("/* c */ identifier");
var leadingTrivia = ex.GetLeadingTrivia();
Assert.Equal(2, leadingTrivia.Count);
var comment1 = leadingTrivia[0];
Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind());
var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0];
var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0];
var ex1 = ex.ReplaceTrivia(comment1, newComment1);
Assert.Equal("/* a */ identifier", ex1.ToFullString());
var ex2 = ex.ReplaceTrivia(comment1, new[] { newComment1, newComment2 });
Assert.Equal("/* a *//* b */ identifier", ex2.ToFullString());
var ex3 = ex.ReplaceTrivia(comment1, new SyntaxTrivia[] { });
Assert.Equal(" identifier", ex3.ToFullString());
}
[Fact]
public void TestInsertTriviaInNode()
{
var ex = SyntaxFactory.ParseExpression("/* c */ identifier");
var leadingTrivia = ex.GetLeadingTrivia();
Assert.Equal(2, leadingTrivia.Count);
var comment1 = leadingTrivia[0];
Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind());
var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0];
var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0];
var ex1 = ex.InsertTriviaBefore(comment1, new[] { newComment1, newComment2 });
Assert.Equal("/* a *//* b *//* c */ identifier", ex1.ToFullString());
var ex2 = ex.InsertTriviaAfter(comment1, new[] { newComment1, newComment2 });
Assert.Equal("/* c *//* a *//* b */ identifier", ex2.ToFullString());
}
[Fact]
public void TestReplaceSingleTriviaInToken()
{
var id = SyntaxFactory.ParseToken("a ");
var trivia = id.TrailingTrivia[0];
var twoSpace = SyntaxFactory.Whitespace(" ");
var id2 = id.ReplaceTrivia(trivia, twoSpace);
Assert.Equal("a ", id2.ToFullString());
}
[Fact]
public void TestReplaceMultipleTriviaInToken()
{
var id = SyntaxFactory.ParseToken("a // goo\r\n");
// replace each trivia with a single space
var id2 = id.ReplaceTrivia(id.GetAllTrivia(), (tr, tr2) => SyntaxFactory.Space);
// should be 3 spaces (one for original space, comment and end-of-line)
Assert.Equal("a ", id2.ToFullString());
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia()
{
var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal("m(a , /* trivia */ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_2()
{
var expr = SyntaxFactory.ParseExpression(@"m(a, b, /* trivia */
c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"m(a, /* trivia */
c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_3()
{
var expr = SyntaxFactory.ParseExpression(@"m(a, b,
/* trivia */ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"m(a,
/* trivia */ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_4()
{
var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a,
/*arg2:*/ b,
/*arg3:*/ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"SomeMethod(/*arg1:*/ a,
/*arg2:*/
/*arg3:*/ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_5()
{
var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a
a,
// some comment about b
b,
// some comment about c
c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"SomeMethod(// comment about a
a,
// some comment about b
// some comment about c
c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepNoTrivia()
{
var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal("m(a, /* trivia */ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepNoTrivia_2()
{
var expr = SyntaxFactory.ParseExpression(
@"m(a, b, /* trivia */
c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"m(a, c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepNoTrivia_3()
{
var expr = SyntaxFactory.ParseExpression(
@"m(a, b,
/* trivia */ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"m(a, /* trivia */ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepNoTrivia_4()
{
var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a,
/*arg2:*/ b,
/*arg3:*/ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"SomeMethod(/*arg1:*/ a,
/*arg3:*/ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepNoTrivia_5()
{
var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a
a,
// some comment about b
b,
// some comment about c
c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"SomeMethod(// comment about a
a,
// some comment about c
c)", text);
}
[Fact]
public void TestRemoveOnlyNodeInSeparatedList_KeepExteriorTrivia()
{
var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */)");
var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(n);
var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal("m(/* before */ /* after */)", text);
}
[Fact]
public void TestRemoveFirstNodeInSeparatedList_KeepExteriorTrivia()
{
var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */, b, c)");
var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(n);
var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal("m(/* before */ /* after */ b, c)", text);
}
[Fact]
public void TestRemoveLastNodeInSeparatedList_KeepExteriorTrivia()
{
var expr = SyntaxFactory.ParseExpression("m(a, b, /* before */ c /* after */)");
var n = expr.DescendantTokens().Where(t => t.Text == "c").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(n);
var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal("m(a, b /* before */ /* after */)", text);
}
[Fact]
public void TestRemoveNode_KeepNoTrivia()
{
var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal("{ a; c }", text);
}
[Fact]
public void TestRemoveNode_KeepExteriorTrivia()
{
var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal("{ a; /* trivia */ c }", text);
}
[Fact]
public void TestRemoveLastNode_KeepExteriorTrivia()
{
// this tests removing the last node in a non-terminal such that there is no token to the right of the removed
// node to attach the kept trivia too. The trivia must be attached to the previous token.
var cu = SyntaxFactory.ParseCompilationUnit("class C { void M() { } /* trivia */ }");
var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
// remove the body block from the method syntax (since it can be set to null)
var m2 = m.RemoveNode(m.Body, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = m2.ToFullString();
Assert.Equal("void M() /* trivia */ ", text);
}
[Fact]
public void TestRemove_KeepExteriorTrivia_KeepUnbalancedDirectives()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"
class C
{
// before
void M()
{
#region Fred
} // after
#endregion
}");
var expectedText = @"
class C
{
// before
#region Fred
// after
#endregion
}";
var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepExteriorTrivia | SyntaxRemoveOptions.KeepUnbalancedDirectives);
var text = cu2.ToFullString();
Assert.Equal(expectedText, text);
}
[Fact]
public void TestRemove_KeepUnbalancedDirectives()
{
var inputText = @"
class C
{
// before
#region Fred
// more before
void M()
{
} // after
#endregion
}";
var expectedText = @"
class C
{
#region Fred
#endregion
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepUnbalancedDirectives);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
public void TestRemove_KeepDirectives()
{
var inputText = @"
class C
{
// before
#region Fred
// more before
void M()
{
#if true
#endif
} // after
#endregion
}";
var expectedText = @"
class C
{
#region Fred
#if true
#endif
#endregion
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepDirectives);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemove_KeepEndOfLine()
{
var inputText = @"
class C
{
// before
void M()
{
} // after
}";
var expectedText = @"
class C
{
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveWithoutEOL_KeepEndOfLine()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } // test");
var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal("class A { } ", text);
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveBadDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } #endregion");
var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives);
var text = cu2.ToFullString();
Assert.Equal("class A { } \r\n#endregion", text);
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveDocument_KeepEndOfLine()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"
#region A
class A
{ }
#endregion");
var cu2 = cu.RemoveNode(cu, SyntaxRemoveOptions.KeepEndOfLine);
Assert.Null(cu2);
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveFirstParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine()
{
// EOL should be found on CommaToken TrailingTrivia
var inputText = @"
class C
{
void M(
// before a
int a,
// after a
// before b
int b
/* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
// after a
// before b
int b
/* after b*/)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveFirstParameterEOLParameterSyntaxTrailingTrivia_KeepEndOfLine()
{
// EOL should be found on ParameterSyntax TrailingTrivia
var inputText = @"
class C
{
void M(
// before a
int a
, /* after comma */ int b
/* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
int b
/* after b*/)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveFirstParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine()
{
// EOL should be found on CommaToken LeadingTrivia and also on ParameterSyntax TrailingTrivia
// but only one will be added
var inputText = @"
class C
{
void M(
// before a
int a
// before b
, /* after comma */ int b
/* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
int b
/* after b*/)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveFirstParameter_KeepTrailingTrivia()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"
class C
{
void M(
// before a
int a
// before b
, /* after comma */ int b
/* after b*/)
{
}
}");
var expectedText = @"
class C
{
void M(
// before b
/* after comma */ int b
/* after b*/)
{
}
}";
var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepTrailingTrivia);
var text = cu2.ToFullString();
Assert.Equal(expectedText, text);
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveLastParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine()
{
// EOL should be found on CommaToken LeadingTrivia
var inputText = @"
class C
{
void M(
// before a
int a
// after a
, /* after comma*/ int b /* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
// before a
int a
)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveLastParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine()
{
// EOL should be found on CommaToken TrailingTrivia
var inputText = @"
class C
{
void M(
// before a
int a, /* after comma*/
int b /* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
// before a
int a
)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveLastParameterEOLParameterSyntaxLeadingTrivia_KeepEndOfLine()
{
// EOL should be found on ParameterSyntax LeadingTrivia and also on CommaToken TrailingTrivia
// but only one will be added
var inputText = @"
class C
{
void M(
// before a
int a, /* after comma */
// before b
int b /* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
// before a
int a
)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveLastParameter_KeepLeadingTrivia()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"
class C
{
void M(
// before a
int a, /* after comma */
// before b
int b /* after b*/)
{
}
}");
var expectedText = @"
class C
{
void M(
// before a
int a /* after comma */
// before b
)
{
}
}";
var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepLeadingTrivia);
var text = cu2.ToFullString();
Assert.Equal(expectedText, text);
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveClassWithEndRegionDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives()
{
var inputText = @"
#region A
class A { } #endregion";
var expectedText = @"
#region A
#endregion";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
public void SeparatorsOfSeparatedSyntaxLists()
{
var s1 = "int goo(int a, int b, int c) {}";
var tree = SyntaxFactory.ParseSyntaxTree(s1);
var root = tree.GetCompilationUnitRoot();
var method = (LocalFunctionStatementSyntax)((GlobalStatementSyntax)root.Members[0]).Statement;
var list = (SeparatedSyntaxList<ParameterSyntax>)method.ParameterList.Parameters;
Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(0)).Kind());
Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(1)).Kind());
foreach (var index in new int[] { -1, 2 })
{
bool exceptionThrown = false;
try
{
var unused = list.GetSeparator(2);
}
catch (ArgumentOutOfRangeException)
{
exceptionThrown = true;
}
Assert.True(exceptionThrown);
}
var internalParameterList = (InternalSyntax.ParameterListSyntax)method.ParameterList.Green;
var internalParameters = internalParameterList.Parameters;
Assert.Equal(2, internalParameters.SeparatorCount);
Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(0))).Kind());
Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(1))).Kind());
Assert.Equal(3, internalParameters.Count);
Assert.Equal("a", internalParameters[0].Identifier.ValueText);
Assert.Equal("b", internalParameters[1].Identifier.ValueText);
Assert.Equal("c", internalParameters[2].Identifier.ValueText);
}
[Fact]
public void ThrowIfUnderlyingNodeIsNullForList()
{
var list = new SyntaxNodeOrTokenList();
Assert.Equal(0, list.Count);
foreach (var index in new int[] { -1, 0, 23 })
{
bool exceptionThrown = false;
try
{
var unused = list[0];
}
catch (ArgumentOutOfRangeException)
{
exceptionThrown = true;
}
Assert.True(exceptionThrown);
}
}
[WorkItem(541188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541188")]
[Fact]
public void GetDiagnosticsOnMissingToken()
{
var syntaxTree = SyntaxFactory.ParseSyntaxTree(@"namespace n1 { c1<t");
var token = syntaxTree.FindNodeOrTokenByKind(SyntaxKind.GreaterThanToken);
var diag = syntaxTree.GetDiagnostics(token).ToList();
Assert.True(token.IsMissing);
Assert.Equal(1, diag.Count);
}
[WorkItem(541325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541325")]
[Fact]
public void GetDiagnosticsOnMissingToken2()
{
var syntaxTree = SyntaxFactory.ParseSyntaxTree(@"
class Base<T>
{
public virtual int Property
{
get { return 0; }
// Note: Repro for bug 7990 requires a missing close brace token i.e. missing } below
set {
}
public virtual void Method()
{
}
}");
foreach (var t in syntaxTree.GetCompilationUnitRoot().DescendantTokens())
{
// Bug 7990: Below for loop is an infinite loop.
foreach (var e in syntaxTree.GetDiagnostics(t))
{
}
}
// TODO: Please add meaningful checks once the above deadlock issue is fixed.
}
[WorkItem(541648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541648")]
[Fact]
public void GetDiagnosticsOnMissingToken4()
{
string code = @"
public class MyClass
{
using Lib;
using Lib2;
public class Test1
{
}
}";
var syntaxTree = SyntaxFactory.ParseSyntaxTree(code);
var token = syntaxTree.GetCompilationUnitRoot().FindToken(code.IndexOf("using Lib;", StringComparison.Ordinal));
var diag = syntaxTree.GetDiagnostics(token).ToList();
Assert.True(token.IsMissing);
Assert.Equal(3, diag.Count);
}
[WorkItem(541630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541630")]
[Fact]
public void GetDiagnosticsOnBadReferenceDirective()
{
string code = @"class c1
{
#r
void m1()
{
}
}";
var tree = SyntaxFactory.ParseSyntaxTree(code);
var trivia = tree.GetCompilationUnitRoot().FindTrivia(code.IndexOf("#r", StringComparison.Ordinal)); // ReferenceDirective.
foreach (var diag in tree.GetDiagnostics(trivia))
{
Assert.NotNull(diag);
// TODO: Please add any additional validations if necessary.
}
}
[WorkItem(528626, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528626")]
[Fact]
public void SpanOfNodeWithMissingChildren()
{
string code = @"delegate = 1;";
var tree = SyntaxFactory.ParseSyntaxTree(code);
var compilationUnit = tree.GetCompilationUnitRoot();
var delegateDecl = (DelegateDeclarationSyntax)compilationUnit.Members[0];
var paramList = delegateDecl.ParameterList;
// For (non-EOF) tokens, IsMissing is true if and only if Width is 0.
Assert.True(compilationUnit.DescendantTokens(node => true).
Where(token => token.Kind() != SyntaxKind.EndOfFileToken).
All(token => token.IsMissing == (token.Width == 0)));
// For non-terminals, Is true if Width is 0, but the converse may not hold.
Assert.True(paramList.IsMissing);
Assert.NotEqual(0, paramList.Width);
Assert.NotEqual(0, paramList.FullWidth);
}
[WorkItem(542457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542457")]
[Fact]
public void AddMethodModifier()
{
var tree = SyntaxFactory.ParseSyntaxTree(@"
class Program
{
static void Main(string[] args)
{
}
}");
var compilationUnit = tree.GetCompilationUnitRoot();
var @class = (ClassDeclarationSyntax)compilationUnit.Members.Single();
var method = (MethodDeclarationSyntax)@class.Members.Single();
var newModifiers = method.Modifiers.Add(SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.UnsafeKeyword, SyntaxFactory.TriviaList(SyntaxFactory.Space)));
Assert.Equal(" static unsafe ", newModifiers.ToFullString());
Assert.Equal(2, newModifiers.Count);
Assert.Equal(SyntaxKind.StaticKeyword, newModifiers[0].Kind());
Assert.Equal(SyntaxKind.UnsafeKeyword, newModifiers[1].Kind());
}
[Fact]
public void SeparatedSyntaxListValidation()
{
var intType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword));
var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken);
SyntaxFactory.SingletonSeparatedList<TypeSyntax>(intType);
SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken });
SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType });
SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType, commaToken });
Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { commaToken }));
Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, commaToken }));
Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, intType }));
}
[WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")]
[Fact]
public void SyntaxDotParseCompilationUnitContainingOnlyWhitespace()
{
var node = SyntaxFactory.ParseCompilationUnit(" ");
Assert.True(node.HasLeadingTrivia);
Assert.Equal(1, node.GetLeadingTrivia().Count);
Assert.Equal(1, node.DescendantTrivia().Count());
Assert.Equal(" ", node.GetLeadingTrivia().First().ToString());
}
[WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")]
[Fact]
public void SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace()
{
var node = SyntaxFactory.ParseSyntaxTree(" ").GetCompilationUnitRoot();
Assert.True(node.HasLeadingTrivia);
Assert.Equal(1, node.GetLeadingTrivia().Count);
Assert.Equal(1, node.DescendantTrivia().Count());
Assert.Equal(" ", node.GetLeadingTrivia().First().ToString());
}
[Fact]
public void SyntaxNodeAndTokenToString()
{
var text = @"class A { }";
var root = SyntaxFactory.ParseCompilationUnit(text);
var children = root.DescendantNodesAndTokens();
var nodeOrToken = children.First();
Assert.Equal("class A { }", nodeOrToken.ToString());
Assert.Equal(text, nodeOrToken.ToString());
var node = (SyntaxNode)children.First(n => n.IsNode);
Assert.Equal("class A { }", node.ToString());
Assert.Equal(text, node.ToFullString());
var token = (SyntaxToken)children.First(n => n.IsToken);
Assert.Equal("class", token.ToString());
Assert.Equal("class ", token.ToFullString());
var trivia = root.DescendantTrivia().First();
Assert.Equal(" ", trivia.ToString());
Assert.Equal(" ", trivia.ToFullString());
}
[WorkItem(545116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545116")]
[Fact]
public void FindTriviaOutsideNode()
{
var text = @"// This is trivia
class C
{
static void Main()
{
}
}
";
var root = SyntaxFactory.ParseCompilationUnit(text);
Assert.InRange(0, root.FullSpan.Start, root.FullSpan.End);
var rootTrivia = root.FindTrivia(0);
Assert.Equal("// This is trivia", rootTrivia.ToString().Trim());
var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.NotInRange(0, method.FullSpan.Start, method.FullSpan.End);
var methodTrivia = method.FindTrivia(0);
Assert.Equal(default(SyntaxTrivia), methodTrivia);
}
[Fact]
public void TestSyntaxTriviaListEquals()
{
var emptyWhitespace = SyntaxFactory.Whitespace("");
var emptyToken = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken).WithTrailingTrivia(emptyWhitespace, emptyWhitespace);
var emptyTokenList = SyntaxFactory.TokenList(emptyToken, emptyToken);
// elements should be not equal
Assert.NotEqual(emptyTokenList[0].TrailingTrivia[0], emptyTokenList[1].TrailingTrivia[0]);
// lists should be not equal
Assert.NotEqual(emptyTokenList[0].TrailingTrivia, emptyTokenList[1].TrailingTrivia);
// Two lists with the same parent node, but different indexes should NOT be the same.
var emptyTriviaList = SyntaxFactory.TriviaList(emptyWhitespace, emptyWhitespace);
emptyToken = emptyToken.WithLeadingTrivia(emptyTriviaList).WithTrailingTrivia(emptyTriviaList);
// elements should be not equal
Assert.NotEqual(emptyToken.LeadingTrivia[0], emptyToken.TrailingTrivia[0]);
// lists should be not equal
Assert.NotEqual(emptyToken.LeadingTrivia, emptyToken.TrailingTrivia);
}
[Fact]
public void Test_SyntaxTree_ParseTextInvalidArguments()
{
// Invalid arguments - Validate Exceptions
Assert.Throws<System.ArgumentNullException>(delegate
{
SourceText st = null;
var treeFromSource_invalid2 = SyntaxFactory.ParseSyntaxTree(st);
});
}
[Fact]
public void TestSyntaxTree_Changes()
{
string SourceText = @"using System;
using System.Linq;
using System.Collections;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}";
SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText);
var root = (CompilationUnitSyntax)tree.GetRoot();
// Get the Imports Clauses
var FirstUsingClause = root.Usings[0];
var SecondUsingClause = root.Usings[1];
var ThirdUsingClause = root.Usings[2];
var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree);
Assert.Equal(0, ChangesForDifferentTrees.Count);
// Do a transform to Replace and Existing Tree
NameSyntax name = SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Collections.Generic"));
UsingDirectiveSyntax newUsingClause = ThirdUsingClause.WithName(name);
// Replace Node with a different Imports Clause
root = root.ReplaceNode(ThirdUsingClause, newUsingClause);
var ChangesFromTransform = ThirdUsingClause.SyntaxTree.GetChanges(newUsingClause.SyntaxTree);
Assert.Equal(2, ChangesFromTransform.Count);
// Using the Common Syntax Changes Method
SyntaxTree x = ThirdUsingClause.SyntaxTree;
SyntaxTree y = newUsingClause.SyntaxTree;
var changes2UsingCommonSyntax = x.GetChanges(y);
Assert.Equal(2, changes2UsingCommonSyntax.Count);
// Verify Changes from CS Specific SyntaxTree and Common SyntaxTree are the same
Assert.Equal(ChangesFromTransform, changes2UsingCommonSyntax);
}
[Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")]
public void TestSyntaxTree_GetChangesInvalid()
{
string SourceText = @"using System;
using System.Linq;
using System.Collections;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}";
SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText);
var root = (CompilationUnitSyntax)tree.GetRoot();
// Get the Imports Clauses
var FirstUsingClause = root.Usings[0];
var SecondUsingClause = root.Usings[1];
var ThirdUsingClause = root.Usings[2];
var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree);
Assert.Equal(0, ChangesForDifferentTrees.Count);
// With null tree
SyntaxTree BlankTree = null;
Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChanges(BlankTree));
}
[Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")]
public void TestSyntaxTree_GetChangedSpansInvalid()
{
string SourceText = @"using System;
using System.Linq;
using System.Collections;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}";
SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText);
var root = (CompilationUnitSyntax)tree.GetRoot();
// Get the Imports Clauses
var FirstUsingClause = root.Usings[0];
var SecondUsingClause = root.Usings[1];
var ThirdUsingClause = root.Usings[2];
var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChangedSpans(SecondUsingClause.SyntaxTree);
Assert.Equal(0, ChangesForDifferentTrees.Count);
// With null tree
SyntaxTree BlankTree = null;
Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChangedSpans(BlankTree));
}
[Fact]
public void TestTriviaExists()
{
// token constructed using factory w/o specifying trivia (should have zero-width elastic trivia)
var idToken = SyntaxFactory.Identifier("goo");
Assert.True(idToken.HasLeadingTrivia);
Assert.Equal(1, idToken.LeadingTrivia.Count);
Assert.Equal(0, idToken.LeadingTrivia.Span.Length); // zero-width elastic trivia
Assert.True(idToken.HasTrailingTrivia);
Assert.Equal(1, idToken.TrailingTrivia.Count);
Assert.Equal(0, idToken.TrailingTrivia.Span.Length); // zero-width elastic trivia
// token constructed by parser w/o trivia
idToken = SyntaxFactory.ParseToken("x");
Assert.False(idToken.HasLeadingTrivia);
Assert.Equal(0, idToken.LeadingTrivia.Count);
Assert.False(idToken.HasTrailingTrivia);
Assert.Equal(0, idToken.TrailingTrivia.Count);
// token constructed by parser with trivia
idToken = SyntaxFactory.ParseToken(" x ");
Assert.True(idToken.HasLeadingTrivia);
Assert.Equal(1, idToken.LeadingTrivia.Count);
Assert.Equal(1, idToken.LeadingTrivia.Span.Length);
Assert.True(idToken.HasTrailingTrivia);
Assert.Equal(1, idToken.TrailingTrivia.Count);
Assert.Equal(2, idToken.TrailingTrivia.Span.Length);
// node constructed using factory w/o specifying trivia
SyntaxNode namedNode = SyntaxFactory.IdentifierName("goo");
Assert.True(namedNode.HasLeadingTrivia);
Assert.Equal(1, namedNode.GetLeadingTrivia().Count);
Assert.Equal(0, namedNode.GetLeadingTrivia().Span.Length); // zero-width elastic trivia
Assert.True(namedNode.HasTrailingTrivia);
Assert.Equal(1, namedNode.GetTrailingTrivia().Count);
Assert.Equal(0, namedNode.GetTrailingTrivia().Span.Length); // zero-width elastic trivia
// node constructed by parse w/o trivia
namedNode = SyntaxFactory.ParseExpression("goo");
Assert.False(namedNode.HasLeadingTrivia);
Assert.Equal(0, namedNode.GetLeadingTrivia().Count);
Assert.False(namedNode.HasTrailingTrivia);
Assert.Equal(0, namedNode.GetTrailingTrivia().Count);
// node constructed by parse with trivia
namedNode = SyntaxFactory.ParseExpression(" goo ");
Assert.True(namedNode.HasLeadingTrivia);
Assert.Equal(1, namedNode.GetLeadingTrivia().Count);
Assert.Equal(1, namedNode.GetLeadingTrivia().Span.Length);
Assert.True(namedNode.HasTrailingTrivia);
Assert.Equal(1, namedNode.GetTrailingTrivia().Count);
Assert.Equal(2, namedNode.GetTrailingTrivia().Span.Length);
// nodeOrToken with token constructed from factory w/o specifying trivia
SyntaxNodeOrToken nodeOrToken = SyntaxFactory.Identifier("goo");
Assert.True(nodeOrToken.HasLeadingTrivia);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count);
Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia
Assert.True(nodeOrToken.HasTrailingTrivia);
Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count);
Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia
// nodeOrToken with node constructed from factory w/o specifying trivia
nodeOrToken = SyntaxFactory.IdentifierName("goo");
Assert.True(nodeOrToken.HasLeadingTrivia);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count);
Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia
Assert.True(nodeOrToken.HasTrailingTrivia);
Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count);
Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia
// nodeOrToken with token parsed from factory w/o trivia
nodeOrToken = SyntaxFactory.ParseToken("goo");
Assert.False(nodeOrToken.HasLeadingTrivia);
Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count);
Assert.False(nodeOrToken.HasTrailingTrivia);
Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count);
// nodeOrToken with node parsed from factory w/o trivia
nodeOrToken = SyntaxFactory.ParseExpression("goo");
Assert.False(nodeOrToken.HasLeadingTrivia);
Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count);
Assert.False(nodeOrToken.HasTrailingTrivia);
Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count);
// nodeOrToken with token parsed from factory with trivia
nodeOrToken = SyntaxFactory.ParseToken(" goo ");
Assert.True(nodeOrToken.HasLeadingTrivia);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia
Assert.True(nodeOrToken.HasTrailingTrivia);
Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count);
Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia
// nodeOrToken with node parsed from factory with trivia
nodeOrToken = SyntaxFactory.ParseExpression(" goo ");
Assert.True(nodeOrToken.HasLeadingTrivia);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia
Assert.True(nodeOrToken.HasTrailingTrivia);
Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count);
Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia
}
[WorkItem(6536, "https://github.com/dotnet/roslyn/issues/6536")]
[Fact]
public void TestFindTrivia_NoStackOverflowOnLargeExpression()
{
StringBuilder code = new StringBuilder();
code.Append(
@"class Goo
{
void Bar()
{
string test = ");
for (var i = 0; i < 3000; i++)
{
code.Append(@"""asdf"" + ");
}
code.Append(@"""last"";
}
}");
var tree = SyntaxFactory.ParseSyntaxTree(code.ToString());
var position = 4000;
var trivia = tree.GetCompilationUnitRoot().FindTrivia(position);
// no stack overflow
}
[Fact, WorkItem(8625, "https://github.com/dotnet/roslyn/issues/8625")]
public void SyntaxNodeContains()
{
var text = "a + (b - (c * (d / e)))";
var expression = SyntaxFactory.ParseExpression(text);
var a = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e");
var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression);
Assert.False(firstParens.Contains(a)); // fixing #8625 allows this to return quicker
Assert.True(firstParens.Contains(e));
}
private static void TestWithWindowsAndUnixEndOfLines(string inputText, string expectedText, Action<CompilationUnitSyntax, string> action)
{
inputText = inputText.NormalizeLineEndings();
expectedText = expectedText.NormalizeLineEndings();
var tests = new Dictionary<string, string>
{
{inputText, expectedText}, // Test CRLF (Windows)
{inputText.Replace("\r", ""), expectedText.Replace("\r", "")}, // Test LF (Unix)
};
foreach (var test in tests)
{
action(SyntaxFactory.ParseCompilationUnit(test.Key), test.Value);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax;
using System.Text;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class SyntaxNodeTests
{
[Fact]
[WorkItem(565382, "https://developercommunity.visualstudio.com/content/problem/565382/compiling-causes-a-stack-overflow-error.html")]
public void TestLargeFluentCallWithDirective()
{
var builder = new StringBuilder();
builder.AppendLine(
@"
class C {
C M(string x) { return this; }
void M2() {
new C()
#region Region
");
for (int i = 0; i < 20000; i++)
{
builder.AppendLine(@" .M(""test"")");
}
builder.AppendLine(
@" .M(""test"");
#endregion
}
}");
var tree = SyntaxFactory.ParseSyntaxTree(builder.ToString());
var directives = tree.GetRoot().GetDirectives();
Assert.Equal(2, directives.Count);
}
[Fact]
public void TestQualifiedNameSyntaxWith()
{
// this is just a test to prove that at least one generate With method exists and functions correctly. :-)
var qname = (QualifiedNameSyntax)SyntaxFactory.ParseName("A.B");
var qname2 = qname.WithRight(SyntaxFactory.IdentifierName("C"));
var text = qname2.ToString();
Assert.Equal("A.C", text);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TestAddBaseListTypes()
{
var cls = SyntaxFactory.ParseCompilationUnit("class C { }").Members[0] as ClassDeclarationSyntax;
var cls2 = cls.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("B")));
}
[Fact]
public void TestChildNodes()
{
var text = "m(a,b,c)";
var expression = SyntaxFactory.ParseExpression(text);
var nodes = expression.ChildNodes().ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind());
Assert.Equal(SyntaxKind.ArgumentList, nodes[1].Kind());
}
[Fact]
public void TestAncestors()
{
var text = "a + (b - (c * (d / e)))";
var expression = SyntaxFactory.ParseExpression(text);
var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e");
var nodes = e.Ancestors().ToList();
Assert.Equal(7, nodes.Count);
Assert.Equal(SyntaxKind.DivideExpression, nodes[0].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[1].Kind());
Assert.Equal(SyntaxKind.MultiplyExpression, nodes[2].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[3].Kind());
Assert.Equal(SyntaxKind.SubtractExpression, nodes[4].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[5].Kind());
Assert.Equal(SyntaxKind.AddExpression, nodes[6].Kind());
}
[Fact]
public void TestAncestorsAndSelf()
{
var text = "a + (b - (c * (d / e)))";
var expression = SyntaxFactory.ParseExpression(text);
var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e");
var nodes = e.AncestorsAndSelf().ToList();
Assert.Equal(8, nodes.Count);
Assert.Equal(SyntaxKind.IdentifierName, nodes[0].Kind());
Assert.Equal(SyntaxKind.DivideExpression, nodes[1].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[2].Kind());
Assert.Equal(SyntaxKind.MultiplyExpression, nodes[3].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[4].Kind());
Assert.Equal(SyntaxKind.SubtractExpression, nodes[5].Kind());
Assert.Equal(SyntaxKind.ParenthesizedExpression, nodes[6].Kind());
Assert.Equal(SyntaxKind.AddExpression, nodes[7].Kind());
}
[Fact]
public void TestFirstAncestorOrSelf()
{
var text = "a + (b - (c * (d / e)))";
var expression = SyntaxFactory.ParseExpression(text);
var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e");
var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression);
Assert.NotNull(firstParens);
Assert.Equal("(d / e)", firstParens.ToString());
}
[Fact]
public void TestDescendantNodes()
{
var text = "#if true\r\n return true;";
var statement = SyntaxFactory.ParseStatement(text);
var nodes = statement.DescendantNodes().ToList();
Assert.Equal(1, nodes.Count);
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind());
nodes = statement.DescendantNodes(descendIntoTrivia: true).ToList();
Assert.Equal(3, nodes.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
nodes = statement.DescendantNodes(n => n is StatementSyntax).ToList();
Assert.Equal(1, nodes.Count);
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind());
nodes = statement.DescendantNodes(n => n is StatementSyntax, descendIntoTrivia: true).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
// all over again with spans
nodes = statement.DescendantNodes(statement.FullSpan).ToList();
Assert.Equal(1, nodes.Count);
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind());
nodes = statement.DescendantNodes(statement.FullSpan, descendIntoTrivia: true).ToList();
Assert.Equal(3, nodes.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax).ToList();
Assert.Equal(1, nodes.Count);
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[0].Kind());
nodes = statement.DescendantNodes(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
}
[Fact]
public void TestDescendantNodesAndSelf()
{
var text = "#if true\r\n return true;";
var statement = SyntaxFactory.ParseStatement(text);
var nodes = statement.DescendantNodesAndSelf().ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
nodes = statement.DescendantNodesAndSelf(descendIntoTrivia: true).ToList();
Assert.Equal(4, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind());
nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
nodes = statement.DescendantNodesAndSelf(n => n is StatementSyntax, descendIntoTrivia: true).ToList();
Assert.Equal(3, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
// all over again with spans
nodes = statement.DescendantNodesAndSelf(statement.FullSpan).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
nodes = statement.DescendantNodesAndSelf(statement.FullSpan, descendIntoTrivia: true).ToList();
Assert.Equal(4, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[3].Kind());
nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[1].Kind());
nodes = statement.DescendantNodesAndSelf(statement.FullSpan, n => n is StatementSyntax, descendIntoTrivia: true).ToList();
Assert.Equal(3, nodes.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodes[0].Kind());
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodes[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodes[2].Kind());
}
[Fact]
public void TestDescendantNodesAndTokens()
{
var text = "#if true\r\n return true;";
var statement = SyntaxFactory.ParseStatement(text);
var nodesAndTokens = statement.DescendantNodesAndTokens().ToList();
Assert.Equal(4, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind());
nodesAndTokens = statement.DescendantNodesAndTokens(descendIntoTrivia: true).ToList();
Assert.Equal(10, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[3].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[4].Kind());
Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[5].Kind());
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[6].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[7].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[8].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[9].Kind());
// with span
nodesAndTokens = statement.DescendantNodesAndTokens(statement.FullSpan).ToList();
Assert.Equal(4, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[3].Kind());
}
[Fact]
public void TestDescendantNodesAndTokensAndSelf()
{
var text = "#if true\r\n return true;";
var statement = SyntaxFactory.ParseStatement(text);
var nodesAndTokens = statement.DescendantNodesAndTokensAndSelf().ToList();
Assert.Equal(5, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind());
nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList();
Assert.Equal(11, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.IfDirectiveTrivia, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.HashToken, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.IfKeyword, nodesAndTokens[3].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[4].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[5].Kind());
Assert.Equal(SyntaxKind.EndOfDirectiveToken, nodesAndTokens[6].Kind());
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[7].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[8].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[9].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[10].Kind());
// with span
nodesAndTokens = statement.DescendantNodesAndTokensAndSelf(statement.FullSpan).ToList();
Assert.Equal(5, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.ReturnStatement, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.ReturnKeyword, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.TrueLiteralExpression, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.TrueKeyword, nodesAndTokens[3].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, nodesAndTokens[4].Kind());
}
[Fact]
public void TestDescendantNodesAndTokensAndSelfForEmptyCompilationUnit()
{
var text = "";
var cu = SyntaxFactory.ParseCompilationUnit(text);
var nodesAndTokens = cu.DescendantNodesAndTokensAndSelf().ToList();
Assert.Equal(2, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.CompilationUnit, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.EndOfFileToken, nodesAndTokens[1].Kind());
}
[Fact]
public void TestDescendantNodesAndTokensAndSelfForDocumentationComment()
{
var text = "/// Goo\r\n x";
var expr = SyntaxFactory.ParseExpression(text);
var nodesAndTokens = expr.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToList();
Assert.Equal(7, nodesAndTokens.Count);
Assert.Equal(SyntaxKind.IdentifierName, nodesAndTokens[0].Kind());
Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, nodesAndTokens[1].Kind());
Assert.Equal(SyntaxKind.XmlText, nodesAndTokens[2].Kind());
Assert.Equal(SyntaxKind.XmlTextLiteralToken, nodesAndTokens[3].Kind());
Assert.Equal(SyntaxKind.XmlTextLiteralNewLineToken, nodesAndTokens[4].Kind());
Assert.Equal(SyntaxKind.EndOfDocumentationCommentToken, nodesAndTokens[5].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, nodesAndTokens[6].Kind());
}
[Fact]
public void TestGetAllDirectivesUsingDescendantNodes()
{
var text = "#if false\r\n eat a sandwich\r\n#endif\r\n x";
var expr = SyntaxFactory.ParseExpression(text);
var directives = expr.GetDirectives();
var descendantDirectives = expr.DescendantNodesAndSelf(n => n.ContainsDirectives, descendIntoTrivia: true).OfType<DirectiveTriviaSyntax>().ToList();
Assert.Equal(directives.Count, descendantDirectives.Count);
for (int i = 0; i < directives.Count; i++)
{
Assert.Equal(directives[i], descendantDirectives[i]);
}
}
[Fact]
public void TestGetAllAnnotatedNodesUsingDescendantNodes()
{
var text = "a + (b - (c * (d / e)))";
var expr = SyntaxFactory.ParseExpression(text);
var myAnnotation = new SyntaxAnnotation();
var identifierNodes = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList();
var exprWithAnnotations = expr.ReplaceNodes(identifierNodes, (e, e2) => e2.WithAdditionalAnnotations(myAnnotation));
var nodesWithMyAnnotations = exprWithAnnotations.DescendantNodesAndSelf(n => n.ContainsAnnotations).Where(n => n.HasAnnotation(myAnnotation)).ToList();
Assert.Equal(identifierNodes.Count, nodesWithMyAnnotations.Count);
for (int i = 0; i < identifierNodes.Count; i++)
{
// compare text because node identity changed when adding the annotation
Assert.Equal(identifierNodes[i].ToString(), nodesWithMyAnnotations[i].ToString());
}
}
[Fact]
public void TestDescendantTokens()
{
var s1 = "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList();
Assert.Equal(4, tokens.Count);
Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind());
Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind());
}
[Fact]
public void TestDescendantTokensWithExtraWhitespace()
{
var s1 = " using Goo ; ";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList();
Assert.Equal(4, tokens.Count);
Assert.Equal(SyntaxKind.UsingKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind());
Assert.Equal(SyntaxKind.EndOfFileToken, tokens[3].Kind());
}
[Fact]
public void TestDescendantTokensEntireRange()
{
var s1 = "extern alias Bar;\r\n" + "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens().ToList();
Assert.Equal(8, tokens.Count);
Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[3].Kind());
Assert.Equal(SyntaxKind.UsingKeyword, tokens[4].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[5].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[6].Kind());
Assert.Equal(SyntaxKind.EndOfFileToken, tokens[7].Kind());
}
[Fact]
public void TestDescendantTokensOverFullSpan()
{
var s1 = "extern alias Bar;\r\n" + "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(0, 16)).ToList();
Assert.Equal(3, tokens.Count);
Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind());
}
[Fact]
public void TestDescendantTokensOverInsideSpan()
{
var s1 = "extern alias Bar;\r\n" + "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(1, 14)).ToList();
Assert.Equal(3, tokens.Count);
Assert.Equal(SyntaxKind.ExternKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.AliasKeyword, tokens[1].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[2].Kind());
}
[Fact]
public void TestDescendantTokensOverFullSpanOffset()
{
var s1 = "extern alias Bar;\r\n" + "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(7, 17)).ToList();
Assert.Equal(4, tokens.Count);
Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind());
Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind());
}
[Fact]
public void TestDescendantTokensOverInsideSpanOffset()
{
var s1 = "extern alias Bar;\r\n" + "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
var tokens = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(8, 15)).ToList();
Assert.Equal(4, tokens.Count);
Assert.Equal(SyntaxKind.AliasKeyword, tokens[0].Kind());
Assert.Equal(SyntaxKind.IdentifierToken, tokens[1].Kind());
Assert.Equal(SyntaxKind.SemicolonToken, tokens[2].Kind());
Assert.Equal(SyntaxKind.UsingKeyword, tokens[3].Kind());
}
[Fact]
public void TestDescendantTrivia()
{
var text = "// goo\r\na + b";
var expr = SyntaxFactory.ParseExpression(text);
var list = expr.DescendantTrivia().ToList();
Assert.Equal(4, list.Count);
Assert.Equal(SyntaxKind.SingleLineCommentTrivia, list[0].Kind());
Assert.Equal(SyntaxKind.EndOfLineTrivia, list[1].Kind());
Assert.Equal(SyntaxKind.WhitespaceTrivia, list[2].Kind());
Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind());
}
[Fact]
public void TestDescendantTriviaIntoStructuredTrivia()
{
var text = @"
/// <goo >
/// </goo>
a + b";
var expr = SyntaxFactory.ParseExpression(text);
var list = expr.DescendantTrivia(descendIntoTrivia: true).ToList();
Assert.Equal(7, list.Count);
Assert.Equal(SyntaxKind.EndOfLineTrivia, list[0].Kind());
Assert.Equal(SyntaxKind.SingleLineDocumentationCommentTrivia, list[1].Kind());
Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[2].Kind());
Assert.Equal(SyntaxKind.WhitespaceTrivia, list[3].Kind());
Assert.Equal(SyntaxKind.DocumentationCommentExteriorTrivia, list[4].Kind());
Assert.Equal(SyntaxKind.WhitespaceTrivia, list[5].Kind());
Assert.Equal(SyntaxKind.WhitespaceTrivia, list[6].Kind());
}
[Fact]
public void Bug877223()
{
var s1 = "using Goo;";
var t1 = SyntaxFactory.ParseSyntaxTree(s1);
// var node = t1.GetCompilationUnitRoot().Usings[0].GetTokens(new TextSpan(6, 3)).First();
var node = t1.GetCompilationUnitRoot().DescendantTokens(new TextSpan(6, 3)).First();
Assert.Equal("Goo", node.ToString());
}
[Fact]
public void TestFindToken()
{
var text = "class\n #if XX\n#endif\n goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
var token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length);
Assert.Equal(SyntaxKind.IdentifierToken, token.Kind());
Assert.Equal("goo", token.ToString());
token = tree.GetCompilationUnitRoot().FindToken("class\n #i".Length, findInsideTrivia: true);
Assert.Equal(SyntaxKind.IfKeyword, token.Kind());
}
[Fact]
public void TestFindTokenInLargeList()
{
var identifier = SyntaxFactory.Identifier("x");
var missingIdentifier = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken);
var name = SyntaxFactory.IdentifierName(identifier);
var missingName = SyntaxFactory.IdentifierName(missingIdentifier);
var comma = SyntaxFactory.Token(SyntaxKind.CommaToken);
var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken);
var argument = SyntaxFactory.Argument(name);
var missingArgument = SyntaxFactory.Argument(missingName);
// make a large list that has lots of zero-length nodes (that shouldn't be found)
var nodesAndTokens = SyntaxFactory.NodeOrTokenList(
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
missingArgument, missingComma,
argument);
var argumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(SyntaxFactory.NodeOrTokenList(nodesAndTokens)));
var invocation = SyntaxFactory.InvocationExpression(name, argumentList);
CheckFindToken(invocation);
}
private void CheckFindToken(SyntaxNode node)
{
for (int i = 0; i < node.FullSpan.End; i++)
{
var token = node.FindToken(i);
Assert.True(token.FullSpan.Contains(i));
}
}
[WorkItem(755236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755236")]
[Fact]
public void TestFindNode()
{
var text = "class\n #if XX\n#endif\n goo { }\n class bar { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
var root = tree.GetRoot();
Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: false));
Assert.Equal(root, root.FindNode(root.Span, findInsideTrivia: true));
var classDecl = (TypeDeclarationSyntax)root.ChildNodes().First();
// IdentifierNameSyntax in trivia.
var identifier = root.DescendantNodes(descendIntoTrivia: true).Single(n => n is IdentifierNameSyntax);
var position = identifier.Span.Start + 1;
Assert.Equal(classDecl, root.FindNode(identifier.Span, findInsideTrivia: false));
Assert.Equal(identifier, root.FindNode(identifier.Span, findInsideTrivia: true));
// Token span.
Assert.Equal(classDecl, root.FindNode(classDecl.Identifier.Span, findInsideTrivia: false));
// EOF Token span.
var EOFSpan = new TextSpan(root.FullSpan.End, 0);
Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: false));
Assert.Equal(root, root.FindNode(EOFSpan, findInsideTrivia: true));
// EOF Invalid span for childnode
var classDecl2 = (TypeDeclarationSyntax)root.ChildNodes().Last();
Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(EOFSpan));
// Check end position included in node span
var nodeEndPositionSpan = new TextSpan(classDecl.FullSpan.End, 0);
Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: false));
Assert.Equal(classDecl2, root.FindNode(nodeEndPositionSpan, findInsideTrivia: true));
Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: false));
Assert.Equal(classDecl2, classDecl2.FindNode(nodeEndPositionSpan, findInsideTrivia: true));
Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(nodeEndPositionSpan));
// Invalid spans.
var invalidSpan = new TextSpan(100, 100);
Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan));
invalidSpan = new TextSpan(root.FullSpan.End - 1, 2);
Assert.Throws<ArgumentOutOfRangeException>(() => root.FindNode(invalidSpan));
invalidSpan = new TextSpan(classDecl2.FullSpan.Start - 1, root.FullSpan.End);
Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan));
invalidSpan = new TextSpan(classDecl.FullSpan.End, root.FullSpan.End);
Assert.Throws<ArgumentOutOfRangeException>(() => classDecl2.FindNode(invalidSpan));
// Parent node's span.
Assert.Throws<ArgumentOutOfRangeException>(() => classDecl.FindNode(root.FullSpan));
}
[WorkItem(539941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539941")]
[Fact]
public void TestFindTriviaNoTriviaExistsAtPosition()
{
var code = @"class Goo
{
void Bar()
{
}
}";
var tree = SyntaxFactory.ParseSyntaxTree(code);
var position = tree.GetText().Lines[2].End - 1;
// position points to the closing parenthesis on the line that has "void Bar()"
// There should be no trivia at this position
var trivia = tree.GetCompilationUnitRoot().FindTrivia(position);
Assert.Equal(SyntaxKind.None, trivia.Kind());
Assert.Equal(0, trivia.SpanStart);
Assert.Equal(0, trivia.Span.End);
Assert.Equal(default(SyntaxTrivia), trivia);
}
[Fact]
public void TestTreeEquivalentToSelf()
{
var text = "class goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.True(tree.GetCompilationUnitRoot().IsEquivalentTo(tree.GetCompilationUnitRoot()));
}
[Fact]
public void TestTreeNotEquivalentToNull()
{
var text = "class goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.False(tree.GetCompilationUnitRoot().IsEquivalentTo(null));
}
[Fact]
public void TestTreesFromSameSourceEquivalent()
{
var text = "class goo { }";
var tree1 = SyntaxFactory.ParseSyntaxTree(text);
var tree2 = SyntaxFactory.ParseSyntaxTree(text);
Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot());
Assert.True(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot()));
}
[Fact]
public void TestDifferentTreesNotEquivalent()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }");
var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { }");
Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot());
Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot()));
}
[Fact]
public void TestVastlyDifferentTreesNotEquivalent()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { }");
var tree2 = SyntaxFactory.ParseSyntaxTree(string.Empty);
Assert.NotEqual(tree1.GetCompilationUnitRoot(), tree2.GetCompilationUnitRoot());
Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot()));
}
[Fact]
public void TestSimilarSubtreesEquivalent()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }");
var tree2 = SyntaxFactory.ParseSyntaxTree("class bar { void M() { } }");
var m1 = ((TypeDeclarationSyntax)tree1.GetCompilationUnitRoot().Members[0]).Members[0];
var m2 = ((TypeDeclarationSyntax)tree2.GetCompilationUnitRoot().Members[0]).Members[0];
Assert.Equal(SyntaxKind.MethodDeclaration, m1.Kind());
Assert.Equal(SyntaxKind.MethodDeclaration, m2.Kind());
Assert.NotEqual(m1, m2);
Assert.True(m1.IsEquivalentTo(m2));
}
[Fact]
public void TestTreesWithDifferentTriviaAreNotEquivalent()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class goo {void M() { }}");
var tree2 = SyntaxFactory.ParseSyntaxTree("class goo { void M() { } }");
Assert.False(tree1.GetCompilationUnitRoot().IsEquivalentTo(tree2.GetCompilationUnitRoot()));
}
[Fact]
public void TestNodeIncrementallyEquivalentToSelf()
{
var text = "class goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.True(tree.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot()));
}
[Fact]
public void TestTokenIncrementallyEquivalentToSelf()
{
var text = "class goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.True(tree.GetCompilationUnitRoot().EndOfFileToken.IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().EndOfFileToken));
}
[Fact]
public void TestDifferentTokensFromSameTreeNotIncrementallyEquivalentToSelf()
{
var text = "class goo { }";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.False(tree.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree.GetCompilationUnitRoot().GetFirstToken().GetNextToken()));
}
[Fact]
public void TestCachedTokensFromDifferentTreesIncrementallyEquivalentToSelf()
{
var text = "class goo { }";
var tree1 = SyntaxFactory.ParseSyntaxTree(text);
var tree2 = SyntaxFactory.ParseSyntaxTree(text);
Assert.True(tree1.GetCompilationUnitRoot().GetFirstToken().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot().GetFirstToken()));
}
[Fact]
public void TestNodesFromSameContentNotIncrementallyParsedNotIncrementallyEquivalent()
{
var text = "class goo { }";
var tree1 = SyntaxFactory.ParseSyntaxTree(text);
var tree2 = SyntaxFactory.ParseSyntaxTree(text);
Assert.False(tree1.GetCompilationUnitRoot().IsIncrementallyIdenticalTo(tree2.GetCompilationUnitRoot()));
}
[Fact]
public void TestNodesFromIncrementalParseIncrementallyEquivalent1()
{
var text = "class goo { void M() { } }";
var tree1 = SyntaxFactory.ParseSyntaxTree(text);
var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(default, " ")));
Assert.True(
tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo(
tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single()));
}
[Fact]
public void TestNodesFromIncrementalParseNotIncrementallyEquivalent1()
{
var text = "class goo { void M() { } }";
var tree1 = SyntaxFactory.ParseSyntaxTree(text);
var tree2 = tree1.WithChangedText(tree1.GetText().WithChanges(new TextChange(new TextSpan(22, 0), " return; ")));
Assert.False(
tree1.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single().IsIncrementallyIdenticalTo(
tree2.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single()));
}
[Fact, WorkItem(536664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536664")]
public void TestTriviaNodeCached()
{
var tree = SyntaxFactory.ParseSyntaxTree(" class goo {}");
// get to the trivia node
var trivia = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0];
// we get the trivia again
var triviaAgain = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia()[0];
// should NOT return two distinct objects for trivia and triviaAgain - struct now.
Assert.True(SyntaxTrivia.Equals(trivia, triviaAgain));
}
[Fact]
public void TestGetFirstToken()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var first = tree.GetCompilationUnitRoot().GetFirstToken();
Assert.Equal(SyntaxKind.PublicKeyword, first.Kind());
}
[Fact]
public void TestGetFirstTokenIncludingZeroWidth()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var first = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true);
Assert.Equal(SyntaxKind.PublicKeyword, first.Kind());
}
[Fact]
public void TestGetLastToken()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var last = tree.GetCompilationUnitRoot().GetLastToken();
Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind());
}
[Fact]
public void TestGetLastTokenIncludingZeroWidth()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { ");
var last = tree.GetCompilationUnitRoot().GetLastToken(includeZeroWidth: true);
Assert.Equal(SyntaxKind.EndOfFileToken, last.Kind());
last = tree.GetCompilationUnitRoot().Members[0].GetLastToken(includeZeroWidth: true);
Assert.Equal(SyntaxKind.CloseBraceToken, last.Kind());
Assert.True(last.IsMissing);
Assert.Equal(26, last.FullSpan.Start);
}
[Fact]
public void TestReverseChildSyntaxList()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class A {} public class B {} public static class C {}");
var root1 = tree1.GetCompilationUnitRoot();
TestReverse(root1.ChildNodesAndTokens());
TestReverse(root1.Members[0].ChildNodesAndTokens());
TestReverse(root1.Members[1].ChildNodesAndTokens());
TestReverse(root1.Members[2].ChildNodesAndTokens());
}
private void TestReverse(ChildSyntaxList children)
{
var list1 = children.AsEnumerable().Reverse().ToList();
var list2 = children.Reverse().ToList();
Assert.Equal(list1.Count, list2.Count);
for (int i = 0; i < list1.Count; i++)
{
Assert.Equal(list1[i], list2[i]);
Assert.Equal(list1[i].FullSpan.Start, list2[i].FullSpan.Start);
}
}
[Fact]
public void TestGetNextToken()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
var list = new List<SyntaxToken>();
var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetNextToken(includeSkipped: true);
}
// descendant tokens include EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetNextTokenIncludingSkippedTokens()
{
var text =
@"garbage
using goo.bar;
";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString());
var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList();
Assert.Equal(6, tokens.Count);
Assert.Equal("garbage", tokens[0].Text);
var list = new List<SyntaxToken>(tokens.Count);
var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: true);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetNextToken(includeSkipped: true);
}
Assert.Equal(tokens.Count, list.Count);
for (int i = 0; i < tokens.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetNextTokenExcludingSkippedTokens()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"garbage
using goo.bar;
");
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
Assert.Equal(6, tokens.Count);
var list = new List<SyntaxToken>(tokens.Count);
var token = tree.GetCompilationUnitRoot().GetFirstToken(includeSkipped: false);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetNextToken(includeSkipped: false);
}
// descendant tokens includes EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetNextTokenCommon()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList();
List<SyntaxToken> list = new List<SyntaxToken>();
SyntaxToken token = syntaxTree.GetRoot().GetFirstToken();
while (token.RawKind != 0)
{
list.Add(token);
token = token.GetNextToken();
}
// descendant tokens includes EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetPreviousToken()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
var list = new List<SyntaxToken>();
var token = tree.GetCompilationUnitRoot().GetLastToken(); // skip EOF
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetPreviousToken();
}
list.Reverse();
// descendant tokens includes EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetPreviousTokenIncludingSkippedTokens()
{
var text =
@"garbage
using goo.bar;
";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString());
var tokens = tree.GetCompilationUnitRoot().DescendantTokens(descendIntoTrivia: true).Where(SyntaxToken.NonZeroWidth).ToList();
Assert.Equal(6, tokens.Count);
Assert.Equal("garbage", tokens[0].Text);
var list = new List<SyntaxToken>(tokens.Count);
var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: true);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetPreviousToken(includeSkipped: true);
}
list.Reverse();
Assert.Equal(tokens.Count, list.Count);
for (int i = 0; i < tokens.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetPreviousTokenExcludingSkippedTokens()
{
var text =
@"garbage
using goo.bar;
";
var tree = SyntaxFactory.ParseSyntaxTree(text);
Assert.Equal(text, tree.GetCompilationUnitRoot().ToFullString());
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
Assert.Equal(6, tokens.Count);
var list = new List<SyntaxToken>(tokens.Count);
var token = tree.GetCompilationUnitRoot().GetLastToken(includeSkipped: false);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetPreviousToken(includeSkipped: false);
}
list.Reverse();
// descendant tokens includes EOF
Assert.Equal(tokens.Count, list.Count + 1);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(tokens[i], list[i]);
}
}
[Fact]
public void TestGetPreviousTokenCommon()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList();
List<SyntaxToken> list = new List<SyntaxToken>();
var token = syntaxTree.GetRoot().GetLastToken(includeZeroWidth: false); // skip EOF
while (token.RawKind != 0)
{
list.Add(token);
token = token.GetPreviousToken();
}
list.Reverse();
// descendant tokens include EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetNextTokenIncludingZeroWidth()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {");
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
var list = new List<SyntaxToken>();
var token = tree.GetCompilationUnitRoot().GetFirstToken(includeZeroWidth: true);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetNextToken(includeZeroWidth: true);
}
Assert.Equal(tokens.Count, list.Count);
for (int i = 0; i < tokens.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetNextTokenIncludingZeroWidthCommon()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {");
List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList();
List<SyntaxToken> list = new List<SyntaxToken>();
SyntaxToken token = syntaxTree.GetRoot().GetFirstToken(includeZeroWidth: true);
while (token.RawKind != 0)
{
list.Add(token);
token = token.GetNextToken(includeZeroWidth: true);
}
Assert.Equal(tokens.Count, list.Count);
for (int i = 0; i < tokens.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetPreviousTokenIncludingZeroWidth()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo {");
var tokens = tree.GetCompilationUnitRoot().DescendantTokens().ToList();
var list = new List<SyntaxToken>();
var token = tree.GetCompilationUnitRoot().EndOfFileToken.GetPreviousToken(includeZeroWidth: true);
while (token.Kind() != SyntaxKind.None)
{
list.Add(token);
token = token.GetPreviousToken(includeZeroWidth: true);
}
list.Reverse();
// descendant tokens include EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(list[i], tokens[i]);
}
}
[Fact]
public void TestGetPreviousTokenIncludingZeroWidthCommon()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("public static class goo {");
List<SyntaxToken> tokens = syntaxTree.GetRoot().DescendantTokens().ToList();
List<SyntaxToken> list = new List<SyntaxToken>();
SyntaxToken token = ((SyntaxToken)((SyntaxTree)syntaxTree).GetCompilationUnitRoot().EndOfFileToken).GetPreviousToken(includeZeroWidth: true);
while (token.RawKind != 0)
{
list.Add(token);
token = token.GetPreviousToken(includeZeroWidth: true);
}
list.Reverse();
// descendant tokens includes EOF
Assert.Equal(tokens.Count - 1, list.Count);
for (int i = 0; i < list.Count; i++)
{
Assert.Equal(tokens[i], list[i]);
}
}
[Fact]
public void TestGetNextSibling()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList();
var list = new List<SyntaxNodeOrToken>();
for (var child = children[0]; child.Kind() != SyntaxKind.None; child = child.GetNextSibling())
{
list.Add(child);
}
Assert.Equal(children.Count, list.Count);
for (int i = 0; i < children.Count; i++)
{
Assert.Equal(list[i], children[i]);
}
}
[Fact]
public void TestGetPreviousSibling()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var children = tree.GetCompilationUnitRoot().Members[0].ChildNodesAndTokens().ToList();
var reversed = children.AsEnumerable().Reverse().ToList();
var list = new List<SyntaxNodeOrToken>();
for (var child = children[children.Count - 1]; child.Kind() != SyntaxKind.None; child = child.GetPreviousSibling())
{
list.Add(child);
}
Assert.Equal(children.Count, list.Count);
for (int i = 0; i < reversed.Count; i++)
{
Assert.Equal(list[i], reversed[i]);
}
}
[Fact]
public void TestSyntaxNodeOrTokenEquality()
{
var tree = SyntaxFactory.ParseSyntaxTree("public static class goo { }");
var child = tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0];
var member = (TypeDeclarationSyntax)tree.GetCompilationUnitRoot().Members[0];
Assert.Equal((SyntaxNodeOrToken)member, child);
var name = member.Identifier;
var nameChild = member.ChildNodesAndTokens()[3];
Assert.Equal((SyntaxNodeOrToken)name, nameChild);
var closeBraceToken = member.CloseBraceToken;
var closeBraceChild = member.GetLastToken();
Assert.Equal((SyntaxNodeOrToken)closeBraceToken, closeBraceChild);
}
[Fact]
public void TestStructuredTriviaHasNoParent()
{
var tree = SyntaxFactory.ParseSyntaxTree("#define GOO");
var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0];
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind());
Assert.True(trivia.HasStructure);
Assert.NotNull(trivia.GetStructure());
Assert.Null(trivia.GetStructure().Parent);
}
[Fact]
public void TestStructuredTriviaHasParentTrivia()
{
var tree = SyntaxFactory.ParseSyntaxTree("#define GOO");
var trivia = tree.GetCompilationUnitRoot().EndOfFileToken.GetLeadingTrivia()[0];
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, trivia.Kind());
Assert.True(trivia.HasStructure);
Assert.NotNull(trivia.GetStructure());
var parentTrivia = trivia.GetStructure().ParentTrivia;
Assert.NotEqual(SyntaxKind.None, parentTrivia.Kind());
Assert.Equal(trivia, parentTrivia);
}
[Fact]
public void TestStructuredTriviaParentTrivia()
{
var def = SyntaxFactory.DefineDirectiveTrivia(SyntaxFactory.Identifier("GOO"), false);
// unrooted structured trivia should report parent trivia as default
Assert.Equal(default(SyntaxTrivia), def.ParentTrivia);
var trivia = SyntaxFactory.Trivia(def);
var structure = trivia.GetStructure();
Assert.NotEqual(def, structure); // these should not be identity equals
Assert.True(def.IsEquivalentTo(structure)); // they should be equivalent though
Assert.Equal(trivia, structure.ParentTrivia); // parent trivia should be equal to original trivia
// attach trivia to token and walk down to structured trivia and back up again
var token = SyntaxFactory.Identifier(default(SyntaxTriviaList), "x", SyntaxTriviaList.Create(trivia));
var tokenTrivia = token.TrailingTrivia[0];
var tokenStructuredTrivia = tokenTrivia.GetStructure();
var tokenStructuredParentTrivia = tokenStructuredTrivia.ParentTrivia;
Assert.Equal(tokenTrivia, tokenStructuredParentTrivia);
Assert.Equal(token, tokenStructuredParentTrivia.Token);
}
[Fact]
public void TestGetFirstDirective()
{
var tree = SyntaxFactory.ParseSyntaxTree("#define GOO");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind());
}
[Fact]
public void TestGetLastDirective()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#undef GOO
");
var d = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.UndefDirectiveTrivia, d.Kind());
}
[Fact]
public void TestGetNextDirective()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#define BAR
class C {
#if GOO
void M() { }
#endif
}
");
var d1 = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d1);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d1.Kind());
var d2 = d1.GetNextDirective();
Assert.NotNull(d2);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d2.Kind());
var d3 = d2.GetNextDirective();
Assert.NotNull(d3);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d3.Kind());
var d4 = d3.GetNextDirective();
Assert.NotNull(d4);
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d4.Kind());
var d5 = d4.GetNextDirective();
Assert.Null(d5);
}
[Fact]
public void TestGetPreviousDirective()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#define BAR
class C {
#if GOO
void M() { }
#endif
}
");
var d1 = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d1);
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d1.Kind());
var d2 = d1.GetPreviousDirective();
Assert.NotNull(d2);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d2.Kind());
var d3 = d2.GetPreviousDirective();
Assert.NotNull(d3);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d3.Kind());
var d4 = d3.GetPreviousDirective();
Assert.NotNull(d4);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d4.Kind());
var d5 = d4.GetPreviousDirective();
Assert.Null(d5);
}
[Fact]
public void TestGetDirectivesRelatedToIf()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind());
d = d.GetNextDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToIfElements()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind());
d = d.GetNextDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
// get directives related to elif
var related2 = related[1].GetRelatedDirectives();
Assert.True(related.SequenceEqual(related2));
// get directives related to else
var related3 = related[3].GetRelatedDirectives();
Assert.True(related.SequenceEqual(related3));
}
[Fact]
public void TestGetDirectivesRelatedToEndIf()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToIfWithNestedIfEndIF()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#if ZED
class A1 { }
#endif
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind());
d = d.GetNextDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToIfWithNestedRegionEndRegion()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#region some region
class A1 { }
#endregion
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.DefineDirectiveTrivia, d.Kind());
d = d.GetNextDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToEndIfWithNestedIfEndIf()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
class A { }
#if ZED
class A1 { }
#endif
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToEndIfWithNestedRegionEndRegion()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#define GOO
#if GOO
#region some region
class A { }
#endregion
#elif BAR
class B { }
#elif BAZ
class B { }
#else
class C { }
#endif
");
var d = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(5, related.Count);
Assert.Equal(SyntaxKind.IfDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[1].Kind());
Assert.Equal(SyntaxKind.ElifDirectiveTrivia, related[2].Kind());
Assert.Equal(SyntaxKind.ElseDirectiveTrivia, related[3].Kind());
Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, related[4].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToRegion()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"#region Some Region
class A { }
#endregion
#if GOO
#endif
");
var d = tree.GetCompilationUnitRoot().GetFirstDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.RegionDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(2, related.Count);
Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind());
}
[Fact]
public void TestGetDirectivesRelatedToEndRegion()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"
#if GOO
#endif
#region Some Region
class A { }
#endregion
");
var d = tree.GetCompilationUnitRoot().GetLastDirective();
Assert.NotNull(d);
Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, d.Kind());
var related = d.GetRelatedDirectives();
Assert.NotNull(related);
Assert.Equal(2, related.Count);
Assert.Equal(SyntaxKind.RegionDirectiveTrivia, related[0].Kind());
Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, related[1].Kind());
}
[WorkItem(536995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536995")]
[Fact]
public void TestTextAndSpanWithTrivia1()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"/*START*/namespace Microsoft.CSharp.Test
{
}/*END*/");
var rootNode = tree.GetCompilationUnitRoot();
Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length);
Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length);
Assert.True(rootNode.ToString().Contains("/*END*/"));
Assert.False(rootNode.ToString().Contains("/*START*/"));
}
[WorkItem(536996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536996")]
[Fact]
public void TestTextAndSpanWithTrivia2()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"/*START*/
namespace Microsoft.CSharp.Test
{
}
/*END*/");
var rootNode = tree.GetCompilationUnitRoot();
Assert.Equal(rootNode.FullSpan.Length, rootNode.ToFullString().Length);
Assert.Equal(rootNode.Span.Length, rootNode.ToString().Length);
Assert.True(rootNode.ToString().Contains("/*END*/"));
Assert.False(rootNode.ToString().Contains("/*START*/"));
}
[Fact]
public void TestCreateCommonSyntaxNode()
{
var rootNode = SyntaxFactory.ParseSyntaxTree("using X; namespace Y { }").GetCompilationUnitRoot();
var namespaceNode = rootNode.ChildNodesAndTokens()[1].AsNode();
var nodeOrToken = (SyntaxNodeOrToken)namespaceNode;
Assert.True(nodeOrToken.IsNode);
Assert.Equal(namespaceNode, nodeOrToken.AsNode());
Assert.Equal(rootNode, nodeOrToken.Parent);
Assert.Equal(namespaceNode.FullSpan, nodeOrToken.FullSpan);
Assert.Equal(namespaceNode.Span, nodeOrToken.Span);
}
[Fact, WorkItem(537070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537070")]
public void TestTraversalUsingCommonSyntaxNodeOrToken()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(@"class c1
{
}");
var nodeOrToken = (SyntaxNodeOrToken)syntaxTree.GetRoot();
Assert.Equal(0, syntaxTree.GetDiagnostics().Count());
Action<SyntaxNodeOrToken> walk = null;
walk = (SyntaxNodeOrToken nOrT) =>
{
Assert.Equal(0, syntaxTree.GetDiagnostics(nOrT).Count());
foreach (var child in nOrT.ChildNodesAndTokens())
{
walk(child);
}
};
walk(nodeOrToken);
}
[WorkItem(537747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537747")]
[Fact]
public void SyntaxTriviaDefaultIsDirective()
{
SyntaxTrivia trivia = new SyntaxTrivia();
Assert.False(trivia.IsDirective);
}
[Fact]
public void SyntaxNames()
{
var cc = SyntaxFactory.Token(SyntaxKind.ColonColonToken);
var lt = SyntaxFactory.Token(SyntaxKind.LessThanToken);
var gt = SyntaxFactory.Token(SyntaxKind.GreaterThanToken);
var dot = SyntaxFactory.Token(SyntaxKind.DotToken);
var gp = SyntaxFactory.SingletonSeparatedList<TypeSyntax>(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)));
var externAlias = SyntaxFactory.IdentifierName("alias");
var goo = SyntaxFactory.IdentifierName("Goo");
var bar = SyntaxFactory.IdentifierName("Bar");
// Goo.Bar
var qualified = SyntaxFactory.QualifiedName(goo, dot, bar);
Assert.Equal("Goo.Bar", qualified.ToString());
Assert.Equal("Bar", qualified.GetUnqualifiedName().Identifier.ValueText);
// Bar<int>
var generic = SyntaxFactory.GenericName(bar.Identifier, SyntaxFactory.TypeArgumentList(lt, gp, gt));
Assert.Equal("Bar<int>", generic.ToString());
Assert.Equal("Bar", generic.GetUnqualifiedName().Identifier.ValueText);
// Goo.Bar<int>
var qualifiedGeneric = SyntaxFactory.QualifiedName(goo, dot, generic);
Assert.Equal("Goo.Bar<int>", qualifiedGeneric.ToString());
Assert.Equal("Bar", qualifiedGeneric.GetUnqualifiedName().Identifier.ValueText);
// alias::Goo
var alias = SyntaxFactory.AliasQualifiedName(externAlias, cc, goo);
Assert.Equal("alias::Goo", alias.ToString());
Assert.Equal("Goo", alias.GetUnqualifiedName().Identifier.ValueText);
// alias::Bar<int>
var aliasGeneric = SyntaxFactory.AliasQualifiedName(externAlias, cc, generic);
Assert.Equal("alias::Bar<int>", aliasGeneric.ToString());
Assert.Equal("Bar", aliasGeneric.GetUnqualifiedName().Identifier.ValueText);
// alias::Goo.Bar
var aliasQualified = SyntaxFactory.QualifiedName(alias, dot, bar);
Assert.Equal("alias::Goo.Bar", aliasQualified.ToString());
Assert.Equal("Bar", aliasQualified.GetUnqualifiedName().Identifier.ValueText);
// alias::Goo.Bar<int>
var aliasQualifiedGeneric = SyntaxFactory.QualifiedName(alias, dot, generic);
Assert.Equal("alias::Goo.Bar<int>", aliasQualifiedGeneric.ToString());
Assert.Equal("Bar", aliasQualifiedGeneric.GetUnqualifiedName().Identifier.ValueText);
}
[Fact]
public void ZeroWidthTokensInListAreUnique()
{
var someToken = SyntaxFactory.MissingToken(SyntaxKind.IntKeyword);
var list = SyntaxFactory.TokenList(someToken, someToken);
Assert.Equal(someToken, someToken);
Assert.NotEqual(list[0], list[1]);
}
[Fact]
public void ZeroWidthTokensInParentAreUnique()
{
var missingComma = SyntaxFactory.MissingToken(SyntaxKind.CommaToken);
var omittedArraySize = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken));
var spec = SyntaxFactory.ArrayRankSpecifier(
SyntaxFactory.Token(SyntaxKind.OpenBracketToken),
SyntaxFactory.SeparatedList<ExpressionSyntax>(new SyntaxNodeOrToken[] { omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize, missingComma, omittedArraySize }),
SyntaxFactory.Token(SyntaxKind.CloseBracketToken)
);
var sizes = spec.Sizes;
Assert.Equal(4, sizes.Count);
Assert.Equal(3, sizes.SeparatorCount);
Assert.NotEqual(sizes[0], sizes[1]);
Assert.NotEqual(sizes[0], sizes[2]);
Assert.NotEqual(sizes[0], sizes[3]);
Assert.NotEqual(sizes[1], sizes[2]);
Assert.NotEqual(sizes[1], sizes[3]);
Assert.NotEqual(sizes[2], sizes[3]);
Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(1));
Assert.NotEqual(sizes.GetSeparator(0), sizes.GetSeparator(2));
Assert.NotEqual(sizes.GetSeparator(1), sizes.GetSeparator(2));
}
[Fact]
public void ZeroWidthStructuredTrivia()
{
// create zero width structured trivia (not sure how these come about but its not impossible)
var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false);
Assert.Equal(0, zeroWidth.Width);
// create token with more than one instance of same zero width structured trivia!
var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "goo", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth)));
// create node with this token
var someNode = SyntaxFactory.IdentifierName(someToken);
Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count);
Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure);
Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure);
// prove that trivia have different identity
Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1]));
var tt0 = someNode.Identifier.TrailingTrivia[0];
var tt1 = someNode.Identifier.TrailingTrivia[1];
var str0 = tt0.GetStructure();
var str1 = tt1.GetStructure();
// prove that structures have different identity
Assert.NotEqual(str0, str1);
// prove that structured trivia can get back to original trivia with correct identity
var tr0 = str0.ParentTrivia;
Assert.Equal(tt0, tr0);
var tr1 = str1.ParentTrivia;
Assert.Equal(tt1, tr1);
}
[Fact]
public void ZeroWidthStructuredTriviaOnZeroWidthToken()
{
// create zero width structured trivia (not sure how these come about but its not impossible)
var zeroWidth = SyntaxFactory.ElseDirectiveTrivia(SyntaxFactory.MissingToken(SyntaxKind.HashToken), SyntaxFactory.MissingToken(SyntaxKind.ElseKeyword), SyntaxFactory.MissingToken(SyntaxKind.EndOfDirectiveToken), false, false);
Assert.Equal(0, zeroWidth.Width);
// create token with more than one instance of same zero width structured trivia!
var someToken = SyntaxFactory.Identifier(default(SyntaxTriviaList), "", SyntaxFactory.TriviaList(SyntaxFactory.Trivia(zeroWidth), SyntaxFactory.Trivia(zeroWidth)));
// create node with this token
var someNode = SyntaxFactory.IdentifierName(someToken);
Assert.Equal(2, someNode.Identifier.TrailingTrivia.Count);
Assert.True(someNode.Identifier.TrailingTrivia[0].HasStructure);
Assert.True(someNode.Identifier.TrailingTrivia[1].HasStructure);
// prove that trivia have different identity
Assert.False(someNode.Identifier.TrailingTrivia[0].Equals(someNode.Identifier.TrailingTrivia[1]));
var tt0 = someNode.Identifier.TrailingTrivia[0];
var tt1 = someNode.Identifier.TrailingTrivia[1];
var str0 = tt0.GetStructure();
var str1 = tt1.GetStructure();
// prove that structures have different identity
Assert.NotEqual(str0, str1);
// prove that structured trivia can get back to original trivia with correct identity
var tr0 = str0.ParentTrivia;
Assert.Equal(tt0, tr0);
var tr1 = str1.ParentTrivia;
Assert.Equal(tt1, tr1);
}
[WorkItem(537059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537059")]
[Fact]
public void TestIncompleteDeclWithDotToken()
{
var tree = SyntaxFactory.ParseSyntaxTree(
@"
class Test
{
int IX.GOO
");
// Verify the kind of the CSharpSyntaxNode "int IX.GOO" is MethodDeclaration and NOT FieldDeclaration
Assert.Equal(SyntaxKind.MethodDeclaration, tree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].ChildNodesAndTokens()[3].Kind());
}
[WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")]
[Fact]
public void TestGetTokensLanguageAny()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}");
var actualTokens = syntaxTree.GetCompilationUnitRoot().DescendantTokens();
var expectedTokenKinds = new SyntaxKind[]
{
SyntaxKind.ClassKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenBraceToken,
SyntaxKind.CloseBraceToken,
SyntaxKind.EndOfFileToken,
};
Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug
Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => t.Kind())));
}
[WorkItem(538360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538360")]
[Fact]
public void TestGetTokensCommonAny()
{
SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("class C {}");
var actualTokens = syntaxTree.GetRoot().DescendantTokens(syntaxTree.GetRoot().FullSpan);
var expectedTokenKinds = new SyntaxKind[]
{
SyntaxKind.ClassKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenBraceToken,
SyntaxKind.CloseBraceToken,
SyntaxKind.EndOfFileToken,
};
Assert.Equal(expectedTokenKinds.Count(), actualTokens.Count()); //redundant but helps debug
Assert.True(expectedTokenKinds.SequenceEqual(actualTokens.Select(t => (SyntaxKind)t.RawKind)));
}
[Fact]
public void TestGetLocation()
{
var tree = SyntaxFactory.ParseSyntaxTree("class C { void F() { } }");
dynamic root = tree.GetCompilationUnitRoot();
MethodDeclarationSyntax method = root.Members[0].Members[0];
var nodeLocation = method.GetLocation();
Assert.True(nodeLocation.IsInSource);
Assert.Equal(tree, nodeLocation.SourceTree);
Assert.Equal(method.Span, nodeLocation.SourceSpan);
var tokenLocation = method.Identifier.GetLocation();
Assert.True(tokenLocation.IsInSource);
Assert.Equal(tree, tokenLocation.SourceTree);
Assert.Equal(method.Identifier.Span, tokenLocation.SourceSpan);
var triviaLocation = method.ReturnType.GetLastToken().TrailingTrivia[0].GetLocation();
Assert.True(triviaLocation.IsInSource);
Assert.Equal(tree, triviaLocation.SourceTree);
Assert.Equal(method.ReturnType.GetLastToken().TrailingTrivia[0].Span, triviaLocation.SourceSpan);
var textSpan = new TextSpan(5, 10);
var spanLocation = tree.GetLocation(textSpan);
Assert.True(spanLocation.IsInSource);
Assert.Equal(tree, spanLocation.SourceTree);
Assert.Equal(textSpan, spanLocation.SourceSpan);
}
[Fact]
public void TestReplaceNode()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var bex = (BinaryExpressionSyntax)expr;
var expr2 = bex.ReplaceNode(bex.Right, SyntaxFactory.ParseExpression("c"));
Assert.Equal("a + c", expr2.ToFullString());
}
[Fact]
public void TestReplaceNodes()
{
var expr = SyntaxFactory.ParseExpression("a + b + c + d");
// replace each expression with a parenthesized expression
var replaced = expr.ReplaceNodes(
expr.DescendantNodes().OfType<ExpressionSyntax>(),
(node, rewritten) => SyntaxFactory.ParenthesizedExpression(rewritten));
var replacedText = replaced.ToFullString();
Assert.Equal("(((a )+ (b ))+ (c ))+ (d)", replacedText);
}
[Fact]
public void TestReplaceNodeInListWithMultiple()
{
var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)");
var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c"));
var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d"));
// replace first with multiple
var newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD });
Assert.Equal("m(c,d, b)", newNode.ToFullString());
// replace last with multiple
newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD });
Assert.Equal("m(a, c,d)", newNode.ToFullString());
// replace first with empty list
newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { });
Assert.Equal("m(b)", newNode.ToFullString());
// replace last with empty list
newNode = invocation.ReplaceNode(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { });
Assert.Equal("m(a)", newNode.ToFullString());
}
[Fact]
public void TestReplaceNonListNodeWithMultiple()
{
var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)");
var then = ifstatement.Statement;
var stat1 = SyntaxFactory.ParseStatement("m1(x)");
var stat2 = SyntaxFactory.ParseStatement("m2(y)");
// you cannot replace a node that is a single node member with multiple nodes
Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new[] { stat1, stat2 }));
// you cannot replace a node that is a single node member with an empty list
Assert.Throws<InvalidOperationException>(() => ifstatement.ReplaceNode(then, new StatementSyntax[] { }));
}
[Fact]
public void TestInsertNodesInList()
{
var invocation = (InvocationExpressionSyntax)SyntaxFactory.ParseExpression("m(a, b)");
var argC = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c"));
var argD = SyntaxFactory.Argument(SyntaxFactory.ParseExpression("d"));
// insert before first
var newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD });
Assert.Equal("m(c,d,a, b)", newNode.ToFullString());
// insert after first
newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[0], new SyntaxNode[] { argC, argD });
Assert.Equal("m(a,c,d, b)", newNode.ToFullString());
// insert before last
newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD });
Assert.Equal("m(a,c,d, b)", newNode.ToFullString());
// insert after last
newNode = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments[1], new SyntaxNode[] { argC, argD });
Assert.Equal("m(a, b,c,d)", newNode.ToFullString());
}
[Fact]
public void TestInsertNodesRelativeToNonListNode()
{
var ifstatement = (IfStatementSyntax)SyntaxFactory.ParseStatement("if (a < b) m(c)");
var then = ifstatement.Statement;
var stat1 = SyntaxFactory.ParseStatement("m1(x)");
var stat2 = SyntaxFactory.ParseStatement("m2(y)");
// you cannot insert nodes before/after a node that is not part of a list
Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesBefore(then, new[] { stat1, stat2 }));
// you cannot insert nodes before/after a node that is not part of a list
Assert.Throws<InvalidOperationException>(() => ifstatement.InsertNodesAfter(then, new StatementSyntax[] { }));
}
[Fact]
public void TestReplaceStatementInListWithMultiple()
{
var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }");
var stmt1 = SyntaxFactory.ParseStatement("var z = 30; ");
var stmt2 = SyntaxFactory.ParseStatement("var q = 40; ");
// replace first with multiple
var newBlock = block.ReplaceNode(block.Statements[0], new[] { stmt1, stmt2 });
Assert.Equal("{ var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString());
// replace second with multiple
newBlock = block.ReplaceNode(block.Statements[1], new[] { stmt1, stmt2 });
Assert.Equal("{ var x = 10; var z = 30; var q = 40; }", newBlock.ToFullString());
// replace first with empty list
newBlock = block.ReplaceNode(block.Statements[0], new SyntaxNode[] { });
Assert.Equal("{ var y = 20; }", newBlock.ToFullString());
// replace second with empty list
newBlock = block.ReplaceNode(block.Statements[1], new SyntaxNode[] { });
Assert.Equal("{ var x = 10; }", newBlock.ToFullString());
}
[Fact]
public void TestInsertStatementsInList()
{
var block = (BlockSyntax)SyntaxFactory.ParseStatement("{ var x = 10; var y = 20; }");
var stmt1 = SyntaxFactory.ParseStatement("var z = 30; ");
var stmt2 = SyntaxFactory.ParseStatement("var q = 40; ");
// insert before first
var newBlock = block.InsertNodesBefore(block.Statements[0], new[] { stmt1, stmt2 });
Assert.Equal("{ var z = 30; var q = 40; var x = 10; var y = 20; }", newBlock.ToFullString());
// insert after first
newBlock = block.InsertNodesAfter(block.Statements[0], new[] { stmt1, stmt2 });
Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString());
// insert before last
newBlock = block.InsertNodesBefore(block.Statements[1], new[] { stmt1, stmt2 });
Assert.Equal("{ var x = 10; var z = 30; var q = 40; var y = 20; }", newBlock.ToFullString());
// insert after last
newBlock = block.InsertNodesAfter(block.Statements[1], new[] { stmt1, stmt2 });
Assert.Equal("{ var x = 10; var y = 20; var z = 30; var q = 40; }", newBlock.ToFullString());
}
[Fact]
public void TestReplaceSingleToken()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var bToken = expr.DescendantTokens().First(t => t.Text == "b");
var expr2 = expr.ReplaceToken(bToken, SyntaxFactory.ParseToken("c"));
Assert.Equal("a + c", expr2.ToString());
}
[Fact]
public void TestReplaceMultipleTokens()
{
var expr = SyntaxFactory.ParseExpression("a + b + c");
var d = SyntaxFactory.ParseToken("d ");
var tokens = expr.DescendantTokens().Where(t => t.IsKind(SyntaxKind.IdentifierToken)).ToList();
var replaced = expr.ReplaceTokens(tokens, (tok, tok2) => d);
Assert.Equal("d + d + d ", replaced.ToFullString());
}
[Fact]
public void TestReplaceSingleTokenWithMultipleTokens()
{
var cu = SyntaxFactory.ParseCompilationUnit("private class C { }");
var privateToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0];
var publicToken = SyntaxFactory.ParseToken("public ");
var partialToken = SyntaxFactory.ParseToken("partial ");
var cu1 = cu.ReplaceToken(privateToken, publicToken);
Assert.Equal("public class C { }", cu1.ToFullString());
var cu2 = cu.ReplaceToken(privateToken, new[] { publicToken, partialToken });
Assert.Equal("public partial class C { }", cu2.ToFullString());
var cu3 = cu.ReplaceToken(privateToken, new SyntaxToken[] { });
Assert.Equal("class C { }", cu3.ToFullString());
}
[Fact]
public void TestReplaceNonListTokenWithMultipleTokensFails()
{
var cu = SyntaxFactory.ParseCompilationUnit("private class C { }");
var identifierC = cu.DescendantTokens().First(t => t.Text == "C");
var identifierA = SyntaxFactory.ParseToken("A");
var identifierB = SyntaxFactory.ParseToken("B");
// you cannot replace a token that is a single token member with multiple tokens
Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new[] { identifierA, identifierB }));
// you cannot replace a token that is a single token member with an empty list of tokens
Assert.Throws<InvalidOperationException>(() => cu.ReplaceToken(identifierC, new SyntaxToken[] { }));
}
[Fact]
public void TestInsertTokens()
{
var cu = SyntaxFactory.ParseCompilationUnit("public class C { }");
var publicToken = ((ClassDeclarationSyntax)cu.Members[0]).Modifiers[0];
var partialToken = SyntaxFactory.ParseToken("partial ");
var staticToken = SyntaxFactory.ParseToken("static ");
var cu1 = cu.InsertTokensBefore(publicToken, new[] { staticToken });
Assert.Equal("static public class C { }", cu1.ToFullString());
var cu2 = cu.InsertTokensAfter(publicToken, new[] { staticToken });
Assert.Equal("public static class C { }", cu2.ToFullString());
}
[Fact]
public void TestInsertTokensRelativeToNonListToken()
{
var cu = SyntaxFactory.ParseCompilationUnit("public class C { }");
var identifierC = cu.DescendantTokens().First(t => t.Text == "C");
var identifierA = SyntaxFactory.ParseToken("A");
var identifierB = SyntaxFactory.ParseToken("B");
// you cannot insert a token before/after a token that is not part of a list of tokens
Assert.Throws<InvalidOperationException>(() => cu.InsertTokensBefore(identifierC, new[] { identifierA, identifierB }));
// you cannot insert a token before/after a token that is not part of a list of tokens
Assert.Throws<InvalidOperationException>(() => cu.InsertTokensAfter(identifierC, new[] { identifierA, identifierB }));
}
[Fact]
public void ReplaceMissingToken()
{
var text = "return x";
var expr = SyntaxFactory.ParseStatement(text);
var token = expr.DescendantTokens().First(t => t.IsMissing);
var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(token.Kind()));
var text2 = expr2.ToFullString();
Assert.Equal("return x;", text2);
}
[Fact]
public void ReplaceEndOfCommentToken()
{
var text = "/// Goo\r\n return x;";
var expr = SyntaxFactory.ParseStatement(text);
var tokens = expr.DescendantTokens(descendIntoTrivia: true).ToList();
var token = tokens.First(t => t.Kind() == SyntaxKind.EndOfDocumentationCommentToken);
var expr2 = expr.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace("garbage")), token.Kind(), default(SyntaxTriviaList)));
var text2 = expr2.ToFullString();
Assert.Equal("/// Goo\r\ngarbage return x;", text2);
}
[Fact]
public void ReplaceEndOfFileToken()
{
var text = "";
var cu = SyntaxFactory.ParseCompilationUnit(text);
var token = cu.DescendantTokens().Single(t => t.Kind() == SyntaxKind.EndOfFileToken);
var cu2 = cu.ReplaceToken(token, SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.Whitespace(" ")), token.Kind(), default(SyntaxTriviaList)));
var text2 = cu2.ToFullString();
Assert.Equal(" ", text2);
}
[Fact]
public void TestReplaceTriviaDeep()
{
var expr = SyntaxFactory.ParseExpression("#if true\r\na + \r\n#endif\r\n + b");
// get whitespace trivia inside structured directive trivia
var deepTrivia = expr.GetDirectives().SelectMany(d => d.DescendantTrivia().Where(tr => tr.Kind() == SyntaxKind.WhitespaceTrivia)).ToList();
// replace deep trivia with double-whitespace trivia
var twoSpace = SyntaxFactory.Whitespace(" ");
var expr2 = expr.ReplaceTrivia(deepTrivia, (tr, tr2) => twoSpace);
Assert.Equal("#if true\r\na + \r\n#endif\r\n + b", expr2.ToFullString());
}
[Fact]
public void TestReplaceSingleTriviaInNode()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var trivia = expr.DescendantTokens().First(t => t.Text == "a").TrailingTrivia[0];
var twoSpaces = SyntaxFactory.Whitespace(" ");
var expr2 = expr.ReplaceTrivia(trivia, twoSpaces);
Assert.Equal("a + b", expr2.ToFullString());
}
[Fact]
public void TestReplaceMultipleTriviaInNode()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var twoSpaces = SyntaxFactory.Whitespace(" ");
var trivia = expr.DescendantTrivia().Where(tr => tr.IsKind(SyntaxKind.WhitespaceTrivia)).ToList();
var replaced = expr.ReplaceTrivia(trivia, (tr, tr2) => twoSpaces);
Assert.Equal("a + b", replaced.ToFullString());
}
[Fact]
public void TestReplaceSingleTriviaWithMultipleTriviaInNode()
{
var ex = SyntaxFactory.ParseExpression("/* c */ identifier");
var leadingTrivia = ex.GetLeadingTrivia();
Assert.Equal(2, leadingTrivia.Count);
var comment1 = leadingTrivia[0];
Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind());
var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0];
var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0];
var ex1 = ex.ReplaceTrivia(comment1, newComment1);
Assert.Equal("/* a */ identifier", ex1.ToFullString());
var ex2 = ex.ReplaceTrivia(comment1, new[] { newComment1, newComment2 });
Assert.Equal("/* a *//* b */ identifier", ex2.ToFullString());
var ex3 = ex.ReplaceTrivia(comment1, new SyntaxTrivia[] { });
Assert.Equal(" identifier", ex3.ToFullString());
}
[Fact]
public void TestInsertTriviaInNode()
{
var ex = SyntaxFactory.ParseExpression("/* c */ identifier");
var leadingTrivia = ex.GetLeadingTrivia();
Assert.Equal(2, leadingTrivia.Count);
var comment1 = leadingTrivia[0];
Assert.Equal(SyntaxKind.MultiLineCommentTrivia, comment1.Kind());
var newComment1 = SyntaxFactory.ParseLeadingTrivia("/* a */")[0];
var newComment2 = SyntaxFactory.ParseLeadingTrivia("/* b */")[0];
var ex1 = ex.InsertTriviaBefore(comment1, new[] { newComment1, newComment2 });
Assert.Equal("/* a *//* b *//* c */ identifier", ex1.ToFullString());
var ex2 = ex.InsertTriviaAfter(comment1, new[] { newComment1, newComment2 });
Assert.Equal("/* c *//* a *//* b */ identifier", ex2.ToFullString());
}
[Fact]
public void TestReplaceSingleTriviaInToken()
{
var id = SyntaxFactory.ParseToken("a ");
var trivia = id.TrailingTrivia[0];
var twoSpace = SyntaxFactory.Whitespace(" ");
var id2 = id.ReplaceTrivia(trivia, twoSpace);
Assert.Equal("a ", id2.ToFullString());
}
[Fact]
public void TestReplaceMultipleTriviaInToken()
{
var id = SyntaxFactory.ParseToken("a // goo\r\n");
// replace each trivia with a single space
var id2 = id.ReplaceTrivia(id.GetAllTrivia(), (tr, tr2) => SyntaxFactory.Space);
// should be 3 spaces (one for original space, comment and end-of-line)
Assert.Equal("a ", id2.ToFullString());
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia()
{
var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal("m(a , /* trivia */ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_2()
{
var expr = SyntaxFactory.ParseExpression(@"m(a, b, /* trivia */
c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"m(a, /* trivia */
c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_3()
{
var expr = SyntaxFactory.ParseExpression(@"m(a, b,
/* trivia */ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"m(a,
/* trivia */ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_4()
{
var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a,
/*arg2:*/ b,
/*arg3:*/ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"SomeMethod(/*arg1:*/ a,
/*arg2:*/
/*arg3:*/ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepExteriorTrivia_5()
{
var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a
a,
// some comment about b
b,
// some comment about c
c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"SomeMethod(// comment about a
a,
// some comment about b
// some comment about c
c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepNoTrivia()
{
var expr = SyntaxFactory.ParseExpression("m(a, b, /* trivia */ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal("m(a, /* trivia */ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepNoTrivia_2()
{
var expr = SyntaxFactory.ParseExpression(
@"m(a, b, /* trivia */
c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"m(a, c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepNoTrivia_3()
{
var expr = SyntaxFactory.ParseExpression(
@"m(a, b,
/* trivia */ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"m(a, /* trivia */ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepNoTrivia_4()
{
var expr = SyntaxFactory.ParseExpression(@"SomeMethod(/*arg1:*/ a,
/*arg2:*/ b,
/*arg3:*/ c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"SomeMethod(/*arg1:*/ a,
/*arg3:*/ c)", text);
}
[Fact]
public void TestRemoveNodeInSeparatedList_KeepNoTrivia_5()
{
var expr = SyntaxFactory.ParseExpression(@"SomeMethod(// comment about a
a,
// some comment about b
b,
// some comment about c
c)");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal(@"SomeMethod(// comment about a
a,
// some comment about c
c)", text);
}
[Fact]
public void TestRemoveOnlyNodeInSeparatedList_KeepExteriorTrivia()
{
var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */)");
var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(n);
var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal("m(/* before */ /* after */)", text);
}
[Fact]
public void TestRemoveFirstNodeInSeparatedList_KeepExteriorTrivia()
{
var expr = SyntaxFactory.ParseExpression("m(/* before */ a /* after */, b, c)");
var n = expr.DescendantTokens().Where(t => t.Text == "a").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(n);
var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal("m(/* before */ /* after */ b, c)", text);
}
[Fact]
public void TestRemoveLastNodeInSeparatedList_KeepExteriorTrivia()
{
var expr = SyntaxFactory.ParseExpression("m(a, b, /* before */ c /* after */)");
var n = expr.DescendantTokens().Where(t => t.Text == "c").Select(t => t.Parent.FirstAncestorOrSelf<ArgumentSyntax>()).FirstOrDefault();
Assert.NotNull(n);
var expr2 = expr.RemoveNode(n, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal("m(a, b /* before */ /* after */)", text);
}
[Fact]
public void TestRemoveNode_KeepNoTrivia()
{
var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepNoTrivia);
var text = expr2.ToFullString();
Assert.Equal("{ a; c }", text);
}
[Fact]
public void TestRemoveNode_KeepExteriorTrivia()
{
var expr = SyntaxFactory.ParseStatement("{ a; b; /* trivia */ c }");
var b = expr.DescendantTokens().Where(t => t.Text == "b").Select(t => t.Parent.FirstAncestorOrSelf<StatementSyntax>()).FirstOrDefault();
Assert.NotNull(b);
var expr2 = expr.RemoveNode(b, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = expr2.ToFullString();
Assert.Equal("{ a; /* trivia */ c }", text);
}
[Fact]
public void TestRemoveLastNode_KeepExteriorTrivia()
{
// this tests removing the last node in a non-terminal such that there is no token to the right of the removed
// node to attach the kept trivia too. The trivia must be attached to the previous token.
var cu = SyntaxFactory.ParseCompilationUnit("class C { void M() { } /* trivia */ }");
var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
// remove the body block from the method syntax (since it can be set to null)
var m2 = m.RemoveNode(m.Body, SyntaxRemoveOptions.KeepExteriorTrivia);
var text = m2.ToFullString();
Assert.Equal("void M() /* trivia */ ", text);
}
[Fact]
public void TestRemove_KeepExteriorTrivia_KeepUnbalancedDirectives()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"
class C
{
// before
void M()
{
#region Fred
} // after
#endregion
}");
var expectedText = @"
class C
{
// before
#region Fred
// after
#endregion
}";
var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepExteriorTrivia | SyntaxRemoveOptions.KeepUnbalancedDirectives);
var text = cu2.ToFullString();
Assert.Equal(expectedText, text);
}
[Fact]
public void TestRemove_KeepUnbalancedDirectives()
{
var inputText = @"
class C
{
// before
#region Fred
// more before
void M()
{
} // after
#endregion
}";
var expectedText = @"
class C
{
#region Fred
#endregion
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepUnbalancedDirectives);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
public void TestRemove_KeepDirectives()
{
var inputText = @"
class C
{
// before
#region Fred
// more before
void M()
{
#if true
#endif
} // after
#endregion
}";
var expectedText = @"
class C
{
#region Fred
#if true
#endif
#endregion
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepDirectives);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemove_KeepEndOfLine()
{
var inputText = @"
class C
{
// before
void M()
{
} // after
}";
var expectedText = @"
class C
{
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<MethodDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveWithoutEOL_KeepEndOfLine()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } // test");
var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal("class A { } ", text);
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveBadDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"class A { } class B { } #endregion");
var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives);
var text = cu2.ToFullString();
Assert.Equal("class A { } \r\n#endregion", text);
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveDocument_KeepEndOfLine()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"
#region A
class A
{ }
#endregion");
var cu2 = cu.RemoveNode(cu, SyntaxRemoveOptions.KeepEndOfLine);
Assert.Null(cu2);
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveFirstParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine()
{
// EOL should be found on CommaToken TrailingTrivia
var inputText = @"
class C
{
void M(
// before a
int a,
// after a
// before b
int b
/* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
// after a
// before b
int b
/* after b*/)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveFirstParameterEOLParameterSyntaxTrailingTrivia_KeepEndOfLine()
{
// EOL should be found on ParameterSyntax TrailingTrivia
var inputText = @"
class C
{
void M(
// before a
int a
, /* after comma */ int b
/* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
int b
/* after b*/)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveFirstParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine()
{
// EOL should be found on CommaToken LeadingTrivia and also on ParameterSyntax TrailingTrivia
// but only one will be added
var inputText = @"
class C
{
void M(
// before a
int a
// before b
, /* after comma */ int b
/* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
int b
/* after b*/)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveFirstParameter_KeepTrailingTrivia()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"
class C
{
void M(
// before a
int a
// before b
, /* after comma */ int b
/* after b*/)
{
}
}");
var expectedText = @"
class C
{
void M(
// before b
/* after comma */ int b
/* after b*/)
{
}
}";
var m = cu.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepTrailingTrivia);
var text = cu2.ToFullString();
Assert.Equal(expectedText, text);
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveLastParameterEOLCommaTokenLeadingTrivia_KeepEndOfLine()
{
// EOL should be found on CommaToken LeadingTrivia
var inputText = @"
class C
{
void M(
// before a
int a
// after a
, /* after comma*/ int b /* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
// before a
int a
)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveLastParameterEOLCommaTokenTrailingTrivia_KeepEndOfLine()
{
// EOL should be found on CommaToken TrailingTrivia
var inputText = @"
class C
{
void M(
// before a
int a, /* after comma*/
int b /* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
// before a
int a
)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveLastParameterEOLParameterSyntaxLeadingTrivia_KeepEndOfLine()
{
// EOL should be found on ParameterSyntax LeadingTrivia and also on CommaToken TrailingTrivia
// but only one will be added
var inputText = @"
class C
{
void M(
// before a
int a, /* after comma */
// before b
int b /* after b*/)
{
}
}";
var expectedText = @"
class C
{
void M(
// before a
int a
)
{
}
}";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveLastParameter_KeepLeadingTrivia()
{
var cu = SyntaxFactory.ParseCompilationUnit(@"
class C
{
void M(
// before a
int a, /* after comma */
// before b
int b /* after b*/)
{
}
}");
var expectedText = @"
class C
{
void M(
// before a
int a /* after comma */
// before b
)
{
}
}";
var m = cu.DescendantNodes().OfType<ParameterSyntax>().LastOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepLeadingTrivia);
var text = cu2.ToFullString();
Assert.Equal(expectedText, text);
}
[Fact]
[WorkItem(22924, "https://github.com/dotnet/roslyn/issues/22924")]
public void TestRemoveClassWithEndRegionDirectiveWithoutEOL_KeepEndOfLine_KeepDirectives()
{
var inputText = @"
#region A
class A { } #endregion";
var expectedText = @"
#region A
#endregion";
TestWithWindowsAndUnixEndOfLines(inputText, expectedText, (cu, expected) =>
{
var m = cu.DescendantNodes().OfType<TypeDeclarationSyntax>().FirstOrDefault();
Assert.NotNull(m);
var cu2 = cu.RemoveNode(m, SyntaxRemoveOptions.KeepEndOfLine | SyntaxRemoveOptions.KeepDirectives);
var text = cu2.ToFullString();
Assert.Equal(expected, text);
});
}
[Fact]
public void SeparatorsOfSeparatedSyntaxLists()
{
var s1 = "int goo(int a, int b, int c) {}";
var tree = SyntaxFactory.ParseSyntaxTree(s1);
var root = tree.GetCompilationUnitRoot();
var method = (LocalFunctionStatementSyntax)((GlobalStatementSyntax)root.Members[0]).Statement;
var list = (SeparatedSyntaxList<ParameterSyntax>)method.ParameterList.Parameters;
Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(0)).Kind());
Assert.Equal(SyntaxKind.CommaToken, ((SyntaxToken)list.GetSeparator(1)).Kind());
foreach (var index in new int[] { -1, 2 })
{
bool exceptionThrown = false;
try
{
var unused = list.GetSeparator(2);
}
catch (ArgumentOutOfRangeException)
{
exceptionThrown = true;
}
Assert.True(exceptionThrown);
}
var internalParameterList = (InternalSyntax.ParameterListSyntax)method.ParameterList.Green;
var internalParameters = internalParameterList.Parameters;
Assert.Equal(2, internalParameters.SeparatorCount);
Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(0))).Kind());
Assert.Equal(SyntaxKind.CommaToken, (new SyntaxToken(internalParameters.GetSeparator(1))).Kind());
Assert.Equal(3, internalParameters.Count);
Assert.Equal("a", internalParameters[0].Identifier.ValueText);
Assert.Equal("b", internalParameters[1].Identifier.ValueText);
Assert.Equal("c", internalParameters[2].Identifier.ValueText);
}
[Fact]
public void ThrowIfUnderlyingNodeIsNullForList()
{
var list = new SyntaxNodeOrTokenList();
Assert.Equal(0, list.Count);
foreach (var index in new int[] { -1, 0, 23 })
{
bool exceptionThrown = false;
try
{
var unused = list[0];
}
catch (ArgumentOutOfRangeException)
{
exceptionThrown = true;
}
Assert.True(exceptionThrown);
}
}
[WorkItem(541188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541188")]
[Fact]
public void GetDiagnosticsOnMissingToken()
{
var syntaxTree = SyntaxFactory.ParseSyntaxTree(@"namespace n1 { c1<t");
var token = syntaxTree.FindNodeOrTokenByKind(SyntaxKind.GreaterThanToken);
var diag = syntaxTree.GetDiagnostics(token).ToList();
Assert.True(token.IsMissing);
Assert.Equal(1, diag.Count);
}
[WorkItem(541325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541325")]
[Fact]
public void GetDiagnosticsOnMissingToken2()
{
var syntaxTree = SyntaxFactory.ParseSyntaxTree(@"
class Base<T>
{
public virtual int Property
{
get { return 0; }
// Note: Repro for bug 7990 requires a missing close brace token i.e. missing } below
set {
}
public virtual void Method()
{
}
}");
foreach (var t in syntaxTree.GetCompilationUnitRoot().DescendantTokens())
{
// Bug 7990: Below for loop is an infinite loop.
foreach (var e in syntaxTree.GetDiagnostics(t))
{
}
}
// TODO: Please add meaningful checks once the above deadlock issue is fixed.
}
[WorkItem(541648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541648")]
[Fact]
public void GetDiagnosticsOnMissingToken4()
{
string code = @"
public class MyClass
{
using Lib;
using Lib2;
public class Test1
{
}
}";
var syntaxTree = SyntaxFactory.ParseSyntaxTree(code);
var token = syntaxTree.GetCompilationUnitRoot().FindToken(code.IndexOf("using Lib;", StringComparison.Ordinal));
var diag = syntaxTree.GetDiagnostics(token).ToList();
Assert.True(token.IsMissing);
Assert.Equal(3, diag.Count);
}
[WorkItem(541630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541630")]
[Fact]
public void GetDiagnosticsOnBadReferenceDirective()
{
string code = @"class c1
{
#r
void m1()
{
}
}";
var tree = SyntaxFactory.ParseSyntaxTree(code);
var trivia = tree.GetCompilationUnitRoot().FindTrivia(code.IndexOf("#r", StringComparison.Ordinal)); // ReferenceDirective.
foreach (var diag in tree.GetDiagnostics(trivia))
{
Assert.NotNull(diag);
// TODO: Please add any additional validations if necessary.
}
}
[WorkItem(528626, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528626")]
[Fact]
public void SpanOfNodeWithMissingChildren()
{
string code = @"delegate = 1;";
var tree = SyntaxFactory.ParseSyntaxTree(code);
var compilationUnit = tree.GetCompilationUnitRoot();
var delegateDecl = (DelegateDeclarationSyntax)compilationUnit.Members[0];
var paramList = delegateDecl.ParameterList;
// For (non-EOF) tokens, IsMissing is true if and only if Width is 0.
Assert.True(compilationUnit.DescendantTokens(node => true).
Where(token => token.Kind() != SyntaxKind.EndOfFileToken).
All(token => token.IsMissing == (token.Width == 0)));
// For non-terminals, Is true if Width is 0, but the converse may not hold.
Assert.True(paramList.IsMissing);
Assert.NotEqual(0, paramList.Width);
Assert.NotEqual(0, paramList.FullWidth);
}
[WorkItem(542457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542457")]
[Fact]
public void AddMethodModifier()
{
var tree = SyntaxFactory.ParseSyntaxTree(@"
class Program
{
static void Main(string[] args)
{
}
}");
var compilationUnit = tree.GetCompilationUnitRoot();
var @class = (ClassDeclarationSyntax)compilationUnit.Members.Single();
var method = (MethodDeclarationSyntax)@class.Members.Single();
var newModifiers = method.Modifiers.Add(SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.UnsafeKeyword, SyntaxFactory.TriviaList(SyntaxFactory.Space)));
Assert.Equal(" static unsafe ", newModifiers.ToFullString());
Assert.Equal(2, newModifiers.Count);
Assert.Equal(SyntaxKind.StaticKeyword, newModifiers[0].Kind());
Assert.Equal(SyntaxKind.UnsafeKeyword, newModifiers[1].Kind());
}
[Fact]
public void SeparatedSyntaxListValidation()
{
var intType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword));
var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken);
SyntaxFactory.SingletonSeparatedList<TypeSyntax>(intType);
SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken });
SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType });
SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, intType, commaToken });
Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { commaToken }));
Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, commaToken, commaToken }));
Assert.Throws<ArgumentException>(() => SyntaxFactory.SeparatedList<TypeSyntax>(new SyntaxNodeOrToken[] { intType, intType }));
}
[WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")]
[Fact]
public void SyntaxDotParseCompilationUnitContainingOnlyWhitespace()
{
var node = SyntaxFactory.ParseCompilationUnit(" ");
Assert.True(node.HasLeadingTrivia);
Assert.Equal(1, node.GetLeadingTrivia().Count);
Assert.Equal(1, node.DescendantTrivia().Count());
Assert.Equal(" ", node.GetLeadingTrivia().First().ToString());
}
[WorkItem(543310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543310")]
[Fact]
public void SyntaxTreeDotParseCompilationUnitContainingOnlyWhitespace()
{
var node = SyntaxFactory.ParseSyntaxTree(" ").GetCompilationUnitRoot();
Assert.True(node.HasLeadingTrivia);
Assert.Equal(1, node.GetLeadingTrivia().Count);
Assert.Equal(1, node.DescendantTrivia().Count());
Assert.Equal(" ", node.GetLeadingTrivia().First().ToString());
}
[Fact]
public void SyntaxNodeAndTokenToString()
{
var text = @"class A { }";
var root = SyntaxFactory.ParseCompilationUnit(text);
var children = root.DescendantNodesAndTokens();
var nodeOrToken = children.First();
Assert.Equal("class A { }", nodeOrToken.ToString());
Assert.Equal(text, nodeOrToken.ToString());
var node = (SyntaxNode)children.First(n => n.IsNode);
Assert.Equal("class A { }", node.ToString());
Assert.Equal(text, node.ToFullString());
var token = (SyntaxToken)children.First(n => n.IsToken);
Assert.Equal("class", token.ToString());
Assert.Equal("class ", token.ToFullString());
var trivia = root.DescendantTrivia().First();
Assert.Equal(" ", trivia.ToString());
Assert.Equal(" ", trivia.ToFullString());
}
[WorkItem(545116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545116")]
[Fact]
public void FindTriviaOutsideNode()
{
var text = @"// This is trivia
class C
{
static void Main()
{
}
}
";
var root = SyntaxFactory.ParseCompilationUnit(text);
Assert.InRange(0, root.FullSpan.Start, root.FullSpan.End);
var rootTrivia = root.FindTrivia(0);
Assert.Equal("// This is trivia", rootTrivia.ToString().Trim());
var method = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.NotInRange(0, method.FullSpan.Start, method.FullSpan.End);
var methodTrivia = method.FindTrivia(0);
Assert.Equal(default(SyntaxTrivia), methodTrivia);
}
[Fact]
public void TestSyntaxTriviaListEquals()
{
var emptyWhitespace = SyntaxFactory.Whitespace("");
var emptyToken = SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken).WithTrailingTrivia(emptyWhitespace, emptyWhitespace);
var emptyTokenList = SyntaxFactory.TokenList(emptyToken, emptyToken);
// elements should be not equal
Assert.NotEqual(emptyTokenList[0].TrailingTrivia[0], emptyTokenList[1].TrailingTrivia[0]);
// lists should be not equal
Assert.NotEqual(emptyTokenList[0].TrailingTrivia, emptyTokenList[1].TrailingTrivia);
// Two lists with the same parent node, but different indexes should NOT be the same.
var emptyTriviaList = SyntaxFactory.TriviaList(emptyWhitespace, emptyWhitespace);
emptyToken = emptyToken.WithLeadingTrivia(emptyTriviaList).WithTrailingTrivia(emptyTriviaList);
// elements should be not equal
Assert.NotEqual(emptyToken.LeadingTrivia[0], emptyToken.TrailingTrivia[0]);
// lists should be not equal
Assert.NotEqual(emptyToken.LeadingTrivia, emptyToken.TrailingTrivia);
}
[Fact]
public void Test_SyntaxTree_ParseTextInvalidArguments()
{
// Invalid arguments - Validate Exceptions
Assert.Throws<System.ArgumentNullException>(delegate
{
SourceText st = null;
var treeFromSource_invalid2 = SyntaxFactory.ParseSyntaxTree(st);
});
}
[Fact]
public void TestSyntaxTree_Changes()
{
string SourceText = @"using System;
using System.Linq;
using System.Collections;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}";
SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText);
var root = (CompilationUnitSyntax)tree.GetRoot();
// Get the Imports Clauses
var FirstUsingClause = root.Usings[0];
var SecondUsingClause = root.Usings[1];
var ThirdUsingClause = root.Usings[2];
var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree);
Assert.Equal(0, ChangesForDifferentTrees.Count);
// Do a transform to Replace and Existing Tree
NameSyntax name = SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Collections.Generic"));
UsingDirectiveSyntax newUsingClause = ThirdUsingClause.WithName(name);
// Replace Node with a different Imports Clause
root = root.ReplaceNode(ThirdUsingClause, newUsingClause);
var ChangesFromTransform = ThirdUsingClause.SyntaxTree.GetChanges(newUsingClause.SyntaxTree);
Assert.Equal(2, ChangesFromTransform.Count);
// Using the Common Syntax Changes Method
SyntaxTree x = ThirdUsingClause.SyntaxTree;
SyntaxTree y = newUsingClause.SyntaxTree;
var changes2UsingCommonSyntax = x.GetChanges(y);
Assert.Equal(2, changes2UsingCommonSyntax.Count);
// Verify Changes from CS Specific SyntaxTree and Common SyntaxTree are the same
Assert.Equal(ChangesFromTransform, changes2UsingCommonSyntax);
}
[Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")]
public void TestSyntaxTree_GetChangesInvalid()
{
string SourceText = @"using System;
using System.Linq;
using System.Collections;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}";
SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText);
var root = (CompilationUnitSyntax)tree.GetRoot();
// Get the Imports Clauses
var FirstUsingClause = root.Usings[0];
var SecondUsingClause = root.Usings[1];
var ThirdUsingClause = root.Usings[2];
var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChanges(SecondUsingClause.SyntaxTree);
Assert.Equal(0, ChangesForDifferentTrees.Count);
// With null tree
SyntaxTree BlankTree = null;
Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChanges(BlankTree));
}
[Fact, WorkItem(658329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658329")]
public void TestSyntaxTree_GetChangedSpansInvalid()
{
string SourceText = @"using System;
using System.Linq;
using System.Collections;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello, World!"");
}
}";
SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(SourceText);
var root = (CompilationUnitSyntax)tree.GetRoot();
// Get the Imports Clauses
var FirstUsingClause = root.Usings[0];
var SecondUsingClause = root.Usings[1];
var ThirdUsingClause = root.Usings[2];
var ChangesForDifferentTrees = FirstUsingClause.SyntaxTree.GetChangedSpans(SecondUsingClause.SyntaxTree);
Assert.Equal(0, ChangesForDifferentTrees.Count);
// With null tree
SyntaxTree BlankTree = null;
Assert.Throws<ArgumentNullException>(() => FirstUsingClause.SyntaxTree.GetChangedSpans(BlankTree));
}
[Fact]
public void TestTriviaExists()
{
// token constructed using factory w/o specifying trivia (should have zero-width elastic trivia)
var idToken = SyntaxFactory.Identifier("goo");
Assert.True(idToken.HasLeadingTrivia);
Assert.Equal(1, idToken.LeadingTrivia.Count);
Assert.Equal(0, idToken.LeadingTrivia.Span.Length); // zero-width elastic trivia
Assert.True(idToken.HasTrailingTrivia);
Assert.Equal(1, idToken.TrailingTrivia.Count);
Assert.Equal(0, idToken.TrailingTrivia.Span.Length); // zero-width elastic trivia
// token constructed by parser w/o trivia
idToken = SyntaxFactory.ParseToken("x");
Assert.False(idToken.HasLeadingTrivia);
Assert.Equal(0, idToken.LeadingTrivia.Count);
Assert.False(idToken.HasTrailingTrivia);
Assert.Equal(0, idToken.TrailingTrivia.Count);
// token constructed by parser with trivia
idToken = SyntaxFactory.ParseToken(" x ");
Assert.True(idToken.HasLeadingTrivia);
Assert.Equal(1, idToken.LeadingTrivia.Count);
Assert.Equal(1, idToken.LeadingTrivia.Span.Length);
Assert.True(idToken.HasTrailingTrivia);
Assert.Equal(1, idToken.TrailingTrivia.Count);
Assert.Equal(2, idToken.TrailingTrivia.Span.Length);
// node constructed using factory w/o specifying trivia
SyntaxNode namedNode = SyntaxFactory.IdentifierName("goo");
Assert.True(namedNode.HasLeadingTrivia);
Assert.Equal(1, namedNode.GetLeadingTrivia().Count);
Assert.Equal(0, namedNode.GetLeadingTrivia().Span.Length); // zero-width elastic trivia
Assert.True(namedNode.HasTrailingTrivia);
Assert.Equal(1, namedNode.GetTrailingTrivia().Count);
Assert.Equal(0, namedNode.GetTrailingTrivia().Span.Length); // zero-width elastic trivia
// node constructed by parse w/o trivia
namedNode = SyntaxFactory.ParseExpression("goo");
Assert.False(namedNode.HasLeadingTrivia);
Assert.Equal(0, namedNode.GetLeadingTrivia().Count);
Assert.False(namedNode.HasTrailingTrivia);
Assert.Equal(0, namedNode.GetTrailingTrivia().Count);
// node constructed by parse with trivia
namedNode = SyntaxFactory.ParseExpression(" goo ");
Assert.True(namedNode.HasLeadingTrivia);
Assert.Equal(1, namedNode.GetLeadingTrivia().Count);
Assert.Equal(1, namedNode.GetLeadingTrivia().Span.Length);
Assert.True(namedNode.HasTrailingTrivia);
Assert.Equal(1, namedNode.GetTrailingTrivia().Count);
Assert.Equal(2, namedNode.GetTrailingTrivia().Span.Length);
// nodeOrToken with token constructed from factory w/o specifying trivia
SyntaxNodeOrToken nodeOrToken = SyntaxFactory.Identifier("goo");
Assert.True(nodeOrToken.HasLeadingTrivia);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count);
Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia
Assert.True(nodeOrToken.HasTrailingTrivia);
Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count);
Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia
// nodeOrToken with node constructed from factory w/o specifying trivia
nodeOrToken = SyntaxFactory.IdentifierName("goo");
Assert.True(nodeOrToken.HasLeadingTrivia);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count);
Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia
Assert.True(nodeOrToken.HasTrailingTrivia);
Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count);
Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia
// nodeOrToken with token parsed from factory w/o trivia
nodeOrToken = SyntaxFactory.ParseToken("goo");
Assert.False(nodeOrToken.HasLeadingTrivia);
Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count);
Assert.False(nodeOrToken.HasTrailingTrivia);
Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count);
// nodeOrToken with node parsed from factory w/o trivia
nodeOrToken = SyntaxFactory.ParseExpression("goo");
Assert.False(nodeOrToken.HasLeadingTrivia);
Assert.Equal(0, nodeOrToken.GetLeadingTrivia().Count);
Assert.False(nodeOrToken.HasTrailingTrivia);
Assert.Equal(0, nodeOrToken.GetTrailingTrivia().Count);
// nodeOrToken with token parsed from factory with trivia
nodeOrToken = SyntaxFactory.ParseToken(" goo ");
Assert.True(nodeOrToken.HasLeadingTrivia);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia
Assert.True(nodeOrToken.HasTrailingTrivia);
Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count);
Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia
// nodeOrToken with node parsed from factory with trivia
nodeOrToken = SyntaxFactory.ParseExpression(" goo ");
Assert.True(nodeOrToken.HasLeadingTrivia);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Count);
Assert.Equal(1, nodeOrToken.GetLeadingTrivia().Span.Length); // zero-width elastic trivia
Assert.True(nodeOrToken.HasTrailingTrivia);
Assert.Equal(1, nodeOrToken.GetTrailingTrivia().Count);
Assert.Equal(2, nodeOrToken.GetTrailingTrivia().Span.Length); // zero-width elastic trivia
}
[WorkItem(6536, "https://github.com/dotnet/roslyn/issues/6536")]
[Fact]
public void TestFindTrivia_NoStackOverflowOnLargeExpression()
{
StringBuilder code = new StringBuilder();
code.Append(
@"class Goo
{
void Bar()
{
string test = ");
for (var i = 0; i < 3000; i++)
{
code.Append(@"""asdf"" + ");
}
code.Append(@"""last"";
}
}");
var tree = SyntaxFactory.ParseSyntaxTree(code.ToString());
var position = 4000;
var trivia = tree.GetCompilationUnitRoot().FindTrivia(position);
// no stack overflow
}
[Fact, WorkItem(8625, "https://github.com/dotnet/roslyn/issues/8625")]
public void SyntaxNodeContains()
{
var text = "a + (b - (c * (d / e)))";
var expression = SyntaxFactory.ParseExpression(text);
var a = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var e = expression.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "e");
var firstParens = e.FirstAncestorOrSelf<ExpressionSyntax>(n => n.Kind() == SyntaxKind.ParenthesizedExpression);
Assert.False(firstParens.Contains(a)); // fixing #8625 allows this to return quicker
Assert.True(firstParens.Contains(e));
}
private static void TestWithWindowsAndUnixEndOfLines(string inputText, string expectedText, Action<CompilationUnitSyntax, string> action)
{
inputText = inputText.NormalizeLineEndings();
expectedText = expectedText.NormalizeLineEndings();
var tests = new Dictionary<string, string>
{
{inputText, expectedText}, // Test CRLF (Windows)
{inputText.Replace("\r", ""), expectedText.Replace("\r", "")}, // Test LF (Unix)
};
foreach (var test in tests)
{
action(SyntaxFactory.ParseCompilationUnit(test.Key), test.Value);
}
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TokenData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
/// <summary>
/// it represents a token that is inside of token stream not also outside of token stream
///
/// it uses an index to navigate previous and after tokens in the stream to make navigation faster. and regular
/// Previous/NextToken for tokens outside of the stream.
///
/// this object is supposed to be live very short but created a lot of time. that is why it is struct.
/// (same reason why SyntaxToken is struct - to reduce heap allocation)
/// </summary>
internal readonly struct TokenData : IEqualityComparer<TokenData>, IEquatable<TokenData>, IComparable<TokenData>, IComparer<TokenData>
{
public TokenData(TokenStream tokenStream, int indexInStream, SyntaxToken token)
{
Contract.ThrowIfNull(tokenStream);
Contract.ThrowIfFalse((indexInStream == -1) || (0 <= indexInStream && indexInStream < tokenStream.TokenCount));
this.TokenStream = tokenStream;
this.IndexInStream = indexInStream;
this.Token = token;
}
public TokenStream TokenStream { get; }
public int IndexInStream { get; }
public SyntaxToken Token { get; }
public TokenData GetPreviousTokenData()
=> this.TokenStream.GetPreviousTokenData(this);
public TokenData GetNextTokenData()
=> this.TokenStream.GetNextTokenData(this);
public bool Equals(TokenData x, TokenData y)
=> x.Equals(y);
public int GetHashCode(TokenData obj)
=> obj.GetHashCode();
public override int GetHashCode()
=> this.Token.GetHashCode();
public override bool Equals(object? obj)
{
return obj is TokenData data &&
this.Equals(data);
}
public bool Equals(TokenData other)
{
if (this.TokenStream != other.TokenStream)
{
return false;
}
if (this.IndexInStream >= 0 && this.IndexInStream == other.IndexInStream)
{
return true;
}
return this.Token.Equals(other.Token);
}
public int Compare(TokenData x, TokenData y)
=> x.CompareTo(y);
public int CompareTo(TokenData other)
{
Contract.ThrowIfFalse(this.TokenStream == other.TokenStream);
if (this.IndexInStream >= 0 && other.IndexInStream >= 0)
{
return this.IndexInStream - other.IndexInStream;
}
var start = this.Token.SpanStart - other.Token.SpanStart;
if (start != 0)
{
return start;
}
var end = this.Token.Span.End - other.Token.Span.End;
if (end != 0)
{
return end;
}
// this is expansive check. but there is no other way to check.
var commonRoot = this.Token.GetCommonRoot(other.Token);
RoslynDebug.Assert(commonRoot != null);
var tokens = commonRoot.DescendantTokens();
var index1 = Index(tokens, this.Token);
var index2 = Index(tokens, other.Token);
Contract.ThrowIfFalse(index1 >= 0 && index2 >= 0);
return index1 - index2;
}
private static int Index(IEnumerable<SyntaxToken> tokens, SyntaxToken token)
{
var index = 0;
foreach (var current in tokens)
{
if (current == token)
{
return index;
}
index++;
}
return -1;
}
public static bool operator <(TokenData left, TokenData right)
=> left.CompareTo(right) < 0;
public static bool operator >(TokenData left, TokenData right)
=> left.CompareTo(right) > 0;
public static bool operator ==(TokenData left, TokenData right)
=> left.Equals(right);
public static bool operator !=(TokenData left, TokenData right)
=> left.Equals(right);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
/// <summary>
/// it represents a token that is inside of token stream not also outside of token stream
///
/// it uses an index to navigate previous and after tokens in the stream to make navigation faster. and regular
/// Previous/NextToken for tokens outside of the stream.
///
/// this object is supposed to be live very short but created a lot of time. that is why it is struct.
/// (same reason why SyntaxToken is struct - to reduce heap allocation)
/// </summary>
internal readonly struct TokenData : IEqualityComparer<TokenData>, IEquatable<TokenData>, IComparable<TokenData>, IComparer<TokenData>
{
public TokenData(TokenStream tokenStream, int indexInStream, SyntaxToken token)
{
Contract.ThrowIfNull(tokenStream);
Contract.ThrowIfFalse((indexInStream == -1) || (0 <= indexInStream && indexInStream < tokenStream.TokenCount));
this.TokenStream = tokenStream;
this.IndexInStream = indexInStream;
this.Token = token;
}
public TokenStream TokenStream { get; }
public int IndexInStream { get; }
public SyntaxToken Token { get; }
public TokenData GetPreviousTokenData()
=> this.TokenStream.GetPreviousTokenData(this);
public TokenData GetNextTokenData()
=> this.TokenStream.GetNextTokenData(this);
public bool Equals(TokenData x, TokenData y)
=> x.Equals(y);
public int GetHashCode(TokenData obj)
=> obj.GetHashCode();
public override int GetHashCode()
=> this.Token.GetHashCode();
public override bool Equals(object? obj)
{
return obj is TokenData data &&
this.Equals(data);
}
public bool Equals(TokenData other)
{
if (this.TokenStream != other.TokenStream)
{
return false;
}
if (this.IndexInStream >= 0 && this.IndexInStream == other.IndexInStream)
{
return true;
}
return this.Token.Equals(other.Token);
}
public int Compare(TokenData x, TokenData y)
=> x.CompareTo(y);
public int CompareTo(TokenData other)
{
Contract.ThrowIfFalse(this.TokenStream == other.TokenStream);
if (this.IndexInStream >= 0 && other.IndexInStream >= 0)
{
return this.IndexInStream - other.IndexInStream;
}
var start = this.Token.SpanStart - other.Token.SpanStart;
if (start != 0)
{
return start;
}
var end = this.Token.Span.End - other.Token.Span.End;
if (end != 0)
{
return end;
}
// this is expansive check. but there is no other way to check.
var commonRoot = this.Token.GetCommonRoot(other.Token);
RoslynDebug.Assert(commonRoot != null);
var tokens = commonRoot.DescendantTokens();
var index1 = Index(tokens, this.Token);
var index2 = Index(tokens, other.Token);
Contract.ThrowIfFalse(index1 >= 0 && index2 >= 0);
return index1 - index2;
}
private static int Index(IEnumerable<SyntaxToken> tokens, SyntaxToken token)
{
var index = 0;
foreach (var current in tokens)
{
if (current == token)
{
return index;
}
index++;
}
return -1;
}
public static bool operator <(TokenData left, TokenData right)
=> left.CompareTo(right) < 0;
public static bool operator >(TokenData left, TokenData right)
=> left.CompareTo(right) > 0;
public static bool operator ==(TokenData left, TokenData right)
=> left.Equals(right);
public static bool operator !=(TokenData left, TokenData right)
=> left.Equals(right);
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
internal partial class CSharpIntroduceVariableService
{
protected override async Task<Document> IntroduceLocalAsync(
SemanticDocument document,
ExpressionSyntax expression,
bool allOccurrences,
bool isConstant,
CancellationToken cancellationToken)
{
var containerToGenerateInto = expression.Ancestors().FirstOrDefault(s =>
s is BlockSyntax || s is ArrowExpressionClauseSyntax || s is LambdaExpressionSyntax);
var newLocalNameToken = GenerateUniqueLocalName(
document, expression, isConstant, containerToGenerateInto, cancellationToken);
var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken);
var modifiers = isConstant
? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword))
: default;
var declarationStatement = SyntaxFactory.LocalDeclarationStatement(
modifiers,
SyntaxFactory.VariableDeclaration(
GetTypeSyntax(document, expression, cancellationToken),
SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(
newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
null,
SyntaxFactory.EqualsValueClause(expression.WithoutTrivia())))));
// If we're inserting into a multi-line parent, then add a newline after the local-var
// we're adding. That way we don't end up having it and the starting statement be on
// the same line (which will cause indentation to be computed incorrectly).
var text = await document.Document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (!text.AreOnSameLine(containerToGenerateInto.GetFirstToken(), containerToGenerateInto.GetLastToken()))
{
declarationStatement = declarationStatement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed);
}
switch (containerToGenerateInto)
{
case BlockSyntax block:
return await IntroduceLocalDeclarationIntoBlockAsync(
document, block, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken).ConfigureAwait(false);
case ArrowExpressionClauseSyntax arrowExpression:
// this will be null for expression-bodied properties & indexer (not for individual getters & setters, those do have a symbol),
// both of which are a shorthand for the getter and always return a value
var method = document.SemanticModel.GetDeclaredSymbol(arrowExpression.Parent, cancellationToken) as IMethodSymbol;
var createReturnStatement = !method?.ReturnsVoid ?? true;
return RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration(
document, arrowExpression, expression, newLocalName,
declarationStatement, allOccurrences, createReturnStatement, cancellationToken);
case LambdaExpressionSyntax lambda:
return IntroduceLocalDeclarationIntoLambda(
document, lambda, expression, newLocalName, declarationStatement,
allOccurrences, cancellationToken);
}
throw new InvalidOperationException();
}
private Document IntroduceLocalDeclarationIntoLambda(
SemanticDocument document,
LambdaExpressionSyntax oldLambda,
ExpressionSyntax expression,
IdentifierNameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
CancellationToken cancellationToken)
{
var oldBody = (ExpressionSyntax)oldLambda.Body;
var isEntireLambdaBodySelected = oldBody.Equals(expression.WalkUpParentheses());
var rewrittenBody = Rewrite(
document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken);
var shouldIncludeReturnStatement = ShouldIncludeReturnStatement(document, oldLambda, cancellationToken);
var newBody = GetNewBlockBodyForLambda(
declarationStatement, isEntireLambdaBodySelected, rewrittenBody, shouldIncludeReturnStatement);
// Add an elastic newline so that the formatter will place this new lambda body across multiple lines.
newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed))
.WithAdditionalAnnotations(Formatter.Annotation);
var newLambda = oldLambda.WithBody(newBody);
var newRoot = document.Root.ReplaceNode(oldLambda, newLambda);
return document.Document.WithSyntaxRoot(newRoot);
}
private static bool ShouldIncludeReturnStatement(
SemanticDocument document,
LambdaExpressionSyntax oldLambda,
CancellationToken cancellationToken)
{
if (document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType is INamedTypeSymbol delegateType &&
delegateType.DelegateInvokeMethod != null)
{
if (delegateType.DelegateInvokeMethod.ReturnsVoid)
{
return false;
}
// Async lambdas with a Task or ValueTask return type don't need a return statement.
// e.g.:
// Func<int, Task> f = async x => await M2();
//
// After refactoring:
// Func<int, Task> f = async x =>
// {
// Task task = M2();
// await task;
// };
var compilation = document.SemanticModel.Compilation;
var delegateReturnType = delegateType.DelegateInvokeMethod.ReturnType;
if (oldLambda.AsyncKeyword != default && delegateReturnType != null)
{
if ((compilation.TaskType() != null && delegateReturnType.Equals(compilation.TaskType())) ||
(compilation.ValueTaskType() != null && delegateReturnType.Equals(compilation.ValueTaskType())))
{
return false;
}
}
}
return true;
}
private static BlockSyntax GetNewBlockBodyForLambda(
LocalDeclarationStatementSyntax declarationStatement,
bool isEntireLambdaBodySelected,
ExpressionSyntax rewrittenBody,
bool includeReturnStatement)
{
if (includeReturnStatement)
{
// Case 1: The lambda has a non-void return type.
// e.g.:
// Func<int, int> f = x => [|x + 1|];
//
// After refactoring:
// Func<int, int> f = x =>
// {
// var v = x + 1;
// return v;
// };
return SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody));
}
// For lambdas with void return types, we don't need to include the rewritten body if the entire lambda body
// was originally selected for refactoring, as the rewritten body should already be encompassed within the
// declaration statement.
if (isEntireLambdaBodySelected)
{
// Case 2a: The lambda has a void return type, and the user selects the entire lambda body.
// e.g.:
// Action<int> goo = x => [|x.ToString()|];
//
// After refactoring:
// Action<int> goo = x =>
// {
// string v = x.ToString();
// };
return SyntaxFactory.Block(declarationStatement);
}
// Case 2b: The lambda has a void return type, and the user didn't select the entire lambda body.
// e.g.:
// Task.Run(() => File.Copy("src", [|Path.Combine("dir", "file")|]));
//
// After refactoring:
// Task.Run(() =>
// {
// string destFileName = Path.Combine("dir", "file");
// File.Copy("src", destFileName);
// });
return SyntaxFactory.Block(
declarationStatement,
SyntaxFactory.ExpressionStatement(rewrittenBody, SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
}
private static TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax expression, CancellationToken cancellationToken)
{
var typeSymbol = GetTypeSymbol(document, expression, cancellationToken);
return typeSymbol.GenerateTypeSyntax();
}
private Document RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration(
SemanticDocument document,
ArrowExpressionClauseSyntax arrowExpression,
ExpressionSyntax expression,
NameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
bool createReturnStatement,
CancellationToken cancellationToken)
{
var oldBody = arrowExpression;
var oldParentingNode = oldBody.Parent;
var leadingTrivia = oldBody.GetLeadingTrivia()
.AddRange(oldBody.ArrowToken.TrailingTrivia);
var newExpression = Rewrite(document, expression, newLocalName, document, oldBody.Expression, allOccurrences, cancellationToken);
var convertedStatement = createReturnStatement
? SyntaxFactory.ReturnStatement(newExpression)
: (StatementSyntax)SyntaxFactory.ExpressionStatement(newExpression);
var newBody = SyntaxFactory.Block(declarationStatement, convertedStatement)
.WithLeadingTrivia(leadingTrivia)
.WithTrailingTrivia(oldBody.GetTrailingTrivia());
// Add an elastic newline so that the formatter will place this new block across multiple lines.
newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed))
.WithAdditionalAnnotations(Formatter.Annotation);
var newRoot = document.Root.ReplaceNode(oldParentingNode, WithBlockBody(oldParentingNode, newBody));
return document.Document.WithSyntaxRoot(newRoot);
}
private static SyntaxNode WithBlockBody(SyntaxNode node, BlockSyntax body)
{
switch (node)
{
case BasePropertyDeclarationSyntax baseProperty:
var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, body)));
return baseProperty
.TryWithExpressionBody(null)
.WithAccessorList(accessorList)
.TryWithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(baseProperty);
case AccessorDeclarationSyntax accessor:
return accessor
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(accessor);
case BaseMethodDeclarationSyntax baseMethod:
return baseMethod
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(baseMethod);
case LocalFunctionStatementSyntax localFunction:
return localFunction
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(localFunction);
default:
throw ExceptionUtilities.UnexpectedValue(node);
}
}
private async Task<Document> IntroduceLocalDeclarationIntoBlockAsync(
SemanticDocument document,
BlockSyntax block,
ExpressionSyntax expression,
NameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
CancellationToken cancellationToken)
{
declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation);
SyntaxNode scope = block;
// If we're within a non-static local function, our scope for the new local declaration is expanded to include the enclosing member.
var localFunction = block.GetAncestor<LocalFunctionStatementSyntax>();
if (localFunction != null && !localFunction.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.StaticKeyword)))
{
scope = block.GetAncestor<MemberDeclarationSyntax>();
}
var matches = FindMatches(document, expression, document, scope, allOccurrences, cancellationToken);
Debug.Assert(matches.Contains(expression));
(document, matches) = await ComplexifyParentingStatementsAsync(document, matches, cancellationToken).ConfigureAwait(false);
// Our original expression should have been one of the matches, which were tracked as part
// of complexification, so we can retrieve the latest version of the expression here.
expression = document.Root.GetCurrentNode(expression);
var root = document.Root;
ISet<StatementSyntax> allAffectedStatements = new HashSet<StatementSyntax>(matches.SelectMany(expr => GetApplicableStatementAncestors(expr)));
SyntaxNode innermostCommonBlock;
var innermostStatements = new HashSet<StatementSyntax>(matches.Select(expr => GetApplicableStatementAncestors(expr).First()));
if (innermostStatements.Count == 1)
{
// if there was only one match, or all the matches came from the same statement
var statement = innermostStatements.Single();
// and the statement is an embedded statement without a block, we want to generate one
// around this statement rather than continue going up to find an actual block
if (!IsBlockLike(statement.Parent))
{
root = root.TrackNodes(allAffectedStatements.Concat(new SyntaxNode[] { expression, statement }));
root = root.ReplaceNode(root.GetCurrentNode(statement),
SyntaxFactory.Block(root.GetCurrentNode(statement)).WithAdditionalAnnotations(Formatter.Annotation));
expression = root.GetCurrentNode(expression);
allAffectedStatements = allAffectedStatements.Select(root.GetCurrentNode).ToSet();
statement = root.GetCurrentNode(statement);
}
innermostCommonBlock = statement.Parent;
}
else
{
innermostCommonBlock = innermostStatements.FindInnermostCommonNode(IsBlockLike);
}
var firstStatementAffectedIndex = GetFirstStatementAffectedIndex(innermostCommonBlock, matches, GetStatements(innermostCommonBlock).IndexOf(allAffectedStatements.Contains));
var newInnerMostBlock = Rewrite(
document, expression, newLocalName, document, innermostCommonBlock, allOccurrences, cancellationToken);
var statements = InsertWithinTriviaOfNext(GetStatements(newInnerMostBlock), declarationStatement, firstStatementAffectedIndex);
var finalInnerMostBlock = WithStatements(newInnerMostBlock, statements);
var newRoot = root.ReplaceNode(innermostCommonBlock, finalInnerMostBlock);
return document.Document.WithSyntaxRoot(newRoot);
}
private static IEnumerable<StatementSyntax> GetApplicableStatementAncestors(ExpressionSyntax expr)
{
foreach (var statement in expr.GetAncestorsOrThis<StatementSyntax>())
{
// When determining where to put a local, we don't want to put it between the `else`
// and `if` of a compound if-statement.
if (statement.Kind() == SyntaxKind.IfStatement &&
statement.IsParentKind(SyntaxKind.ElseClause))
{
continue;
}
yield return statement;
}
}
private static int GetFirstStatementAffectedIndex(SyntaxNode innermostCommonBlock, ISet<ExpressionSyntax> matches, int firstStatementAffectedIndex)
{
// If a local function is involved, we have to make sure the new declaration is placed:
// 1. Before all calls to local functions that use the variable.
// 2. Before the local function(s) themselves.
// 3. Before all matches, i.e. places in the code where the new declaration will replace existing code.
// Cases (2) and (3) are already covered by the 'firstStatementAffectedIndex' parameter. Thus, all we have to do is ensure we consider (1) when
// determining where to place our new declaration.
// Find all the local functions within the scope that will use the new declaration.
var localFunctions = innermostCommonBlock.DescendantNodes().Where(node => node.IsKind(SyntaxKind.LocalFunctionStatement) && matches.Any(match => match.Span.OverlapsWith(node.Span)));
if (localFunctions.IsEmpty())
{
return firstStatementAffectedIndex;
}
var localFunctionIdentifiers = localFunctions.Select(node => ((LocalFunctionStatementSyntax)node).Identifier.ValueText);
// Find all calls to the applicable local functions within the scope.
var localFunctionCalls = innermostCommonBlock.DescendantNodes().Where(node => node is InvocationExpressionSyntax invocationExpression &&
invocationExpression.Expression.GetRightmostName() != null &&
!invocationExpression.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
localFunctionIdentifiers.Contains(invocationExpression.Expression.GetRightmostName().Identifier.ValueText));
if (localFunctionCalls.IsEmpty())
{
return firstStatementAffectedIndex;
}
// Find which call is the earliest.
var earliestLocalFunctionCall = localFunctionCalls.Min(node => node.SpanStart);
var statementsInBlock = GetStatements(innermostCommonBlock);
// Check if our earliest call is before all local function declarations and all matches, and if so, place our new declaration there.
var earliestLocalFunctionCallIndex = statementsInBlock.IndexOf(s => s.Span.Contains(earliestLocalFunctionCall));
return Math.Min(earliestLocalFunctionCallIndex, firstStatementAffectedIndex);
}
private static SyntaxList<StatementSyntax> InsertWithinTriviaOfNext(
SyntaxList<StatementSyntax> oldStatements,
StatementSyntax newStatement,
int statementIndex)
{
var nextStatement = oldStatements.ElementAtOrDefault(statementIndex);
if (nextStatement == null)
return oldStatements.Insert(statementIndex, newStatement);
// Grab all the trivia before the line the next statement is on and move it to the new node.
var nextStatementLeading = nextStatement.GetLeadingTrivia();
var precedingEndOfLine = nextStatementLeading.LastOrDefault(t => t.Kind() == SyntaxKind.EndOfLineTrivia);
if (precedingEndOfLine == default)
{
return oldStatements.ReplaceRange(
nextStatement, new[] { newStatement, nextStatement });
}
var endOfLineIndex = nextStatementLeading.IndexOf(precedingEndOfLine) + 1;
return oldStatements.ReplaceRange(
nextStatement, new[]
{
newStatement.WithLeadingTrivia(nextStatementLeading.Take(endOfLineIndex)),
nextStatement.WithLeadingTrivia(nextStatementLeading.Skip(endOfLineIndex)),
});
}
private static bool IsBlockLike(SyntaxNode node) => node is BlockSyntax || node is SwitchSectionSyntax;
private static SyntaxList<StatementSyntax> GetStatements(SyntaxNode blockLike)
=> blockLike switch
{
BlockSyntax block => block.Statements,
SwitchSectionSyntax switchSection => switchSection.Statements,
_ => throw ExceptionUtilities.UnexpectedValue(blockLike),
};
private static SyntaxNode WithStatements(SyntaxNode blockLike, SyntaxList<StatementSyntax> statements)
=> blockLike switch
{
BlockSyntax block => block.WithStatements(statements),
SwitchSectionSyntax switchSection => switchSection.WithStatements(statements),
_ => throw ExceptionUtilities.UnexpectedValue(blockLike),
};
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
internal partial class CSharpIntroduceVariableService
{
protected override async Task<Document> IntroduceLocalAsync(
SemanticDocument document,
ExpressionSyntax expression,
bool allOccurrences,
bool isConstant,
CancellationToken cancellationToken)
{
var containerToGenerateInto = expression.Ancestors().FirstOrDefault(s =>
s is BlockSyntax || s is ArrowExpressionClauseSyntax || s is LambdaExpressionSyntax);
var newLocalNameToken = GenerateUniqueLocalName(
document, expression, isConstant, containerToGenerateInto, cancellationToken);
var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken);
var modifiers = isConstant
? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword))
: default;
var declarationStatement = SyntaxFactory.LocalDeclarationStatement(
modifiers,
SyntaxFactory.VariableDeclaration(
GetTypeSyntax(document, expression, cancellationToken),
SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(
newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
null,
SyntaxFactory.EqualsValueClause(expression.WithoutTrivia())))));
// If we're inserting into a multi-line parent, then add a newline after the local-var
// we're adding. That way we don't end up having it and the starting statement be on
// the same line (which will cause indentation to be computed incorrectly).
var text = await document.Document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (!text.AreOnSameLine(containerToGenerateInto.GetFirstToken(), containerToGenerateInto.GetLastToken()))
{
declarationStatement = declarationStatement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed);
}
switch (containerToGenerateInto)
{
case BlockSyntax block:
return await IntroduceLocalDeclarationIntoBlockAsync(
document, block, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken).ConfigureAwait(false);
case ArrowExpressionClauseSyntax arrowExpression:
// this will be null for expression-bodied properties & indexer (not for individual getters & setters, those do have a symbol),
// both of which are a shorthand for the getter and always return a value
var method = document.SemanticModel.GetDeclaredSymbol(arrowExpression.Parent, cancellationToken) as IMethodSymbol;
var createReturnStatement = !method?.ReturnsVoid ?? true;
return RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration(
document, arrowExpression, expression, newLocalName,
declarationStatement, allOccurrences, createReturnStatement, cancellationToken);
case LambdaExpressionSyntax lambda:
return IntroduceLocalDeclarationIntoLambda(
document, lambda, expression, newLocalName, declarationStatement,
allOccurrences, cancellationToken);
}
throw new InvalidOperationException();
}
private Document IntroduceLocalDeclarationIntoLambda(
SemanticDocument document,
LambdaExpressionSyntax oldLambda,
ExpressionSyntax expression,
IdentifierNameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
CancellationToken cancellationToken)
{
var oldBody = (ExpressionSyntax)oldLambda.Body;
var isEntireLambdaBodySelected = oldBody.Equals(expression.WalkUpParentheses());
var rewrittenBody = Rewrite(
document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken);
var shouldIncludeReturnStatement = ShouldIncludeReturnStatement(document, oldLambda, cancellationToken);
var newBody = GetNewBlockBodyForLambda(
declarationStatement, isEntireLambdaBodySelected, rewrittenBody, shouldIncludeReturnStatement);
// Add an elastic newline so that the formatter will place this new lambda body across multiple lines.
newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed))
.WithAdditionalAnnotations(Formatter.Annotation);
var newLambda = oldLambda.WithBody(newBody);
var newRoot = document.Root.ReplaceNode(oldLambda, newLambda);
return document.Document.WithSyntaxRoot(newRoot);
}
private static bool ShouldIncludeReturnStatement(
SemanticDocument document,
LambdaExpressionSyntax oldLambda,
CancellationToken cancellationToken)
{
if (document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType is INamedTypeSymbol delegateType &&
delegateType.DelegateInvokeMethod != null)
{
if (delegateType.DelegateInvokeMethod.ReturnsVoid)
{
return false;
}
// Async lambdas with a Task or ValueTask return type don't need a return statement.
// e.g.:
// Func<int, Task> f = async x => await M2();
//
// After refactoring:
// Func<int, Task> f = async x =>
// {
// Task task = M2();
// await task;
// };
var compilation = document.SemanticModel.Compilation;
var delegateReturnType = delegateType.DelegateInvokeMethod.ReturnType;
if (oldLambda.AsyncKeyword != default && delegateReturnType != null)
{
if ((compilation.TaskType() != null && delegateReturnType.Equals(compilation.TaskType())) ||
(compilation.ValueTaskType() != null && delegateReturnType.Equals(compilation.ValueTaskType())))
{
return false;
}
}
}
return true;
}
private static BlockSyntax GetNewBlockBodyForLambda(
LocalDeclarationStatementSyntax declarationStatement,
bool isEntireLambdaBodySelected,
ExpressionSyntax rewrittenBody,
bool includeReturnStatement)
{
if (includeReturnStatement)
{
// Case 1: The lambda has a non-void return type.
// e.g.:
// Func<int, int> f = x => [|x + 1|];
//
// After refactoring:
// Func<int, int> f = x =>
// {
// var v = x + 1;
// return v;
// };
return SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody));
}
// For lambdas with void return types, we don't need to include the rewritten body if the entire lambda body
// was originally selected for refactoring, as the rewritten body should already be encompassed within the
// declaration statement.
if (isEntireLambdaBodySelected)
{
// Case 2a: The lambda has a void return type, and the user selects the entire lambda body.
// e.g.:
// Action<int> goo = x => [|x.ToString()|];
//
// After refactoring:
// Action<int> goo = x =>
// {
// string v = x.ToString();
// };
return SyntaxFactory.Block(declarationStatement);
}
// Case 2b: The lambda has a void return type, and the user didn't select the entire lambda body.
// e.g.:
// Task.Run(() => File.Copy("src", [|Path.Combine("dir", "file")|]));
//
// After refactoring:
// Task.Run(() =>
// {
// string destFileName = Path.Combine("dir", "file");
// File.Copy("src", destFileName);
// });
return SyntaxFactory.Block(
declarationStatement,
SyntaxFactory.ExpressionStatement(rewrittenBody, SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
}
private static TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax expression, CancellationToken cancellationToken)
{
var typeSymbol = GetTypeSymbol(document, expression, cancellationToken);
return typeSymbol.GenerateTypeSyntax();
}
private Document RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration(
SemanticDocument document,
ArrowExpressionClauseSyntax arrowExpression,
ExpressionSyntax expression,
NameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
bool createReturnStatement,
CancellationToken cancellationToken)
{
var oldBody = arrowExpression;
var oldParentingNode = oldBody.Parent;
var leadingTrivia = oldBody.GetLeadingTrivia()
.AddRange(oldBody.ArrowToken.TrailingTrivia);
var newExpression = Rewrite(document, expression, newLocalName, document, oldBody.Expression, allOccurrences, cancellationToken);
var convertedStatement = createReturnStatement
? SyntaxFactory.ReturnStatement(newExpression)
: (StatementSyntax)SyntaxFactory.ExpressionStatement(newExpression);
var newBody = SyntaxFactory.Block(declarationStatement, convertedStatement)
.WithLeadingTrivia(leadingTrivia)
.WithTrailingTrivia(oldBody.GetTrailingTrivia());
// Add an elastic newline so that the formatter will place this new block across multiple lines.
newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed))
.WithAdditionalAnnotations(Formatter.Annotation);
var newRoot = document.Root.ReplaceNode(oldParentingNode, WithBlockBody(oldParentingNode, newBody));
return document.Document.WithSyntaxRoot(newRoot);
}
private static SyntaxNode WithBlockBody(SyntaxNode node, BlockSyntax body)
{
switch (node)
{
case BasePropertyDeclarationSyntax baseProperty:
var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, body)));
return baseProperty
.TryWithExpressionBody(null)
.WithAccessorList(accessorList)
.TryWithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(baseProperty);
case AccessorDeclarationSyntax accessor:
return accessor
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(accessor);
case BaseMethodDeclarationSyntax baseMethod:
return baseMethod
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(baseMethod);
case LocalFunctionStatementSyntax localFunction:
return localFunction
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(localFunction);
default:
throw ExceptionUtilities.UnexpectedValue(node);
}
}
private async Task<Document> IntroduceLocalDeclarationIntoBlockAsync(
SemanticDocument document,
BlockSyntax block,
ExpressionSyntax expression,
NameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
CancellationToken cancellationToken)
{
declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation);
SyntaxNode scope = block;
// If we're within a non-static local function, our scope for the new local declaration is expanded to include the enclosing member.
var localFunction = block.GetAncestor<LocalFunctionStatementSyntax>();
if (localFunction != null && !localFunction.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.StaticKeyword)))
{
scope = block.GetAncestor<MemberDeclarationSyntax>();
}
var matches = FindMatches(document, expression, document, scope, allOccurrences, cancellationToken);
Debug.Assert(matches.Contains(expression));
(document, matches) = await ComplexifyParentingStatementsAsync(document, matches, cancellationToken).ConfigureAwait(false);
// Our original expression should have been one of the matches, which were tracked as part
// of complexification, so we can retrieve the latest version of the expression here.
expression = document.Root.GetCurrentNode(expression);
var root = document.Root;
ISet<StatementSyntax> allAffectedStatements = new HashSet<StatementSyntax>(matches.SelectMany(expr => GetApplicableStatementAncestors(expr)));
SyntaxNode innermostCommonBlock;
var innermostStatements = new HashSet<StatementSyntax>(matches.Select(expr => GetApplicableStatementAncestors(expr).First()));
if (innermostStatements.Count == 1)
{
// if there was only one match, or all the matches came from the same statement
var statement = innermostStatements.Single();
// and the statement is an embedded statement without a block, we want to generate one
// around this statement rather than continue going up to find an actual block
if (!IsBlockLike(statement.Parent))
{
root = root.TrackNodes(allAffectedStatements.Concat(new SyntaxNode[] { expression, statement }));
root = root.ReplaceNode(root.GetCurrentNode(statement),
SyntaxFactory.Block(root.GetCurrentNode(statement)).WithAdditionalAnnotations(Formatter.Annotation));
expression = root.GetCurrentNode(expression);
allAffectedStatements = allAffectedStatements.Select(root.GetCurrentNode).ToSet();
statement = root.GetCurrentNode(statement);
}
innermostCommonBlock = statement.Parent;
}
else
{
innermostCommonBlock = innermostStatements.FindInnermostCommonNode(IsBlockLike);
}
var firstStatementAffectedIndex = GetFirstStatementAffectedIndex(innermostCommonBlock, matches, GetStatements(innermostCommonBlock).IndexOf(allAffectedStatements.Contains));
var newInnerMostBlock = Rewrite(
document, expression, newLocalName, document, innermostCommonBlock, allOccurrences, cancellationToken);
var statements = InsertWithinTriviaOfNext(GetStatements(newInnerMostBlock), declarationStatement, firstStatementAffectedIndex);
var finalInnerMostBlock = WithStatements(newInnerMostBlock, statements);
var newRoot = root.ReplaceNode(innermostCommonBlock, finalInnerMostBlock);
return document.Document.WithSyntaxRoot(newRoot);
}
private static IEnumerable<StatementSyntax> GetApplicableStatementAncestors(ExpressionSyntax expr)
{
foreach (var statement in expr.GetAncestorsOrThis<StatementSyntax>())
{
// When determining where to put a local, we don't want to put it between the `else`
// and `if` of a compound if-statement.
if (statement.Kind() == SyntaxKind.IfStatement &&
statement.IsParentKind(SyntaxKind.ElseClause))
{
continue;
}
yield return statement;
}
}
private static int GetFirstStatementAffectedIndex(SyntaxNode innermostCommonBlock, ISet<ExpressionSyntax> matches, int firstStatementAffectedIndex)
{
// If a local function is involved, we have to make sure the new declaration is placed:
// 1. Before all calls to local functions that use the variable.
// 2. Before the local function(s) themselves.
// 3. Before all matches, i.e. places in the code where the new declaration will replace existing code.
// Cases (2) and (3) are already covered by the 'firstStatementAffectedIndex' parameter. Thus, all we have to do is ensure we consider (1) when
// determining where to place our new declaration.
// Find all the local functions within the scope that will use the new declaration.
var localFunctions = innermostCommonBlock.DescendantNodes().Where(node => node.IsKind(SyntaxKind.LocalFunctionStatement) && matches.Any(match => match.Span.OverlapsWith(node.Span)));
if (localFunctions.IsEmpty())
{
return firstStatementAffectedIndex;
}
var localFunctionIdentifiers = localFunctions.Select(node => ((LocalFunctionStatementSyntax)node).Identifier.ValueText);
// Find all calls to the applicable local functions within the scope.
var localFunctionCalls = innermostCommonBlock.DescendantNodes().Where(node => node is InvocationExpressionSyntax invocationExpression &&
invocationExpression.Expression.GetRightmostName() != null &&
!invocationExpression.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
localFunctionIdentifiers.Contains(invocationExpression.Expression.GetRightmostName().Identifier.ValueText));
if (localFunctionCalls.IsEmpty())
{
return firstStatementAffectedIndex;
}
// Find which call is the earliest.
var earliestLocalFunctionCall = localFunctionCalls.Min(node => node.SpanStart);
var statementsInBlock = GetStatements(innermostCommonBlock);
// Check if our earliest call is before all local function declarations and all matches, and if so, place our new declaration there.
var earliestLocalFunctionCallIndex = statementsInBlock.IndexOf(s => s.Span.Contains(earliestLocalFunctionCall));
return Math.Min(earliestLocalFunctionCallIndex, firstStatementAffectedIndex);
}
private static SyntaxList<StatementSyntax> InsertWithinTriviaOfNext(
SyntaxList<StatementSyntax> oldStatements,
StatementSyntax newStatement,
int statementIndex)
{
var nextStatement = oldStatements.ElementAtOrDefault(statementIndex);
if (nextStatement == null)
return oldStatements.Insert(statementIndex, newStatement);
// Grab all the trivia before the line the next statement is on and move it to the new node.
var nextStatementLeading = nextStatement.GetLeadingTrivia();
var precedingEndOfLine = nextStatementLeading.LastOrDefault(t => t.Kind() == SyntaxKind.EndOfLineTrivia);
if (precedingEndOfLine == default)
{
return oldStatements.ReplaceRange(
nextStatement, new[] { newStatement, nextStatement });
}
var endOfLineIndex = nextStatementLeading.IndexOf(precedingEndOfLine) + 1;
return oldStatements.ReplaceRange(
nextStatement, new[]
{
newStatement.WithLeadingTrivia(nextStatementLeading.Take(endOfLineIndex)),
nextStatement.WithLeadingTrivia(nextStatementLeading.Skip(endOfLineIndex)),
});
}
private static bool IsBlockLike(SyntaxNode node) => node is BlockSyntax || node is SwitchSectionSyntax;
private static SyntaxList<StatementSyntax> GetStatements(SyntaxNode blockLike)
=> blockLike switch
{
BlockSyntax block => block.Statements,
SwitchSectionSyntax switchSection => switchSection.Statements,
_ => throw ExceptionUtilities.UnexpectedValue(blockLike),
};
private static SyntaxNode WithStatements(SyntaxNode blockLike, SyntaxList<StatementSyntax> statements)
=> blockLike switch
{
BlockSyntax block => block.WithStatements(statements),
SwitchSectionSyntax switchSection => switchSection.WithStatements(statements),
_ => throw ExceptionUtilities.UnexpectedValue(blockLike),
};
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/SuppressIntervalIntrospector.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.Formatting
{
internal readonly struct SuppressIntervalIntrospector :
IIntervalIntrospector<SuppressSpacingData>,
IIntervalIntrospector<SuppressWrappingData>
{
int IIntervalIntrospector<SuppressSpacingData>.GetStart(SuppressSpacingData value)
=> value.TextSpan.Start;
int IIntervalIntrospector<SuppressSpacingData>.GetLength(SuppressSpacingData value)
=> value.TextSpan.Length;
int IIntervalIntrospector<SuppressWrappingData>.GetStart(SuppressWrappingData value)
=> value.TextSpan.Start;
int IIntervalIntrospector<SuppressWrappingData>.GetLength(SuppressWrappingData value)
=> value.TextSpan.Length;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.Formatting
{
internal readonly struct SuppressIntervalIntrospector :
IIntervalIntrospector<SuppressSpacingData>,
IIntervalIntrospector<SuppressWrappingData>
{
int IIntervalIntrospector<SuppressSpacingData>.GetStart(SuppressSpacingData value)
=> value.TextSpan.Start;
int IIntervalIntrospector<SuppressSpacingData>.GetLength(SuppressSpacingData value)
=> value.TextSpan.Length;
int IIntervalIntrospector<SuppressWrappingData>.GetStart(SuppressWrappingData value)
=> value.TextSpan.Start;
int IIntervalIntrospector<SuppressWrappingData>.GetLength(SuppressWrappingData value)
=> value.TextSpan.Length;
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests_Projections.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.VisualStudio.Text.Projection
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
<[UseExportProvider]>
Public Class VisualBasicCompletionCommandHandlerTests_Projections
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSimpleWithJustSubjectBuffer() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Option Strict Off
Option Explicit On
Imports System
Namespace ASP
Public Class _Page_Views_Home_Index_vbhtml
Private Shared __o As Object
Public Sub Execute()
#ExternalSource ("Index.vbhtml", 1)
__o = AppDomain$$
#End ExternalSource
End Sub
End Class
End Namespace
]]></Document>)
state.SendTypeChars(".")
Await state.AssertCompletionSession()
state.SendTypeChars("Curr")
Await state.AssertSelectedCompletionItem(displayText:="CurrentDomain")
state.SendTab()
Assert.Contains("__o = AppDomain.CurrentDomain", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAfterDot() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
{|S2:
Class C
Sub Goo()
System$$
End Sub
End Class
|}]]></Document>)
Dim subjectDocument = state.Workspace.Documents.First()
Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
state.SendTypeCharsToSpecificViewAndBuffer(".", view, buffer)
Await state.AssertCompletionSession(view)
state.SendTypeCharsToSpecificViewAndBuffer("Cons", view, buffer)
Await state.AssertSelectedCompletionItem(displayText:="Console", projectionsView:=view)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInObjectCreationExpression() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
{|S2:
Class C
Sub Goo()
Dim s As New$$
End Sub
End Class
|}]]></Document>)
Dim subjectDocument = state.Workspace.Documents.First()
Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
state.SendTypeCharsToSpecificViewAndBuffer(" ", view, buffer)
Await state.AssertCompletionSession(view)
state.SendTypeCharsToSpecificViewAndBuffer("Str", view, buffer)
Await state.AssertSelectedCompletionItem(displayText:="String", isHardSelected:=True, projectionsView:=view)
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.VisualStudio.Text.Projection
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
<[UseExportProvider]>
Public Class VisualBasicCompletionCommandHandlerTests_Projections
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestSimpleWithJustSubjectBuffer() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
Option Strict Off
Option Explicit On
Imports System
Namespace ASP
Public Class _Page_Views_Home_Index_vbhtml
Private Shared __o As Object
Public Sub Execute()
#ExternalSource ("Index.vbhtml", 1)
__o = AppDomain$$
#End ExternalSource
End Sub
End Class
End Namespace
]]></Document>)
state.SendTypeChars(".")
Await state.AssertCompletionSession()
state.SendTypeChars("Curr")
Await state.AssertSelectedCompletionItem(displayText:="CurrentDomain")
state.SendTab()
Assert.Contains("__o = AppDomain.CurrentDomain", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAfterDot() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
{|S2:
Class C
Sub Goo()
System$$
End Sub
End Class
|}]]></Document>)
Dim subjectDocument = state.Workspace.Documents.First()
Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
state.SendTypeCharsToSpecificViewAndBuffer(".", view, buffer)
Await state.AssertCompletionSession(view)
state.SendTypeCharsToSpecificViewAndBuffer("Cons", view, buffer)
Await state.AssertSelectedCompletionItem(displayText:="Console", projectionsView:=view)
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInObjectCreationExpression() As Task
Using state = TestStateFactory.CreateVisualBasicTestState(
<Document><![CDATA[
{|S2:
Class C
Sub Goo()
Dim s As New$$
End Sub
End Class
|}]]></Document>)
Dim subjectDocument = state.Workspace.Documents.First()
Dim firstProjection = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1: <html>@|}
{|S2:|}
</Document>.NormalizedValue, {subjectDocument}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim topProjectionBuffer = state.Workspace.CreateProjectionBufferDocument(
<Document>
{|S1:|}
{|S2:</html>|}
</Document>.NormalizedValue, {firstProjection}, options:=ProjectionBufferOptions.WritableLiteralSpans)
Dim view = topProjectionBuffer.GetTextView()
Dim buffer = subjectDocument.GetTextBuffer()
state.SendTypeCharsToSpecificViewAndBuffer(" ", view, buffer)
Await state.AssertCompletionSession(view)
state.SendTypeCharsToSpecificViewAndBuffer("Str", view, buffer)
Await state.AssertSelectedCompletionItem(displayText:="String", isHardSelected:=True, projectionsView:=view)
End Using
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Workspaces/CSharp/Portable/CodeGeneration/ArgumentGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class ArgumentGenerator
{
public static ArgumentSyntax GenerateArgument(SyntaxNode argument)
{
if (argument is ExpressionSyntax expression)
{
return SyntaxFactory.Argument(expression);
}
return (ArgumentSyntax)argument;
}
public static ArgumentListSyntax GenerateArgumentList(IList<SyntaxNode> arguments)
=> SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(GenerateArgument)));
public static BracketedArgumentListSyntax GenerateBracketedArgumentList(IList<SyntaxNode> arguments)
=> SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList(arguments.Select(GenerateArgument)));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class ArgumentGenerator
{
public static ArgumentSyntax GenerateArgument(SyntaxNode argument)
{
if (argument is ExpressionSyntax expression)
{
return SyntaxFactory.Argument(expression);
}
return (ArgumentSyntax)argument;
}
public static ArgumentListSyntax GenerateArgumentList(IList<SyntaxNode> arguments)
=> SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(GenerateArgument)));
public static BracketedArgumentListSyntax GenerateBracketedArgumentList(IList<SyntaxNode> arguments)
=> SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList(arguments.Select(GenerateArgument)));
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/FavoritesDataItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using Microsoft.VisualStudio.Debugger;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// DkmDataItem for passing favorites information between ResultProvider.GetChild(...) and
/// ResultProvider.IDkmClrResultProvider.GetResult when evaluating child items in an
/// expansion.
/// </summary>
internal class FavoritesDataItem : DkmDataItem
{
public readonly bool CanFavorite;
public readonly bool IsFavorite;
internal FavoritesDataItem(bool canFavorite, bool isFavorite)
{
CanFavorite = canFavorite;
IsFavorite = isFavorite;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using Microsoft.VisualStudio.Debugger;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// DkmDataItem for passing favorites information between ResultProvider.GetChild(...) and
/// ResultProvider.IDkmClrResultProvider.GetResult when evaluating child items in an
/// expansion.
/// </summary>
internal class FavoritesDataItem : DkmDataItem
{
public readonly bool CanFavorite;
public readonly bool IsFavorite;
internal FavoritesDataItem(bool canFavorite, bool isFavorite)
{
CanFavorite = canFavorite;
IsFavorite = isFavorite;
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/VisualStudio/VisualBasic/Impl/ObjectBrowser/ObjectBrowserLibraryManager.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.VisualStudio.Shell.Interop
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
Imports Microsoft.VisualStudio.ComponentModelHost
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser
Friend Class ObjectBrowserLibraryManager
Inherits AbstractObjectBrowserLibraryManager
Public Sub New(serviceProvider As IServiceProvider, componentModel As IComponentModel, workspace As VisualStudioWorkspace)
MyBase.New(LanguageNames.VisualBasic, Guids.VisualBasicLibraryId, serviceProvider, componentModel, workspace)
End Sub
Friend Overrides Function CreateDescriptionBuilder(
description As IVsObjectBrowserDescription3,
listItem As ObjectListItem,
project As Project
) As AbstractDescriptionBuilder
Return New DescriptionBuilder(description, Me, listItem, project)
End Function
Friend Overrides Function CreateListItemFactory() As AbstractListItemFactory
Return New ListItemFactory()
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
Imports Microsoft.VisualStudio.Shell.Interop
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
Imports Microsoft.VisualStudio.ComponentModelHost
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser
Friend Class ObjectBrowserLibraryManager
Inherits AbstractObjectBrowserLibraryManager
Public Sub New(serviceProvider As IServiceProvider, componentModel As IComponentModel, workspace As VisualStudioWorkspace)
MyBase.New(LanguageNames.VisualBasic, Guids.VisualBasicLibraryId, serviceProvider, componentModel, workspace)
End Sub
Friend Overrides Function CreateDescriptionBuilder(
description As IVsObjectBrowserDescription3,
listItem As ObjectListItem,
project As Project
) As AbstractDescriptionBuilder
Return New DescriptionBuilder(description, Me, listItem, project)
End Function
Friend Overrides Function CreateListItemFactory() As AbstractListItemFactory
Return New ListItemFactory()
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/PreviewChangesDialog_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 System.Threading;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
public class PreviewChangesDialog_OutOfProc : OutOfProcComponent
{
public PreviewChangesDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance)
{
}
/// <summary>
/// Verifies that the Preview Changes dialog is showing with the
/// specified title. The dialog does not have an AutomationId and the
/// title can be changed by features, so callers of this method must
/// specify a title.
/// </summary>
/// <param name="expectedTitle"></param>
public void VerifyOpen(string expectedTitle, TimeSpan? timeout = null)
{
using (var cancellationTokenSource = timeout != null ? new CancellationTokenSource(timeout.Value) : null)
{
var cancellationToken = cancellationTokenSource?.Token ?? CancellationToken.None;
DialogHelpers.FindDialogByName(GetMainWindowHWnd(), expectedTitle, isOpen: true, cancellationToken);
// Wait for application idle to ensure the dialog is fully initialized
VisualStudioInstance.WaitForApplicationIdle(cancellationToken);
}
}
public void VerifyClosed(string expectedTitle)
=> DialogHelpers.FindDialogByName(GetMainWindowHWnd(), expectedTitle, isOpen: false, CancellationToken.None);
public void ClickApplyAndWaitForFeature(string expectedTitle, string featureName)
{
DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), expectedTitle, "Apply");
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, featureName);
}
public void ClickCancel(string expectedTitle)
=> DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), expectedTitle, "Cancel");
private IntPtr GetMainWindowHWnd()
=> VisualStudioInstance.Shell.GetHWnd();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess
{
public class PreviewChangesDialog_OutOfProc : OutOfProcComponent
{
public PreviewChangesDialog_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance)
{
}
/// <summary>
/// Verifies that the Preview Changes dialog is showing with the
/// specified title. The dialog does not have an AutomationId and the
/// title can be changed by features, so callers of this method must
/// specify a title.
/// </summary>
/// <param name="expectedTitle"></param>
public void VerifyOpen(string expectedTitle, TimeSpan? timeout = null)
{
using (var cancellationTokenSource = timeout != null ? new CancellationTokenSource(timeout.Value) : null)
{
var cancellationToken = cancellationTokenSource?.Token ?? CancellationToken.None;
DialogHelpers.FindDialogByName(GetMainWindowHWnd(), expectedTitle, isOpen: true, cancellationToken);
// Wait for application idle to ensure the dialog is fully initialized
VisualStudioInstance.WaitForApplicationIdle(cancellationToken);
}
}
public void VerifyClosed(string expectedTitle)
=> DialogHelpers.FindDialogByName(GetMainWindowHWnd(), expectedTitle, isOpen: false, CancellationToken.None);
public void ClickApplyAndWaitForFeature(string expectedTitle, string featureName)
{
DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), expectedTitle, "Apply");
VisualStudioInstance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, featureName);
}
public void ClickCancel(string expectedTitle)
=> DialogHelpers.PressButtonWithNameFromDialogWithName(GetMainWindowHWnd(), expectedTitle, "Cancel");
private IntPtr GetMainWindowHWnd()
=> VisualStudioInstance.Shell.GetHWnd();
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTrackingServiceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
[UseExportProvider]
public class ActiveStatementTrackingServiceTests : EditingTestBase
{
[Fact, WorkItem(846042, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846042")]
public void MovedOutsideOfMethod1()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
<AS:0>Goo(1);</AS:0>
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
<AS:0>}</AS:0>
static void Goo()
{
// tracking span moves to another method as the user types around it
<TS:0>Goo(1);</TS:0>
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void MovedOutsideOfMethod2()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
<AS:0>Goo(1);</AS:0>
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
<AS:0>Goo(1);</AS:0>
}
static void Goo()
{
<TS:0>Goo(2);</TS:0>
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void MovedOutsideOfLambda1()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
Action a = () => { <AS:0>Goo(1);</AS:0> };
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
Action a = () => { <AS:0>}</AS:0>;
<TS:0>Goo(1);</TS:0>
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void MovedOutsideOfLambda2()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
Action a = () => { <AS:0>Goo(1);</AS:0> };
Action b = () => { Goo(2); };
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
Action a = () => { <AS:0>Goo(1);</AS:0> };
Action b = () => { <TS:0>Goo(2);</TS:0> };
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Theory]
[CombinatorialData]
public async Task TrackingService_GetLatestSpansAsync(bool scheduleInitialTrackingBeforeOpenDoc)
{
var source1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }";
var source2 = "class D { }";
using var workspace = new TestWorkspace();
var span11 = new LinePositionSpan(new LinePosition(0, 10), new LinePosition(0, 15));
var span12 = new LinePositionSpan(new LinePosition(0, 20), new LinePosition(0, 25));
var span21 = new LinePositionSpan(new LinePosition(0, 11), new LinePosition(0, 16));
var span22 = new LinePositionSpan(new LinePosition(0, 21), new LinePosition(0, 26));
var spanProvider = new MockActiveStatementSpanProvider();
spanProvider.GetBaseActiveStatementSpansImpl = (_, documentIds) => ImmutableArray.Create(
ImmutableArray.Create(
new ActiveStatementSpan(0, span11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null),
new ActiveStatementSpan(1, span12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null)),
ImmutableArray<ActiveStatementSpan>.Empty);
spanProvider.GetAdjustedActiveStatementSpansImpl = (document, _) => document.Name switch
{
"1.cs" => ImmutableArray.Create(
new ActiveStatementSpan(0, span21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null),
new ActiveStatementSpan(1, span22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null)),
"2.cs" => ImmutableArray<ActiveStatementSpan>.Empty,
_ => throw ExceptionUtilities.Unreachable
};
var testDocument1 = new TestHostDocument(text: source1, displayName: "1.cs", exportProvider: workspace.ExportProvider, filePath: "1.cs");
var testDocument2 = new TestHostDocument(text: source2, displayName: "2.cs", exportProvider: workspace.ExportProvider, filePath: "2.cs");
workspace.AddTestProject(new TestHostProject(workspace, documents: new[] { testDocument1, testDocument2 }));
// opens the documents
var textBuffer1 = testDocument1.GetTextBuffer();
var textBuffer2 = testDocument2.GetTextBuffer();
var solution = workspace.CurrentSolution;
var project = solution.Projects.Single();
var document1 = project.Documents.Single(d => d.Name == "1.cs");
var document2 = project.Documents.Single(d => d.Name == "2.cs");
var snapshot1 = textBuffer1.CurrentSnapshot;
var snapshot2 = textBuffer2.CurrentSnapshot;
Assert.Same(snapshot1, document1.GetTextSynchronously(CancellationToken.None).FindCorrespondingEditorTextSnapshot());
Assert.Same(snapshot2, document2.GetTextSynchronously(CancellationToken.None).FindCorrespondingEditorTextSnapshot());
var trackingSession = new ActiveStatementTrackingService.TrackingSession(workspace, spanProvider);
if (scheduleInitialTrackingBeforeOpenDoc)
{
await trackingSession.TrackActiveSpansAsync(solution, CancellationToken.None);
var spans1 = trackingSession.Test_GetTrackingSpans();
AssertEx.Equal(new[]
{
$"V0 →←@[10..15): IsNonLeafFrame",
$"V0 →←@[20..25): IsLeafFrame"
}, spans1[document1.FilePath].Select(s => $"{s.Span}: {s.Flags}"));
var spans2 = await trackingSession.GetSpansAsync(solution, document1.Id, document1.FilePath, CancellationToken.None);
AssertEx.Equal(new[] { "(0,10)-(0,15)", "(0,20)-(0,25)" }, spans2.Select(s => s.LineSpan.ToString()));
var spans3 = await trackingSession.GetSpansAsync(solution, document2.Id, document2.FilePath, CancellationToken.None);
Assert.Empty(spans3);
}
var spans4 = await trackingSession.GetAdjustedTrackingSpansAsync(document1, snapshot1, CancellationToken.None);
AssertEx.Equal(new[]
{
$"V0 →←@[11..16): IsNonLeafFrame",
$"V0 →←@[21..26): IsLeafFrame"
}, spans4.Select(s => $"{s.Span}: {s.Flags}"));
AssertEx.Empty(await trackingSession.GetAdjustedTrackingSpansAsync(document2, snapshot2, CancellationToken.None));
if (!scheduleInitialTrackingBeforeOpenDoc)
{
await trackingSession.TrackActiveSpansAsync(solution, CancellationToken.None);
var spans5 = trackingSession.Test_GetTrackingSpans();
AssertEx.Equal(new[]
{
$"V0 →←@[11..16): IsNonLeafFrame",
$"V0 →←@[21..26): IsLeafFrame"
}, spans5[document1.FilePath].Select(s => $"{s.Span}: {s.Flags}"));
}
// we are not able to determine active statements in a document:
spanProvider.GetAdjustedActiveStatementSpansImpl = (_, _) => ImmutableArray<ActiveStatementSpan>.Empty;
var spans6 = await trackingSession.GetAdjustedTrackingSpansAsync(document1, snapshot1, CancellationToken.None);
AssertEx.Equal(new[]
{
$"V0 →←@[11..16): IsNonLeafFrame",
$"V0 →←@[21..26): IsLeafFrame"
}, spans6.Select(s => $"{s.Span}: {s.Flags}"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
[UseExportProvider]
public class ActiveStatementTrackingServiceTests : EditingTestBase
{
[Fact, WorkItem(846042, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846042")]
public void MovedOutsideOfMethod1()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
<AS:0>Goo(1);</AS:0>
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
<AS:0>}</AS:0>
static void Goo()
{
// tracking span moves to another method as the user types around it
<TS:0>Goo(1);</TS:0>
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void MovedOutsideOfMethod2()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
<AS:0>Goo(1);</AS:0>
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
<AS:0>Goo(1);</AS:0>
}
static void Goo()
{
<TS:0>Goo(2);</TS:0>
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void MovedOutsideOfLambda1()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
Action a = () => { <AS:0>Goo(1);</AS:0> };
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
Action a = () => { <AS:0>}</AS:0>;
<TS:0>Goo(1);</TS:0>
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void MovedOutsideOfLambda2()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
Action a = () => { <AS:0>Goo(1);</AS:0> };
Action b = () => { Goo(2); };
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
Action a = () => { <AS:0>Goo(1);</AS:0> };
Action b = () => { <TS:0>Goo(2);</TS:0> };
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Theory]
[CombinatorialData]
public async Task TrackingService_GetLatestSpansAsync(bool scheduleInitialTrackingBeforeOpenDoc)
{
var source1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }";
var source2 = "class D { }";
using var workspace = new TestWorkspace();
var span11 = new LinePositionSpan(new LinePosition(0, 10), new LinePosition(0, 15));
var span12 = new LinePositionSpan(new LinePosition(0, 20), new LinePosition(0, 25));
var span21 = new LinePositionSpan(new LinePosition(0, 11), new LinePosition(0, 16));
var span22 = new LinePositionSpan(new LinePosition(0, 21), new LinePosition(0, 26));
var spanProvider = new MockActiveStatementSpanProvider();
spanProvider.GetBaseActiveStatementSpansImpl = (_, documentIds) => ImmutableArray.Create(
ImmutableArray.Create(
new ActiveStatementSpan(0, span11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null),
new ActiveStatementSpan(1, span12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null)),
ImmutableArray<ActiveStatementSpan>.Empty);
spanProvider.GetAdjustedActiveStatementSpansImpl = (document, _) => document.Name switch
{
"1.cs" => ImmutableArray.Create(
new ActiveStatementSpan(0, span21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null),
new ActiveStatementSpan(1, span22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null)),
"2.cs" => ImmutableArray<ActiveStatementSpan>.Empty,
_ => throw ExceptionUtilities.Unreachable
};
var testDocument1 = new TestHostDocument(text: source1, displayName: "1.cs", exportProvider: workspace.ExportProvider, filePath: "1.cs");
var testDocument2 = new TestHostDocument(text: source2, displayName: "2.cs", exportProvider: workspace.ExportProvider, filePath: "2.cs");
workspace.AddTestProject(new TestHostProject(workspace, documents: new[] { testDocument1, testDocument2 }));
// opens the documents
var textBuffer1 = testDocument1.GetTextBuffer();
var textBuffer2 = testDocument2.GetTextBuffer();
var solution = workspace.CurrentSolution;
var project = solution.Projects.Single();
var document1 = project.Documents.Single(d => d.Name == "1.cs");
var document2 = project.Documents.Single(d => d.Name == "2.cs");
var snapshot1 = textBuffer1.CurrentSnapshot;
var snapshot2 = textBuffer2.CurrentSnapshot;
Assert.Same(snapshot1, document1.GetTextSynchronously(CancellationToken.None).FindCorrespondingEditorTextSnapshot());
Assert.Same(snapshot2, document2.GetTextSynchronously(CancellationToken.None).FindCorrespondingEditorTextSnapshot());
var trackingSession = new ActiveStatementTrackingService.TrackingSession(workspace, spanProvider);
if (scheduleInitialTrackingBeforeOpenDoc)
{
await trackingSession.TrackActiveSpansAsync(solution, CancellationToken.None);
var spans1 = trackingSession.Test_GetTrackingSpans();
AssertEx.Equal(new[]
{
$"V0 →←@[10..15): IsNonLeafFrame",
$"V0 →←@[20..25): IsLeafFrame"
}, spans1[document1.FilePath].Select(s => $"{s.Span}: {s.Flags}"));
var spans2 = await trackingSession.GetSpansAsync(solution, document1.Id, document1.FilePath, CancellationToken.None);
AssertEx.Equal(new[] { "(0,10)-(0,15)", "(0,20)-(0,25)" }, spans2.Select(s => s.LineSpan.ToString()));
var spans3 = await trackingSession.GetSpansAsync(solution, document2.Id, document2.FilePath, CancellationToken.None);
Assert.Empty(spans3);
}
var spans4 = await trackingSession.GetAdjustedTrackingSpansAsync(document1, snapshot1, CancellationToken.None);
AssertEx.Equal(new[]
{
$"V0 →←@[11..16): IsNonLeafFrame",
$"V0 →←@[21..26): IsLeafFrame"
}, spans4.Select(s => $"{s.Span}: {s.Flags}"));
AssertEx.Empty(await trackingSession.GetAdjustedTrackingSpansAsync(document2, snapshot2, CancellationToken.None));
if (!scheduleInitialTrackingBeforeOpenDoc)
{
await trackingSession.TrackActiveSpansAsync(solution, CancellationToken.None);
var spans5 = trackingSession.Test_GetTrackingSpans();
AssertEx.Equal(new[]
{
$"V0 →←@[11..16): IsNonLeafFrame",
$"V0 →←@[21..26): IsLeafFrame"
}, spans5[document1.FilePath].Select(s => $"{s.Span}: {s.Flags}"));
}
// we are not able to determine active statements in a document:
spanProvider.GetAdjustedActiveStatementSpansImpl = (_, _) => ImmutableArray<ActiveStatementSpan>.Empty;
var spans6 = await trackingSession.GetAdjustedTrackingSpansAsync(document1, snapshot1, CancellationToken.None);
AssertEx.Equal(new[]
{
$"V0 →←@[11..16): IsNonLeafFrame",
$"V0 →←@[21..26): IsLeafFrame"
}, spans6.Select(s => $"{s.Span}: {s.Flags}"));
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpLanguageInstructionDecoder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
[DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]
internal sealed class CSharpLanguageInstructionDecoder : LanguageInstructionDecoder<CSharpCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol, ParameterSymbol>
{
public CSharpLanguageInstructionDecoder()
: base(CSharpInstructionDecoder.Instance)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
[DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]
internal sealed class CSharpLanguageInstructionDecoder : LanguageInstructionDecoder<CSharpCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol, ParameterSymbol>
{
public CSharpLanguageInstructionDecoder()
: base(CSharpInstructionDecoder.Instance)
{
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/CSharpTest2/Recommendations/SByteKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Completion.Providers;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class SByteKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* goo = stackalloc $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFixedStatement()
{
await VerifyKeywordAsync(
@"fixed ($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref int x = ref $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType4()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IGoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo is $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo as $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLocalVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForeachVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUsingVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFromVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInJoinVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Goo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Goo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNewInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTypeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInSizeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$"));
}
[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(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
=> await VerifyKeywordAsync(@"class c { async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
=> await VerifyAbsenceAsync(@"class c { async async $$ }");
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task Preselection()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
Helper($$)
}
static void Helper(sbyte x) { }
}
");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinType()
{
await VerifyKeywordAsync(@"
class Program
{
($$
}");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinMember()
{
await VerifyKeywordAsync(@"
class Program
{
void Method()
{
($$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerType()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterComma()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<int, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterModifier()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegateAsterisk()
{
await VerifyAbsenceAsync(@"
class C
{
delegate*$$");
}
[WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))]
public async Task TestAfterKeywordIndicatingLocalFunction(string keyword)
{
await VerifyKeywordAsync(AddInsideMethod($@"
{keyword} $$"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Completion.Providers;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class SByteKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* goo = stackalloc $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFixedStatement()
{
await VerifyKeywordAsync(
@"fixed ($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref int x = ref $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType4()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IGoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo is $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo as $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLocalVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForeachVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUsingVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFromVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInJoinVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Goo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Goo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNewInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTypeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInSizeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$"));
}
[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(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
=> await VerifyKeywordAsync(@"class c { async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
=> await VerifyAbsenceAsync(@"class c { async async $$ }");
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task Preselection()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
Helper($$)
}
static void Helper(sbyte x) { }
}
");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinType()
{
await VerifyKeywordAsync(@"
class Program
{
($$
}");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinMember()
{
await VerifyKeywordAsync(@"
class Program
{
void Method()
{
($$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerType()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterComma()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<int, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterModifier()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegateAsterisk()
{
await VerifyAbsenceAsync(@"
class C
{
delegate*$$");
}
[WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))]
public async Task TestAfterKeywordIndicatingLocalFunction(string keyword)
{
await VerifyKeywordAsync(AddInsideMethod($@"
{keyword} $$"));
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/Core.Wpf/InlineRename/Dashboard/DashboardAdornmentManager.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal class DashboardAdornmentManager : IDisposable
{
private readonly IWpfTextView _textView;
private readonly InlineRenameService _renameService;
private readonly IEditorFormatMapService _editorFormatMapService;
private readonly IAdornmentLayer _adornmentLayer;
private static readonly ConditionalWeakTable<InlineRenameSession, DashboardViewModel> s_createdViewModels =
new ConditionalWeakTable<InlineRenameSession, DashboardViewModel>();
public DashboardAdornmentManager(
InlineRenameService renameService,
IEditorFormatMapService editorFormatMapService,
IWpfTextView textView)
{
_renameService = renameService;
_editorFormatMapService = editorFormatMapService;
_textView = textView;
_adornmentLayer = textView.GetAdornmentLayer(DashboardAdornmentProvider.AdornmentLayerName);
_renameService.ActiveSessionChanged += OnActiveSessionChanged;
_textView.Closed += OnTextViewClosed;
UpdateAdornments();
}
public void Dispose()
{
_renameService.ActiveSessionChanged -= OnActiveSessionChanged;
_textView.Closed -= OnTextViewClosed;
}
private void OnTextViewClosed(object sender, EventArgs e)
=> Dispose();
private void OnActiveSessionChanged(object sender, EventArgs e)
=> UpdateAdornments();
private void UpdateAdornments()
{
_adornmentLayer.RemoveAllAdornments();
if (_renameService.ActiveSession != null &&
ViewIncludesBufferFromWorkspace(_textView, _renameService.ActiveSession.Workspace))
{
var newAdornment = new Dashboard(
s_createdViewModels.GetValue(_renameService.ActiveSession, session => new DashboardViewModel(session)),
_editorFormatMapService,
_textView);
_adornmentLayer.AddAdornment(AdornmentPositioningBehavior.ViewportRelative, null, null, newAdornment,
(tag, adornment) => ((Dashboard)adornment).Dispose());
}
}
private static bool ViewIncludesBufferFromWorkspace(IWpfTextView textView, Workspace workspace)
{
return textView.BufferGraph.GetTextBuffers(b => GetWorkspace(b.AsTextContainer()) == workspace)
.Any();
}
private static Workspace GetWorkspace(SourceTextContainer textContainer)
{
Workspace.TryGetWorkspace(textContainer, out var workspace);
return workspace;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal class DashboardAdornmentManager : IDisposable
{
private readonly IWpfTextView _textView;
private readonly InlineRenameService _renameService;
private readonly IEditorFormatMapService _editorFormatMapService;
private readonly IAdornmentLayer _adornmentLayer;
private static readonly ConditionalWeakTable<InlineRenameSession, DashboardViewModel> s_createdViewModels =
new ConditionalWeakTable<InlineRenameSession, DashboardViewModel>();
public DashboardAdornmentManager(
InlineRenameService renameService,
IEditorFormatMapService editorFormatMapService,
IWpfTextView textView)
{
_renameService = renameService;
_editorFormatMapService = editorFormatMapService;
_textView = textView;
_adornmentLayer = textView.GetAdornmentLayer(DashboardAdornmentProvider.AdornmentLayerName);
_renameService.ActiveSessionChanged += OnActiveSessionChanged;
_textView.Closed += OnTextViewClosed;
UpdateAdornments();
}
public void Dispose()
{
_renameService.ActiveSessionChanged -= OnActiveSessionChanged;
_textView.Closed -= OnTextViewClosed;
}
private void OnTextViewClosed(object sender, EventArgs e)
=> Dispose();
private void OnActiveSessionChanged(object sender, EventArgs e)
=> UpdateAdornments();
private void UpdateAdornments()
{
_adornmentLayer.RemoveAllAdornments();
if (_renameService.ActiveSession != null &&
ViewIncludesBufferFromWorkspace(_textView, _renameService.ActiveSession.Workspace))
{
var newAdornment = new Dashboard(
s_createdViewModels.GetValue(_renameService.ActiveSession, session => new DashboardViewModel(session)),
_editorFormatMapService,
_textView);
_adornmentLayer.AddAdornment(AdornmentPositioningBehavior.ViewportRelative, null, null, newAdornment,
(tag, adornment) => ((Dashboard)adornment).Dispose());
}
}
private static bool ViewIncludesBufferFromWorkspace(IWpfTextView textView, Workspace workspace)
{
return textView.BufferGraph.GetTextBuffers(b => GetWorkspace(b.AsTextContainer()) == workspace)
.Any();
}
private static Workspace GetWorkspace(SourceTextContainer textContainer)
{
Workspace.TryGetWorkspace(textContainer, out var workspace);
return workspace;
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/CSharp/Portable/Emitter/Model/FieldSymbolAdapter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class
#if DEBUG
FieldSymbolAdapter : SymbolAdapter,
#else
FieldSymbol :
#endif
Cci.IFieldReference,
Cci.IFieldDefinition,
Cci.ITypeMemberReference,
Cci.ITypeDefinitionMember,
Cci.ISpecializedFieldReference
{
Cci.ITypeReference Cci.IFieldReference.GetType(EmitContext context)
{
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
TypeWithAnnotations fieldTypeWithAnnotations = AdaptedFieldSymbol.TypeWithAnnotations;
var customModifiers = fieldTypeWithAnnotations.CustomModifiers;
var isFixed = AdaptedFieldSymbol.IsFixedSizeBuffer;
var implType = isFixed ? AdaptedFieldSymbol.FixedImplementationType(moduleBeingBuilt) : fieldTypeWithAnnotations.Type;
var type = moduleBeingBuilt.Translate(implType,
syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode,
diagnostics: context.Diagnostics);
if (isFixed || customModifiers.Length == 0)
{
return type;
}
else
{
return new Cci.ModifiedTypeReference(type, ImmutableArray<Cci.ICustomModifier>.CastUp(customModifiers));
}
}
Cci.IFieldDefinition Cci.IFieldReference.GetResolvedField(EmitContext context)
{
return ResolvedFieldImpl((PEModuleBuilder)context.Module);
}
private Cci.IFieldDefinition ResolvedFieldImpl(PEModuleBuilder moduleBeingBuilt)
{
Debug.Assert(this.IsDefinitionOrDistinct());
if (AdaptedFieldSymbol.IsDefinition &&
AdaptedFieldSymbol.ContainingModule == moduleBeingBuilt.SourceModule)
{
return this;
}
return null;
}
Cci.ISpecializedFieldReference Cci.IFieldReference.AsSpecializedFieldReference
{
get
{
Debug.Assert(this.IsDefinitionOrDistinct());
if (!AdaptedFieldSymbol.IsDefinition)
{
return this;
}
return null;
}
}
Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)
{
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
Debug.Assert(this.IsDefinitionOrDistinct());
return moduleBeingBuilt.Translate(AdaptedFieldSymbol.ContainingType,
syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode,
diagnostics: context.Diagnostics,
needDeclaration: AdaptedFieldSymbol.IsDefinition);
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
Debug.Assert(this.IsDefinitionOrDistinct());
if (!AdaptedFieldSymbol.IsDefinition)
{
visitor.Visit((Cci.ISpecializedFieldReference)this);
}
else if (AdaptedFieldSymbol.ContainingModule == ((PEModuleBuilder)visitor.Context.Module).SourceModule)
{
visitor.Visit((Cci.IFieldDefinition)this);
}
else
{
visitor.Visit((Cci.IFieldReference)this);
}
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
return ResolvedFieldImpl(moduleBeingBuilt);
}
string Cci.INamedEntity.Name
{
get
{
return AdaptedFieldSymbol.MetadataName;
}
}
bool Cci.IFieldReference.IsContextualNamedEntity
{
get
{
return false;
}
}
MetadataConstant Cci.IFieldDefinition.GetCompileTimeValue(EmitContext context)
{
CheckDefinitionInvariant();
return GetMetadataConstantValue(context);
}
internal MetadataConstant GetMetadataConstantValue(EmitContext context)
{
// A constant field of type decimal is not treated as a compile time value in CLR,
// so check if it is a metadata constant, not just a constant to exclude decimals.
if (AdaptedFieldSymbol.IsMetadataConstant)
{
// NOTE: We would like to be able to assert that the constant value of this field
// is not bad (i.e. ConstantValue.Bad) if it is being consumed by CCI, but we can't
// because this method is called by the ReferenceIndexer in the metadata-only case
// (and we specifically don't want to prevent metadata-only emit because of a bad
// constant). If the constant value is bad, we'll end up exposing null to CCI.
return ((PEModuleBuilder)context.Module).CreateConstant(AdaptedFieldSymbol.Type, AdaptedFieldSymbol.ConstantValue,
syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode,
diagnostics: context.Diagnostics);
}
return null;
}
ImmutableArray<byte> Cci.IFieldDefinition.MappedData
{
get
{
CheckDefinitionInvariant();
return default(ImmutableArray<byte>);
}
}
bool Cci.IFieldDefinition.IsCompileTimeConstant
{
get
{
CheckDefinitionInvariant();
// A constant field of type decimal is not treated as a compile time value in CLR,
// so check if it is a metadata constant, not just a constant to exclude decimals.
return AdaptedFieldSymbol.IsMetadataConstant;
}
}
bool Cci.IFieldDefinition.IsNotSerialized
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.IsNotSerialized;
}
}
bool Cci.IFieldDefinition.IsReadOnly
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.IsReadOnly || (AdaptedFieldSymbol.IsConst && !AdaptedFieldSymbol.IsMetadataConstant);
}
}
bool Cci.IFieldDefinition.IsRuntimeSpecial
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.HasRuntimeSpecialName;
}
}
bool Cci.IFieldDefinition.IsSpecialName
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.HasSpecialName;
}
}
bool Cci.IFieldDefinition.IsStatic
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.IsStatic;
}
}
bool Cci.IFieldDefinition.IsMarshalledExplicitly
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.IsMarshalledExplicitly;
}
}
Cci.IMarshallingInformation Cci.IFieldDefinition.MarshallingInformation
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.MarshallingInformation;
}
}
ImmutableArray<byte> Cci.IFieldDefinition.MarshallingDescriptor
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.MarshallingDescriptor;
}
}
int Cci.IFieldDefinition.Offset
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.TypeLayoutOffset ?? 0;
}
}
Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.ContainingType.GetCciAdapter();
}
}
Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility
{
get
{
CheckDefinitionInvariant();
return PEModuleBuilder.MemberVisibility(AdaptedFieldSymbol);
}
}
Cci.IFieldReference Cci.ISpecializedFieldReference.UnspecializedVersion
{
get
{
Debug.Assert(!AdaptedFieldSymbol.IsDefinition);
return AdaptedFieldSymbol.OriginalDefinition.GetCciAdapter();
}
}
}
internal partial class FieldSymbol
{
#if DEBUG
private FieldSymbolAdapter _lazyAdapter;
protected sealed override SymbolAdapter GetCciAdapterImpl() => GetCciAdapter();
internal new FieldSymbolAdapter GetCciAdapter()
{
if (_lazyAdapter is null)
{
return InterlockedOperations.Initialize(ref _lazyAdapter, new FieldSymbolAdapter(this));
}
return _lazyAdapter;
}
#else
internal FieldSymbol AdaptedFieldSymbol => this;
internal new FieldSymbol GetCciAdapter()
{
return this;
}
#endif
internal virtual bool IsMarshalledExplicitly
{
get
{
CheckDefinitionInvariant();
return this.MarshallingInformation != null;
}
}
internal virtual ImmutableArray<byte> MarshallingDescriptor
{
get
{
CheckDefinitionInvariant();
return default(ImmutableArray<byte>);
}
}
}
#if DEBUG
internal partial class FieldSymbolAdapter
{
internal FieldSymbolAdapter(FieldSymbol underlyingFieldSymbol)
{
AdaptedFieldSymbol = underlyingFieldSymbol;
}
internal sealed override Symbol AdaptedSymbol => AdaptedFieldSymbol;
internal FieldSymbol AdaptedFieldSymbol { get; }
}
#endif
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class
#if DEBUG
FieldSymbolAdapter : SymbolAdapter,
#else
FieldSymbol :
#endif
Cci.IFieldReference,
Cci.IFieldDefinition,
Cci.ITypeMemberReference,
Cci.ITypeDefinitionMember,
Cci.ISpecializedFieldReference
{
Cci.ITypeReference Cci.IFieldReference.GetType(EmitContext context)
{
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
TypeWithAnnotations fieldTypeWithAnnotations = AdaptedFieldSymbol.TypeWithAnnotations;
var customModifiers = fieldTypeWithAnnotations.CustomModifiers;
var isFixed = AdaptedFieldSymbol.IsFixedSizeBuffer;
var implType = isFixed ? AdaptedFieldSymbol.FixedImplementationType(moduleBeingBuilt) : fieldTypeWithAnnotations.Type;
var type = moduleBeingBuilt.Translate(implType,
syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode,
diagnostics: context.Diagnostics);
if (isFixed || customModifiers.Length == 0)
{
return type;
}
else
{
return new Cci.ModifiedTypeReference(type, ImmutableArray<Cci.ICustomModifier>.CastUp(customModifiers));
}
}
Cci.IFieldDefinition Cci.IFieldReference.GetResolvedField(EmitContext context)
{
return ResolvedFieldImpl((PEModuleBuilder)context.Module);
}
private Cci.IFieldDefinition ResolvedFieldImpl(PEModuleBuilder moduleBeingBuilt)
{
Debug.Assert(this.IsDefinitionOrDistinct());
if (AdaptedFieldSymbol.IsDefinition &&
AdaptedFieldSymbol.ContainingModule == moduleBeingBuilt.SourceModule)
{
return this;
}
return null;
}
Cci.ISpecializedFieldReference Cci.IFieldReference.AsSpecializedFieldReference
{
get
{
Debug.Assert(this.IsDefinitionOrDistinct());
if (!AdaptedFieldSymbol.IsDefinition)
{
return this;
}
return null;
}
}
Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)
{
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
Debug.Assert(this.IsDefinitionOrDistinct());
return moduleBeingBuilt.Translate(AdaptedFieldSymbol.ContainingType,
syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode,
diagnostics: context.Diagnostics,
needDeclaration: AdaptedFieldSymbol.IsDefinition);
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
Debug.Assert(this.IsDefinitionOrDistinct());
if (!AdaptedFieldSymbol.IsDefinition)
{
visitor.Visit((Cci.ISpecializedFieldReference)this);
}
else if (AdaptedFieldSymbol.ContainingModule == ((PEModuleBuilder)visitor.Context.Module).SourceModule)
{
visitor.Visit((Cci.IFieldDefinition)this);
}
else
{
visitor.Visit((Cci.IFieldReference)this);
}
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
return ResolvedFieldImpl(moduleBeingBuilt);
}
string Cci.INamedEntity.Name
{
get
{
return AdaptedFieldSymbol.MetadataName;
}
}
bool Cci.IFieldReference.IsContextualNamedEntity
{
get
{
return false;
}
}
MetadataConstant Cci.IFieldDefinition.GetCompileTimeValue(EmitContext context)
{
CheckDefinitionInvariant();
return GetMetadataConstantValue(context);
}
internal MetadataConstant GetMetadataConstantValue(EmitContext context)
{
// A constant field of type decimal is not treated as a compile time value in CLR,
// so check if it is a metadata constant, not just a constant to exclude decimals.
if (AdaptedFieldSymbol.IsMetadataConstant)
{
// NOTE: We would like to be able to assert that the constant value of this field
// is not bad (i.e. ConstantValue.Bad) if it is being consumed by CCI, but we can't
// because this method is called by the ReferenceIndexer in the metadata-only case
// (and we specifically don't want to prevent metadata-only emit because of a bad
// constant). If the constant value is bad, we'll end up exposing null to CCI.
return ((PEModuleBuilder)context.Module).CreateConstant(AdaptedFieldSymbol.Type, AdaptedFieldSymbol.ConstantValue,
syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode,
diagnostics: context.Diagnostics);
}
return null;
}
ImmutableArray<byte> Cci.IFieldDefinition.MappedData
{
get
{
CheckDefinitionInvariant();
return default(ImmutableArray<byte>);
}
}
bool Cci.IFieldDefinition.IsCompileTimeConstant
{
get
{
CheckDefinitionInvariant();
// A constant field of type decimal is not treated as a compile time value in CLR,
// so check if it is a metadata constant, not just a constant to exclude decimals.
return AdaptedFieldSymbol.IsMetadataConstant;
}
}
bool Cci.IFieldDefinition.IsNotSerialized
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.IsNotSerialized;
}
}
bool Cci.IFieldDefinition.IsReadOnly
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.IsReadOnly || (AdaptedFieldSymbol.IsConst && !AdaptedFieldSymbol.IsMetadataConstant);
}
}
bool Cci.IFieldDefinition.IsRuntimeSpecial
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.HasRuntimeSpecialName;
}
}
bool Cci.IFieldDefinition.IsSpecialName
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.HasSpecialName;
}
}
bool Cci.IFieldDefinition.IsStatic
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.IsStatic;
}
}
bool Cci.IFieldDefinition.IsMarshalledExplicitly
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.IsMarshalledExplicitly;
}
}
Cci.IMarshallingInformation Cci.IFieldDefinition.MarshallingInformation
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.MarshallingInformation;
}
}
ImmutableArray<byte> Cci.IFieldDefinition.MarshallingDescriptor
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.MarshallingDescriptor;
}
}
int Cci.IFieldDefinition.Offset
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.TypeLayoutOffset ?? 0;
}
}
Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition
{
get
{
CheckDefinitionInvariant();
return AdaptedFieldSymbol.ContainingType.GetCciAdapter();
}
}
Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility
{
get
{
CheckDefinitionInvariant();
return PEModuleBuilder.MemberVisibility(AdaptedFieldSymbol);
}
}
Cci.IFieldReference Cci.ISpecializedFieldReference.UnspecializedVersion
{
get
{
Debug.Assert(!AdaptedFieldSymbol.IsDefinition);
return AdaptedFieldSymbol.OriginalDefinition.GetCciAdapter();
}
}
}
internal partial class FieldSymbol
{
#if DEBUG
private FieldSymbolAdapter _lazyAdapter;
protected sealed override SymbolAdapter GetCciAdapterImpl() => GetCciAdapter();
internal new FieldSymbolAdapter GetCciAdapter()
{
if (_lazyAdapter is null)
{
return InterlockedOperations.Initialize(ref _lazyAdapter, new FieldSymbolAdapter(this));
}
return _lazyAdapter;
}
#else
internal FieldSymbol AdaptedFieldSymbol => this;
internal new FieldSymbol GetCciAdapter()
{
return this;
}
#endif
internal virtual bool IsMarshalledExplicitly
{
get
{
CheckDefinitionInvariant();
return this.MarshallingInformation != null;
}
}
internal virtual ImmutableArray<byte> MarshallingDescriptor
{
get
{
CheckDefinitionInvariant();
return default(ImmutableArray<byte>);
}
}
}
#if DEBUG
internal partial class FieldSymbolAdapter
{
internal FieldSymbolAdapter(FieldSymbol underlyingFieldSymbol)
{
AdaptedFieldSymbol = underlyingFieldSymbol;
}
internal sealed override Symbol AdaptedSymbol => AdaptedFieldSymbol;
internal FieldSymbol AdaptedFieldSymbol { get; }
}
#endif
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LoweredDynamicOperationFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class LoweredDynamicOperationFactory
{
private readonly SyntheticBoundNodeFactory _factory;
private readonly int _methodOrdinal;
private readonly int _localFunctionOrdinal;
private NamedTypeSymbol? _currentDynamicCallSiteContainer;
private int _callSiteIdDispenser;
internal LoweredDynamicOperationFactory(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal = -1)
{
Debug.Assert(factory != null);
_factory = factory;
_methodOrdinal = methodOrdinal;
_localFunctionOrdinal = localFunctionOrdinal;
}
public int MethodOrdinal => _methodOrdinal;
// We could read the values of the following enums from metadata instead of hardcoding them here but
// - they can never change since existing programs have the values inlined and would be broken if the values changed their meaning,
// - if any new flags are added to the runtime binder the compiler will change as well to produce them.
// The only scenario that is not supported by hardcoding the values is when a completely new Framework is created
// that redefines these constants and is not supposed to run existing programs.
/// <summary>
/// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags.
/// </summary>
[Flags]
private enum CSharpBinderFlags
{
None = 0,
CheckedContext = 1,
InvokeSimpleName = 2,
InvokeSpecialName = 4,
BinaryOperationLogical = 8,
ConvertExplicit = 16,
ConvertArrayIndex = 32,
ResultIndexed = 64,
ValueFromCompoundAssignment = 128,
ResultDiscarded = 256,
}
/// <summary>
/// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags.
/// </summary>
[Flags]
private enum CSharpArgumentInfoFlags
{
None = 0,
UseCompileTimeType = 1,
Constant = 2,
NamedArgument = 4,
IsRef = 8,
IsOut = 16,
IsStaticType = 32,
}
internal LoweredDynamicOperation MakeDynamicConversion(
BoundExpression loweredOperand,
bool isExplicit,
bool isArrayIndex,
bool isChecked,
TypeSymbol resultType)
{
_factory.Syntax = loweredOperand.Syntax;
CSharpBinderFlags binderFlags = 0;
Debug.Assert(!isExplicit || !isArrayIndex);
if (isChecked)
{
binderFlags |= CSharpBinderFlags.CheckedContext;
}
if (isExplicit)
{
binderFlags |= CSharpBinderFlags.ConvertExplicit;
}
if (isArrayIndex)
{
binderFlags |= CSharpBinderFlags.ConvertArrayIndex;
}
var loweredArguments = ImmutableArray.Create(loweredOperand);
var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Convert, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// target type:
_factory.Typeof(resultType),
// context:
_factory.TypeofDynamicOperationContextType()
});
return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType);
}
internal LoweredDynamicOperation MakeDynamicUnaryOperator(
UnaryOperatorKind operatorKind,
BoundExpression loweredOperand,
TypeSymbol resultType)
{
Debug.Assert(operatorKind.IsDynamic());
_factory.Syntax = loweredOperand.Syntax;
CSharpBinderFlags binderFlags = 0;
if (operatorKind.IsChecked())
{
binderFlags |= CSharpBinderFlags.CheckedContext;
}
var loweredArguments = ImmutableArray.Create(loweredOperand);
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// expression type:
_factory.Literal((int)operatorKind.ToExpressionType()),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments)
}) : null;
return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType);
}
internal LoweredDynamicOperation MakeDynamicBinaryOperator(
BinaryOperatorKind operatorKind,
BoundExpression loweredLeft,
BoundExpression loweredRight,
bool isCompoundAssignment,
TypeSymbol resultType)
{
Debug.Assert(operatorKind.IsDynamic());
_factory.Syntax = loweredLeft.Syntax;
CSharpBinderFlags binderFlags = 0;
if (operatorKind.IsChecked())
{
binderFlags |= CSharpBinderFlags.CheckedContext;
}
if (operatorKind.IsLogical())
{
binderFlags |= CSharpBinderFlags.BinaryOperationLogical;
}
var loweredArguments = ImmutableArray.Create<BoundExpression>(loweredLeft, loweredRight);
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// expression type:
_factory.Literal((int)operatorKind.ToExpressionType(isCompoundAssignment)),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments)
}) : null;
return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType);
}
internal LoweredDynamicOperation MakeDynamicMemberInvocation(
string name,
BoundExpression loweredReceiver,
ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames,
ImmutableArray<RefKind> refKinds,
bool hasImplicitReceiver,
bool resultDiscarded)
{
_factory.Syntax = loweredReceiver.Syntax;
Debug.Assert(_factory.TopLevelMethod is { });
CSharpBinderFlags binderFlags = 0;
if (hasImplicitReceiver && _factory.TopLevelMethod.RequiresInstanceReceiver)
{
binderFlags |= CSharpBinderFlags.InvokeSimpleName;
}
TypeSymbol resultType;
if (resultDiscarded)
{
binderFlags |= CSharpBinderFlags.ResultDiscarded;
resultType = _factory.SpecialType(SpecialType.System_Void);
}
else
{
resultType = AssemblySymbol.DynamicType;
}
RefKind receiverRefKind;
bool receiverIsStaticType;
if (loweredReceiver.Kind == BoundKind.TypeExpression)
{
loweredReceiver = _factory.Typeof(((BoundTypeExpression)loweredReceiver).Type);
receiverRefKind = RefKind.None;
receiverIsStaticType = true;
}
else
{
receiverRefKind = GetReceiverRefKind(loweredReceiver);
receiverIsStaticType = false;
}
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// member name:
_factory.Literal(name),
// type arguments:
typeArgumentsWithAnnotations.IsDefaultOrEmpty ?
_factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)) :
_factory.ArrayOrEmpty(_factory.WellKnownType(WellKnownType.System_Type), _factory.TypeOfs(typeArgumentsWithAnnotations)),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverRefKind, receiverIsStaticType)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, receiverRefKind, loweredArguments, refKinds, null, resultType);
}
internal LoweredDynamicOperation MakeDynamicEventAccessorInvocation(
string accessorName,
BoundExpression loweredReceiver,
BoundExpression loweredHandler)
{
_factory.Syntax = loweredReceiver.Syntax;
CSharpBinderFlags binderFlags = CSharpBinderFlags.InvokeSpecialName | CSharpBinderFlags.ResultDiscarded;
var loweredArguments = ImmutableArray<BoundExpression>.Empty;
var resultType = AssemblySymbol.DynamicType;
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// member name:
_factory.Literal(accessorName),
// type arguments:
_factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredHandler)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredHandler, resultType);
}
internal LoweredDynamicOperation MakeDynamicInvocation(
BoundExpression loweredReceiver,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames,
ImmutableArray<RefKind> refKinds,
bool resultDiscarded)
{
_factory.Syntax = loweredReceiver.Syntax;
TypeSymbol resultType;
CSharpBinderFlags binderFlags = 0;
if (resultDiscarded)
{
binderFlags |= CSharpBinderFlags.ResultDiscarded;
resultType = _factory.SpecialType(SpecialType.System_Void);
}
else
{
resultType = AssemblySymbol.DynamicType;
}
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Invoke, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType);
}
internal LoweredDynamicOperation MakeDynamicConstructorInvocation(
SyntaxNode syntax,
TypeSymbol type,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames,
ImmutableArray<RefKind> refKinds)
{
_factory.Syntax = syntax;
var loweredReceiver = _factory.Typeof(type);
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor, new[]
{
// flags:
_factory.Literal(0),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverIsStaticType: true)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, type);
}
internal LoweredDynamicOperation MakeDynamicGetMember(
BoundExpression loweredReceiver,
string name,
bool resultIndexed)
{
_factory.Syntax = loweredReceiver.Syntax;
CSharpBinderFlags binderFlags = 0;
if (resultIndexed)
{
binderFlags |= CSharpBinderFlags.ResultIndexed;
}
var loweredArguments = ImmutableArray<BoundExpression>.Empty;
var resultType = DynamicTypeSymbol.Instance;
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetMember, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// name:
_factory.Literal(name),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType);
}
internal LoweredDynamicOperation MakeDynamicSetMember(
BoundExpression loweredReceiver,
string name,
BoundExpression loweredRight,
bool isCompoundAssignment = false,
bool isChecked = false)
{
_factory.Syntax = loweredReceiver.Syntax;
CSharpBinderFlags binderFlags = 0;
if (isCompoundAssignment)
{
binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment;
if (isChecked)
{
binderFlags |= CSharpBinderFlags.CheckedContext;
}
}
var loweredArguments = ImmutableArray<BoundExpression>.Empty;
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetMember, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// name:
_factory.Literal(name),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredRight)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredRight, AssemblySymbol.DynamicType);
}
internal LoweredDynamicOperation MakeDynamicGetIndex(
BoundExpression loweredReceiver,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames,
ImmutableArray<RefKind> refKinds)
{
_factory.Syntax = loweredReceiver.Syntax;
var resultType = DynamicTypeSymbol.Instance;
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetIndex, new[]
{
// flags (unused):
_factory.Literal((int)CSharpBinderFlags.None),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver: loweredReceiver)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType);
}
internal LoweredDynamicOperation MakeDynamicSetIndex(
BoundExpression loweredReceiver,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames,
ImmutableArray<RefKind> refKinds,
BoundExpression loweredRight,
bool isCompoundAssignment = false,
bool isChecked = false)
{
CSharpBinderFlags binderFlags = 0;
if (isCompoundAssignment)
{
binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment;
if (isChecked)
{
binderFlags |= CSharpBinderFlags.CheckedContext;
}
}
var loweredReceiverRefKind = GetReceiverRefKind(loweredReceiver);
var resultType = DynamicTypeSymbol.Instance;
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetIndex, new[]
{
// flags (unused):
_factory.Literal((int)binderFlags),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, loweredReceiverRefKind, loweredRight: loweredRight)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, loweredReceiverRefKind, loweredArguments, refKinds, loweredRight, resultType);
}
internal LoweredDynamicOperation MakeDynamicIsEventTest(string name, BoundExpression loweredReceiver)
{
_factory.Syntax = loweredReceiver.Syntax;
var resultType = _factory.SpecialType(SpecialType.System_Boolean);
var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__IsEvent, new[]
{
// flags (unused):
_factory.Literal((int)0),
// member name:
_factory.Literal(name),
// context:
_factory.TypeofDynamicOperationContextType()
});
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, ImmutableArray<BoundExpression>.Empty, default(ImmutableArray<RefKind>), null, resultType);
}
private MethodSymbol GetArgumentInfoFactory()
{
return _factory.WellKnownMethod(WellKnownMember.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create);
}
private BoundExpression? MakeBinderConstruction(WellKnownMember factoryMethod, BoundExpression[] args)
{
var binderFactory = _factory.WellKnownMember(factoryMethod);
if (binderFactory is null)
{
return null;
}
return _factory.Call(null, (MethodSymbol)binderFactory, args.AsImmutableOrNull());
}
// If we have a struct calling object, then we need to pass it by ref, provided
// that it was an Lvalue. For instance,
// Struct s = ...; dynamic d = ...;
// s.M(d); // becomes Site(ref s, d)
// however
// dynamic d = ...;
// GetS().M(d); // becomes Site(GetS(), d) without ref on the target obj arg
internal static RefKind GetReceiverRefKind(BoundExpression loweredReceiver)
{
Debug.Assert(loweredReceiver.Type is { });
if (!loweredReceiver.Type.IsValueType)
{
return RefKind.None;
}
switch (loweredReceiver.Kind)
{
case BoundKind.Local:
case BoundKind.Parameter:
case BoundKind.ArrayAccess:
case BoundKind.ThisReference:
case BoundKind.PointerIndirectionOperator:
case BoundKind.PointerElementAccess:
case BoundKind.RefValueOperator:
return RefKind.Ref;
case BoundKind.BaseReference:
// base dynamic dispatch is not supported, an error has already been reported
case BoundKind.TypeExpression:
throw ExceptionUtilities.UnexpectedValue(loweredReceiver.Kind);
}
return RefKind.None;
}
internal BoundExpression MakeCallSiteArgumentInfos(
MethodSymbol argumentInfoFactory,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames = default(ImmutableArray<string>),
ImmutableArray<RefKind> refKinds = default(ImmutableArray<RefKind>),
BoundExpression? loweredReceiver = null,
RefKind receiverRefKind = RefKind.None,
bool receiverIsStaticType = false,
BoundExpression? loweredRight = null)
{
const string? NoName = null;
Debug.Assert(argumentNames.IsDefaultOrEmpty || loweredArguments.Length == argumentNames.Length);
Debug.Assert(refKinds.IsDefault || loweredArguments.Length == refKinds.Length);
Debug.Assert(!receiverIsStaticType || receiverRefKind == RefKind.None);
var infos = new BoundExpression[(loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0)];
int j = 0;
if (loweredReceiver != null)
{
infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredReceiver, NoName, receiverRefKind, receiverIsStaticType);
}
for (int i = 0; i < loweredArguments.Length; i++)
{
infos[j++] = GetArgumentInfo(
argumentInfoFactory,
loweredArguments[i],
argumentNames.IsDefaultOrEmpty ? NoName : argumentNames[i],
refKinds.IsDefault ? RefKind.None : refKinds[i],
isStaticType: false);
}
if (loweredRight != null)
{
infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredRight, NoName, RefKind.None, isStaticType: false);
}
return _factory.ArrayOrEmpty(argumentInfoFactory.ContainingType, infos);
}
internal LoweredDynamicOperation MakeDynamicOperation(
BoundExpression? binderConstruction,
BoundExpression? loweredReceiver,
RefKind receiverRefKind,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<RefKind> refKinds,
BoundExpression? loweredRight,
TypeSymbol resultType)
{
Debug.Assert(!loweredArguments.IsDefault);
// get well-known types and members we need:
NamedTypeSymbol? delegateTypeOverMethodTypeParameters = GetDelegateType(loweredReceiver, receiverRefKind, loweredArguments, refKinds, loweredRight, resultType);
NamedTypeSymbol callSiteTypeGeneric = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T);
MethodSymbol callSiteFactoryGeneric = _factory.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Create);
FieldSymbol callSiteTargetFieldGeneric = (FieldSymbol)_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Target);
MethodSymbol delegateInvoke;
if (binderConstruction == null ||
delegateTypeOverMethodTypeParameters is null ||
delegateTypeOverMethodTypeParameters.IsErrorType() ||
(delegateInvoke = delegateTypeOverMethodTypeParameters.DelegateInvokeMethod) is null ||
callSiteTypeGeneric.IsErrorType() ||
callSiteFactoryGeneric is null ||
callSiteTargetFieldGeneric is null)
{
// CS1969: One or more types required to compile a dynamic expression cannot be found.
// Dev11 reports it with source location for each dynamic operation, which results in many error messages.
// The diagnostic that names the specific missing type or member has already been reported.
_factory.Diagnostics.Add(ErrorCode.ERR_DynamicRequiredTypesMissing, NoLocation.Singleton);
return LoweredDynamicOperation.Bad(loweredReceiver, loweredArguments, loweredRight, resultType);
}
if (_currentDynamicCallSiteContainer is null)
{
_currentDynamicCallSiteContainer = CreateCallSiteContainer(_factory, _methodOrdinal, _localFunctionOrdinal);
}
var containerDef = (SynthesizedContainer)_currentDynamicCallSiteContainer.OriginalDefinition;
var methodToContainerTypeParametersMap = containerDef.TypeMap;
ImmutableArray<LocalSymbol> temps = MakeTempsForDiscardArguments(ref loweredArguments);
var callSiteType = callSiteTypeGeneric.Construct(new[] { delegateTypeOverMethodTypeParameters });
var callSiteFactoryMethod = callSiteFactoryGeneric.AsMember(callSiteType);
var callSiteTargetField = callSiteTargetFieldGeneric.AsMember(callSiteType);
var callSiteField = DefineCallSiteStorageSymbol(containerDef, delegateTypeOverMethodTypeParameters, methodToContainerTypeParametersMap);
var callSiteFieldAccess = _factory.Field(null, callSiteField);
var callSiteArguments = GetCallSiteArguments(callSiteFieldAccess, loweredReceiver, loweredArguments, loweredRight);
var nullCallSite = _factory.Null(callSiteField.Type);
var siteInitialization = _factory.Conditional(
_factory.ObjectEqual(callSiteFieldAccess, nullCallSite),
_factory.AssignmentExpression(callSiteFieldAccess, _factory.Call(null, callSiteFactoryMethod, binderConstruction)),
nullCallSite,
callSiteField.Type);
var siteInvocation = _factory.Call(
_factory.Field(callSiteFieldAccess, callSiteTargetField),
delegateInvoke,
callSiteArguments);
return new LoweredDynamicOperation(_factory, siteInitialization, siteInvocation, resultType, temps);
}
/// <summary>
/// If there are any discards in the arguments, create locals for each, updates the arguments and
/// returns the symbols that were created.
/// Returns default if no discards found.
/// </summary>
private ImmutableArray<LocalSymbol> MakeTempsForDiscardArguments(ref ImmutableArray<BoundExpression> loweredArguments)
{
int discardCount = loweredArguments.Count(a => a.Kind == BoundKind.DiscardExpression);
if (discardCount == 0)
{
return ImmutableArray<LocalSymbol>.Empty;
}
ArrayBuilder<LocalSymbol> temporariesBuilder = ArrayBuilder<LocalSymbol>.GetInstance(discardCount);
loweredArguments = _factory.MakeTempsForDiscardArguments(loweredArguments, temporariesBuilder);
return temporariesBuilder.ToImmutableAndFree();
}
private static NamedTypeSymbol CreateCallSiteContainer(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal)
{
Debug.Assert(factory.CompilationState.ModuleBuilderOpt is { });
Debug.Assert(factory.TopLevelMethod is { });
Debug.Assert(factory.CurrentFunction is { });
// We don't reuse call-sites during EnC. Each edit creates a new container and sites.
int generation = factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal;
var containerName = GeneratedNames.MakeDynamicCallSiteContainerName(methodOrdinal, localFunctionOrdinal, generation);
var synthesizedContainer = new DynamicSiteContainer(containerName, factory.TopLevelMethod, factory.CurrentFunction);
factory.AddNestedType(synthesizedContainer);
if (!synthesizedContainer.TypeParameters.IsEmpty)
{
return synthesizedContainer.Construct(synthesizedContainer.ConstructedFromTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>());
}
return synthesizedContainer;
}
internal FieldSymbol DefineCallSiteStorageSymbol(NamedTypeSymbol containerDefinition, NamedTypeSymbol delegateTypeOverMethodTypeParameters, TypeMap methodToContainerTypeParametersMap)
{
var fieldName = GeneratedNames.MakeDynamicCallSiteFieldName(_callSiteIdDispenser++);
var delegateTypeOverContainerTypeParameters = methodToContainerTypeParametersMap.SubstituteNamedType(delegateTypeOverMethodTypeParameters);
var callSiteType = _factory.Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T);
_factory.Diagnostics.ReportUseSite(callSiteType, _factory.Syntax);
callSiteType = callSiteType.Construct(new[] { delegateTypeOverContainerTypeParameters });
var field = new SynthesizedFieldSymbol(containerDefinition, callSiteType, fieldName, isPublic: true, isStatic: true);
_factory.AddField(containerDefinition, field);
Debug.Assert(_currentDynamicCallSiteContainer is { });
return _currentDynamicCallSiteContainer.IsGenericType ? field.AsMember(_currentDynamicCallSiteContainer) : field;
}
internal NamedTypeSymbol? GetDelegateType(
BoundExpression? loweredReceiver,
RefKind receiverRefKind,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<RefKind> refKinds,
BoundExpression? loweredRight,
TypeSymbol resultType)
{
Debug.Assert(refKinds.IsDefaultOrEmpty || refKinds.Length == loweredArguments.Length);
var callSiteType = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite);
if (callSiteType.IsErrorType())
{
return null;
}
var delegateSignature = MakeCallSiteDelegateSignature(callSiteType, loweredReceiver, loweredArguments, loweredRight, resultType);
bool returnsVoid = resultType.IsVoidType();
bool hasByRefs = receiverRefKind != RefKind.None || !refKinds.IsDefaultOrEmpty;
if (!hasByRefs)
{
var wkDelegateType = returnsVoid ?
WellKnownTypes.GetWellKnownActionDelegate(invokeArgumentCount: delegateSignature.Length) :
WellKnownTypes.GetWellKnownFunctionDelegate(invokeArgumentCount: delegateSignature.Length - 1);
if (wkDelegateType != WellKnownType.Unknown)
{
var delegateType = _factory.Compilation.GetWellKnownType(wkDelegateType);
if (!delegateType.HasUseSiteError)
{
_factory.Diagnostics.AddDependencies(delegateType);
return delegateType.Construct(delegateSignature);
}
}
}
RefKindVector byRefs;
if (hasByRefs)
{
byRefs = RefKindVector.Create(1 + (loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0) + (returnsVoid ? 0 : 1));
int j = 1;
if (loweredReceiver != null)
{
byRefs[j++] = getRefKind(receiverRefKind);
}
if (!refKinds.IsDefault)
{
for (int i = 0; i < refKinds.Length; i++, j++)
{
byRefs[j] = getRefKind(refKinds[i]);
}
}
if (!returnsVoid)
{
byRefs[j++] = RefKind.None;
}
}
else
{
byRefs = default(RefKindVector);
}
int parameterCount = delegateSignature.Length - (returnsVoid ? 0 : 1);
Debug.Assert(_factory.CompilationState.ModuleBuilderOpt is { });
int generation = _factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal;
var synthesizedType = _factory.Compilation.AnonymousTypeManager.SynthesizeDelegate(parameterCount, byRefs, returnsVoid, generation);
return synthesizedType.Construct(delegateSignature);
// The distinction between by-ref kinds is ignored for dynamic call-sites.
static RefKind getRefKind(RefKind refKind) => refKind == RefKind.None ? RefKind.None : RefKind.Ref;
}
private BoundExpression GetArgumentInfo(
MethodSymbol argumentInfoFactory,
BoundExpression boundArgument,
string? name,
RefKind refKind,
bool isStaticType)
{
CSharpArgumentInfoFlags flags = 0;
if (isStaticType)
{
flags |= CSharpArgumentInfoFlags.IsStaticType;
}
if (name != null)
{
flags |= CSharpArgumentInfoFlags.NamedArgument;
}
Debug.Assert(refKind == RefKind.None || refKind == RefKind.Ref || refKind == RefKind.Out, "unexpected refKind in dynamic");
// by-ref type doesn't trigger dynamic dispatch and it can't be a null literal => set UseCompileTimeType
if (refKind == RefKind.Out)
{
flags |= CSharpArgumentInfoFlags.IsOut | CSharpArgumentInfoFlags.UseCompileTimeType;
}
else if (refKind == RefKind.Ref)
{
flags |= CSharpArgumentInfoFlags.IsRef | CSharpArgumentInfoFlags.UseCompileTimeType;
}
var argType = boundArgument.Type;
// Check "literal" constant.
// What the runtime binder does with this LiteralConstant flag is just to create a constant,
// which is a compelling enough reason to make sure that on the production end of the binder
// data, we do the inverse (i.e., use the LiteralConstant flag whenever we encounter a constant
// argument.
// And in fact, the bug being fixed with this change is that the compiler will consider constants
// for numeric and enum conversions even if they are not literals (such as, (1-1) --> enum), but
// the runtime binder didn't. So we do need to set this flag whenever we see a constant.
// But the complication is that null values lose their type when they get to the runtime binder,
// and so we need a way to distinguish a null constant of any given type from the null literal.
// The design is simple! We use UseCompileTimeType to determine whether we care about the type of
// a null constant argument, so that the null literal gets "LiteralConstant" whereas every other
// constant gets "LiteralConstant | UseCompileTimeType". Because obviously UseCompileTimeType is
// wrong for the null literal.
// We care, because we want to prevent this from working:
//
// const C x = null;
// class C { public void M(SomeUnrelatedReferenceType x) { } }
// ...
// dynamic d = new C(); d.M(x); // This will pass a null constant and the type is gone!
//
// as well as the alternative where x is a const null of type object.
if (boundArgument.ConstantValue != null)
{
flags |= CSharpArgumentInfoFlags.Constant;
}
// Check compile time type.
// See also DynamicRewriter::GenerateCallingObjectFlags.
if (argType is { } && !argType.IsDynamic())
{
flags |= CSharpArgumentInfoFlags.UseCompileTimeType;
}
return _factory.Call(null, argumentInfoFactory, _factory.Literal((int)flags), _factory.Literal(name));
}
private static ImmutableArray<BoundExpression> GetCallSiteArguments(BoundExpression callSiteFieldAccess, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right)
{
var result = new BoundExpression[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0)];
int j = 0;
result[j++] = callSiteFieldAccess;
if (receiver != null)
{
result[j++] = receiver;
}
arguments.CopyTo(result, j);
j += arguments.Length;
if (right != null)
{
result[j++] = right;
}
return result.AsImmutableOrNull();
}
private TypeSymbol[] MakeCallSiteDelegateSignature(TypeSymbol callSiteType, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right, TypeSymbol resultType)
{
var systemObjectType = _factory.SpecialType(SpecialType.System_Object);
var result = new TypeSymbol[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0) + (resultType.IsVoidType() ? 0 : 1)];
int j = 0;
// CallSite:
result[j++] = callSiteType;
// receiver:
if (receiver != null)
{
result[j++] = receiver.Type ?? systemObjectType;
}
// argument types:
for (int i = 0; i < arguments.Length; i++)
{
result[j++] = arguments[i].Type ?? systemObjectType;
}
// right hand side of an assignment:
if (right != null)
{
result[j++] = right.Type ?? systemObjectType;
}
// return type:
if (j < result.Length)
{
result[j++] = resultType ?? systemObjectType;
}
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.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class LoweredDynamicOperationFactory
{
private readonly SyntheticBoundNodeFactory _factory;
private readonly int _methodOrdinal;
private readonly int _localFunctionOrdinal;
private NamedTypeSymbol? _currentDynamicCallSiteContainer;
private int _callSiteIdDispenser;
internal LoweredDynamicOperationFactory(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal = -1)
{
Debug.Assert(factory != null);
_factory = factory;
_methodOrdinal = methodOrdinal;
_localFunctionOrdinal = localFunctionOrdinal;
}
public int MethodOrdinal => _methodOrdinal;
// We could read the values of the following enums from metadata instead of hardcoding them here but
// - they can never change since existing programs have the values inlined and would be broken if the values changed their meaning,
// - if any new flags are added to the runtime binder the compiler will change as well to produce them.
// The only scenario that is not supported by hardcoding the values is when a completely new Framework is created
// that redefines these constants and is not supposed to run existing programs.
/// <summary>
/// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags.
/// </summary>
[Flags]
private enum CSharpBinderFlags
{
None = 0,
CheckedContext = 1,
InvokeSimpleName = 2,
InvokeSpecialName = 4,
BinaryOperationLogical = 8,
ConvertExplicit = 16,
ConvertArrayIndex = 32,
ResultIndexed = 64,
ValueFromCompoundAssignment = 128,
ResultDiscarded = 256,
}
/// <summary>
/// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags.
/// </summary>
[Flags]
private enum CSharpArgumentInfoFlags
{
None = 0,
UseCompileTimeType = 1,
Constant = 2,
NamedArgument = 4,
IsRef = 8,
IsOut = 16,
IsStaticType = 32,
}
internal LoweredDynamicOperation MakeDynamicConversion(
BoundExpression loweredOperand,
bool isExplicit,
bool isArrayIndex,
bool isChecked,
TypeSymbol resultType)
{
_factory.Syntax = loweredOperand.Syntax;
CSharpBinderFlags binderFlags = 0;
Debug.Assert(!isExplicit || !isArrayIndex);
if (isChecked)
{
binderFlags |= CSharpBinderFlags.CheckedContext;
}
if (isExplicit)
{
binderFlags |= CSharpBinderFlags.ConvertExplicit;
}
if (isArrayIndex)
{
binderFlags |= CSharpBinderFlags.ConvertArrayIndex;
}
var loweredArguments = ImmutableArray.Create(loweredOperand);
var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Convert, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// target type:
_factory.Typeof(resultType),
// context:
_factory.TypeofDynamicOperationContextType()
});
return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType);
}
internal LoweredDynamicOperation MakeDynamicUnaryOperator(
UnaryOperatorKind operatorKind,
BoundExpression loweredOperand,
TypeSymbol resultType)
{
Debug.Assert(operatorKind.IsDynamic());
_factory.Syntax = loweredOperand.Syntax;
CSharpBinderFlags binderFlags = 0;
if (operatorKind.IsChecked())
{
binderFlags |= CSharpBinderFlags.CheckedContext;
}
var loweredArguments = ImmutableArray.Create(loweredOperand);
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// expression type:
_factory.Literal((int)operatorKind.ToExpressionType()),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments)
}) : null;
return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType);
}
internal LoweredDynamicOperation MakeDynamicBinaryOperator(
BinaryOperatorKind operatorKind,
BoundExpression loweredLeft,
BoundExpression loweredRight,
bool isCompoundAssignment,
TypeSymbol resultType)
{
Debug.Assert(operatorKind.IsDynamic());
_factory.Syntax = loweredLeft.Syntax;
CSharpBinderFlags binderFlags = 0;
if (operatorKind.IsChecked())
{
binderFlags |= CSharpBinderFlags.CheckedContext;
}
if (operatorKind.IsLogical())
{
binderFlags |= CSharpBinderFlags.BinaryOperationLogical;
}
var loweredArguments = ImmutableArray.Create<BoundExpression>(loweredLeft, loweredRight);
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// expression type:
_factory.Literal((int)operatorKind.ToExpressionType(isCompoundAssignment)),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments)
}) : null;
return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType);
}
internal LoweredDynamicOperation MakeDynamicMemberInvocation(
string name,
BoundExpression loweredReceiver,
ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames,
ImmutableArray<RefKind> refKinds,
bool hasImplicitReceiver,
bool resultDiscarded)
{
_factory.Syntax = loweredReceiver.Syntax;
Debug.Assert(_factory.TopLevelMethod is { });
CSharpBinderFlags binderFlags = 0;
if (hasImplicitReceiver && _factory.TopLevelMethod.RequiresInstanceReceiver)
{
binderFlags |= CSharpBinderFlags.InvokeSimpleName;
}
TypeSymbol resultType;
if (resultDiscarded)
{
binderFlags |= CSharpBinderFlags.ResultDiscarded;
resultType = _factory.SpecialType(SpecialType.System_Void);
}
else
{
resultType = AssemblySymbol.DynamicType;
}
RefKind receiverRefKind;
bool receiverIsStaticType;
if (loweredReceiver.Kind == BoundKind.TypeExpression)
{
loweredReceiver = _factory.Typeof(((BoundTypeExpression)loweredReceiver).Type);
receiverRefKind = RefKind.None;
receiverIsStaticType = true;
}
else
{
receiverRefKind = GetReceiverRefKind(loweredReceiver);
receiverIsStaticType = false;
}
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// member name:
_factory.Literal(name),
// type arguments:
typeArgumentsWithAnnotations.IsDefaultOrEmpty ?
_factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)) :
_factory.ArrayOrEmpty(_factory.WellKnownType(WellKnownType.System_Type), _factory.TypeOfs(typeArgumentsWithAnnotations)),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverRefKind, receiverIsStaticType)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, receiverRefKind, loweredArguments, refKinds, null, resultType);
}
internal LoweredDynamicOperation MakeDynamicEventAccessorInvocation(
string accessorName,
BoundExpression loweredReceiver,
BoundExpression loweredHandler)
{
_factory.Syntax = loweredReceiver.Syntax;
CSharpBinderFlags binderFlags = CSharpBinderFlags.InvokeSpecialName | CSharpBinderFlags.ResultDiscarded;
var loweredArguments = ImmutableArray<BoundExpression>.Empty;
var resultType = AssemblySymbol.DynamicType;
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// member name:
_factory.Literal(accessorName),
// type arguments:
_factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredHandler)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredHandler, resultType);
}
internal LoweredDynamicOperation MakeDynamicInvocation(
BoundExpression loweredReceiver,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames,
ImmutableArray<RefKind> refKinds,
bool resultDiscarded)
{
_factory.Syntax = loweredReceiver.Syntax;
TypeSymbol resultType;
CSharpBinderFlags binderFlags = 0;
if (resultDiscarded)
{
binderFlags |= CSharpBinderFlags.ResultDiscarded;
resultType = _factory.SpecialType(SpecialType.System_Void);
}
else
{
resultType = AssemblySymbol.DynamicType;
}
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Invoke, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType);
}
internal LoweredDynamicOperation MakeDynamicConstructorInvocation(
SyntaxNode syntax,
TypeSymbol type,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames,
ImmutableArray<RefKind> refKinds)
{
_factory.Syntax = syntax;
var loweredReceiver = _factory.Typeof(type);
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor, new[]
{
// flags:
_factory.Literal(0),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverIsStaticType: true)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, type);
}
internal LoweredDynamicOperation MakeDynamicGetMember(
BoundExpression loweredReceiver,
string name,
bool resultIndexed)
{
_factory.Syntax = loweredReceiver.Syntax;
CSharpBinderFlags binderFlags = 0;
if (resultIndexed)
{
binderFlags |= CSharpBinderFlags.ResultIndexed;
}
var loweredArguments = ImmutableArray<BoundExpression>.Empty;
var resultType = DynamicTypeSymbol.Instance;
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetMember, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// name:
_factory.Literal(name),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType);
}
internal LoweredDynamicOperation MakeDynamicSetMember(
BoundExpression loweredReceiver,
string name,
BoundExpression loweredRight,
bool isCompoundAssignment = false,
bool isChecked = false)
{
_factory.Syntax = loweredReceiver.Syntax;
CSharpBinderFlags binderFlags = 0;
if (isCompoundAssignment)
{
binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment;
if (isChecked)
{
binderFlags |= CSharpBinderFlags.CheckedContext;
}
}
var loweredArguments = ImmutableArray<BoundExpression>.Empty;
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetMember, new[]
{
// flags:
_factory.Literal((int)binderFlags),
// name:
_factory.Literal(name),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredRight)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredRight, AssemblySymbol.DynamicType);
}
internal LoweredDynamicOperation MakeDynamicGetIndex(
BoundExpression loweredReceiver,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames,
ImmutableArray<RefKind> refKinds)
{
_factory.Syntax = loweredReceiver.Syntax;
var resultType = DynamicTypeSymbol.Instance;
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetIndex, new[]
{
// flags (unused):
_factory.Literal((int)CSharpBinderFlags.None),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver: loweredReceiver)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType);
}
internal LoweredDynamicOperation MakeDynamicSetIndex(
BoundExpression loweredReceiver,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames,
ImmutableArray<RefKind> refKinds,
BoundExpression loweredRight,
bool isCompoundAssignment = false,
bool isChecked = false)
{
CSharpBinderFlags binderFlags = 0;
if (isCompoundAssignment)
{
binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment;
if (isChecked)
{
binderFlags |= CSharpBinderFlags.CheckedContext;
}
}
var loweredReceiverRefKind = GetReceiverRefKind(loweredReceiver);
var resultType = DynamicTypeSymbol.Instance;
MethodSymbol argumentInfoFactory = GetArgumentInfoFactory();
var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetIndex, new[]
{
// flags (unused):
_factory.Literal((int)binderFlags),
// context:
_factory.TypeofDynamicOperationContextType(),
// argument infos:
MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, loweredReceiverRefKind, loweredRight: loweredRight)
}) : null;
return MakeDynamicOperation(binderConstruction, loweredReceiver, loweredReceiverRefKind, loweredArguments, refKinds, loweredRight, resultType);
}
internal LoweredDynamicOperation MakeDynamicIsEventTest(string name, BoundExpression loweredReceiver)
{
_factory.Syntax = loweredReceiver.Syntax;
var resultType = _factory.SpecialType(SpecialType.System_Boolean);
var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__IsEvent, new[]
{
// flags (unused):
_factory.Literal((int)0),
// member name:
_factory.Literal(name),
// context:
_factory.TypeofDynamicOperationContextType()
});
return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, ImmutableArray<BoundExpression>.Empty, default(ImmutableArray<RefKind>), null, resultType);
}
private MethodSymbol GetArgumentInfoFactory()
{
return _factory.WellKnownMethod(WellKnownMember.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create);
}
private BoundExpression? MakeBinderConstruction(WellKnownMember factoryMethod, BoundExpression[] args)
{
var binderFactory = _factory.WellKnownMember(factoryMethod);
if (binderFactory is null)
{
return null;
}
return _factory.Call(null, (MethodSymbol)binderFactory, args.AsImmutableOrNull());
}
// If we have a struct calling object, then we need to pass it by ref, provided
// that it was an Lvalue. For instance,
// Struct s = ...; dynamic d = ...;
// s.M(d); // becomes Site(ref s, d)
// however
// dynamic d = ...;
// GetS().M(d); // becomes Site(GetS(), d) without ref on the target obj arg
internal static RefKind GetReceiverRefKind(BoundExpression loweredReceiver)
{
Debug.Assert(loweredReceiver.Type is { });
if (!loweredReceiver.Type.IsValueType)
{
return RefKind.None;
}
switch (loweredReceiver.Kind)
{
case BoundKind.Local:
case BoundKind.Parameter:
case BoundKind.ArrayAccess:
case BoundKind.ThisReference:
case BoundKind.PointerIndirectionOperator:
case BoundKind.PointerElementAccess:
case BoundKind.RefValueOperator:
return RefKind.Ref;
case BoundKind.BaseReference:
// base dynamic dispatch is not supported, an error has already been reported
case BoundKind.TypeExpression:
throw ExceptionUtilities.UnexpectedValue(loweredReceiver.Kind);
}
return RefKind.None;
}
internal BoundExpression MakeCallSiteArgumentInfos(
MethodSymbol argumentInfoFactory,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<string> argumentNames = default(ImmutableArray<string>),
ImmutableArray<RefKind> refKinds = default(ImmutableArray<RefKind>),
BoundExpression? loweredReceiver = null,
RefKind receiverRefKind = RefKind.None,
bool receiverIsStaticType = false,
BoundExpression? loweredRight = null)
{
const string? NoName = null;
Debug.Assert(argumentNames.IsDefaultOrEmpty || loweredArguments.Length == argumentNames.Length);
Debug.Assert(refKinds.IsDefault || loweredArguments.Length == refKinds.Length);
Debug.Assert(!receiverIsStaticType || receiverRefKind == RefKind.None);
var infos = new BoundExpression[(loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0)];
int j = 0;
if (loweredReceiver != null)
{
infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredReceiver, NoName, receiverRefKind, receiverIsStaticType);
}
for (int i = 0; i < loweredArguments.Length; i++)
{
infos[j++] = GetArgumentInfo(
argumentInfoFactory,
loweredArguments[i],
argumentNames.IsDefaultOrEmpty ? NoName : argumentNames[i],
refKinds.IsDefault ? RefKind.None : refKinds[i],
isStaticType: false);
}
if (loweredRight != null)
{
infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredRight, NoName, RefKind.None, isStaticType: false);
}
return _factory.ArrayOrEmpty(argumentInfoFactory.ContainingType, infos);
}
internal LoweredDynamicOperation MakeDynamicOperation(
BoundExpression? binderConstruction,
BoundExpression? loweredReceiver,
RefKind receiverRefKind,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<RefKind> refKinds,
BoundExpression? loweredRight,
TypeSymbol resultType)
{
Debug.Assert(!loweredArguments.IsDefault);
// get well-known types and members we need:
NamedTypeSymbol? delegateTypeOverMethodTypeParameters = GetDelegateType(loweredReceiver, receiverRefKind, loweredArguments, refKinds, loweredRight, resultType);
NamedTypeSymbol callSiteTypeGeneric = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T);
MethodSymbol callSiteFactoryGeneric = _factory.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Create);
FieldSymbol callSiteTargetFieldGeneric = (FieldSymbol)_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Target);
MethodSymbol delegateInvoke;
if (binderConstruction == null ||
delegateTypeOverMethodTypeParameters is null ||
delegateTypeOverMethodTypeParameters.IsErrorType() ||
(delegateInvoke = delegateTypeOverMethodTypeParameters.DelegateInvokeMethod) is null ||
callSiteTypeGeneric.IsErrorType() ||
callSiteFactoryGeneric is null ||
callSiteTargetFieldGeneric is null)
{
// CS1969: One or more types required to compile a dynamic expression cannot be found.
// Dev11 reports it with source location for each dynamic operation, which results in many error messages.
// The diagnostic that names the specific missing type or member has already been reported.
_factory.Diagnostics.Add(ErrorCode.ERR_DynamicRequiredTypesMissing, NoLocation.Singleton);
return LoweredDynamicOperation.Bad(loweredReceiver, loweredArguments, loweredRight, resultType);
}
if (_currentDynamicCallSiteContainer is null)
{
_currentDynamicCallSiteContainer = CreateCallSiteContainer(_factory, _methodOrdinal, _localFunctionOrdinal);
}
var containerDef = (SynthesizedContainer)_currentDynamicCallSiteContainer.OriginalDefinition;
var methodToContainerTypeParametersMap = containerDef.TypeMap;
ImmutableArray<LocalSymbol> temps = MakeTempsForDiscardArguments(ref loweredArguments);
var callSiteType = callSiteTypeGeneric.Construct(new[] { delegateTypeOverMethodTypeParameters });
var callSiteFactoryMethod = callSiteFactoryGeneric.AsMember(callSiteType);
var callSiteTargetField = callSiteTargetFieldGeneric.AsMember(callSiteType);
var callSiteField = DefineCallSiteStorageSymbol(containerDef, delegateTypeOverMethodTypeParameters, methodToContainerTypeParametersMap);
var callSiteFieldAccess = _factory.Field(null, callSiteField);
var callSiteArguments = GetCallSiteArguments(callSiteFieldAccess, loweredReceiver, loweredArguments, loweredRight);
var nullCallSite = _factory.Null(callSiteField.Type);
var siteInitialization = _factory.Conditional(
_factory.ObjectEqual(callSiteFieldAccess, nullCallSite),
_factory.AssignmentExpression(callSiteFieldAccess, _factory.Call(null, callSiteFactoryMethod, binderConstruction)),
nullCallSite,
callSiteField.Type);
var siteInvocation = _factory.Call(
_factory.Field(callSiteFieldAccess, callSiteTargetField),
delegateInvoke,
callSiteArguments);
return new LoweredDynamicOperation(_factory, siteInitialization, siteInvocation, resultType, temps);
}
/// <summary>
/// If there are any discards in the arguments, create locals for each, updates the arguments and
/// returns the symbols that were created.
/// Returns default if no discards found.
/// </summary>
private ImmutableArray<LocalSymbol> MakeTempsForDiscardArguments(ref ImmutableArray<BoundExpression> loweredArguments)
{
int discardCount = loweredArguments.Count(a => a.Kind == BoundKind.DiscardExpression);
if (discardCount == 0)
{
return ImmutableArray<LocalSymbol>.Empty;
}
ArrayBuilder<LocalSymbol> temporariesBuilder = ArrayBuilder<LocalSymbol>.GetInstance(discardCount);
loweredArguments = _factory.MakeTempsForDiscardArguments(loweredArguments, temporariesBuilder);
return temporariesBuilder.ToImmutableAndFree();
}
private static NamedTypeSymbol CreateCallSiteContainer(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal)
{
Debug.Assert(factory.CompilationState.ModuleBuilderOpt is { });
Debug.Assert(factory.TopLevelMethod is { });
Debug.Assert(factory.CurrentFunction is { });
// We don't reuse call-sites during EnC. Each edit creates a new container and sites.
int generation = factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal;
var containerName = GeneratedNames.MakeDynamicCallSiteContainerName(methodOrdinal, localFunctionOrdinal, generation);
var synthesizedContainer = new DynamicSiteContainer(containerName, factory.TopLevelMethod, factory.CurrentFunction);
factory.AddNestedType(synthesizedContainer);
if (!synthesizedContainer.TypeParameters.IsEmpty)
{
return synthesizedContainer.Construct(synthesizedContainer.ConstructedFromTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>());
}
return synthesizedContainer;
}
internal FieldSymbol DefineCallSiteStorageSymbol(NamedTypeSymbol containerDefinition, NamedTypeSymbol delegateTypeOverMethodTypeParameters, TypeMap methodToContainerTypeParametersMap)
{
var fieldName = GeneratedNames.MakeDynamicCallSiteFieldName(_callSiteIdDispenser++);
var delegateTypeOverContainerTypeParameters = methodToContainerTypeParametersMap.SubstituteNamedType(delegateTypeOverMethodTypeParameters);
var callSiteType = _factory.Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T);
_factory.Diagnostics.ReportUseSite(callSiteType, _factory.Syntax);
callSiteType = callSiteType.Construct(new[] { delegateTypeOverContainerTypeParameters });
var field = new SynthesizedFieldSymbol(containerDefinition, callSiteType, fieldName, isPublic: true, isStatic: true);
_factory.AddField(containerDefinition, field);
Debug.Assert(_currentDynamicCallSiteContainer is { });
return _currentDynamicCallSiteContainer.IsGenericType ? field.AsMember(_currentDynamicCallSiteContainer) : field;
}
internal NamedTypeSymbol? GetDelegateType(
BoundExpression? loweredReceiver,
RefKind receiverRefKind,
ImmutableArray<BoundExpression> loweredArguments,
ImmutableArray<RefKind> refKinds,
BoundExpression? loweredRight,
TypeSymbol resultType)
{
Debug.Assert(refKinds.IsDefaultOrEmpty || refKinds.Length == loweredArguments.Length);
var callSiteType = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite);
if (callSiteType.IsErrorType())
{
return null;
}
var delegateSignature = MakeCallSiteDelegateSignature(callSiteType, loweredReceiver, loweredArguments, loweredRight, resultType);
bool returnsVoid = resultType.IsVoidType();
bool hasByRefs = receiverRefKind != RefKind.None || !refKinds.IsDefaultOrEmpty;
if (!hasByRefs)
{
var wkDelegateType = returnsVoid ?
WellKnownTypes.GetWellKnownActionDelegate(invokeArgumentCount: delegateSignature.Length) :
WellKnownTypes.GetWellKnownFunctionDelegate(invokeArgumentCount: delegateSignature.Length - 1);
if (wkDelegateType != WellKnownType.Unknown)
{
var delegateType = _factory.Compilation.GetWellKnownType(wkDelegateType);
if (!delegateType.HasUseSiteError)
{
_factory.Diagnostics.AddDependencies(delegateType);
return delegateType.Construct(delegateSignature);
}
}
}
RefKindVector byRefs;
if (hasByRefs)
{
byRefs = RefKindVector.Create(1 + (loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0) + (returnsVoid ? 0 : 1));
int j = 1;
if (loweredReceiver != null)
{
byRefs[j++] = getRefKind(receiverRefKind);
}
if (!refKinds.IsDefault)
{
for (int i = 0; i < refKinds.Length; i++, j++)
{
byRefs[j] = getRefKind(refKinds[i]);
}
}
if (!returnsVoid)
{
byRefs[j++] = RefKind.None;
}
}
else
{
byRefs = default(RefKindVector);
}
int parameterCount = delegateSignature.Length - (returnsVoid ? 0 : 1);
Debug.Assert(_factory.CompilationState.ModuleBuilderOpt is { });
int generation = _factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal;
var synthesizedType = _factory.Compilation.AnonymousTypeManager.SynthesizeDelegate(parameterCount, byRefs, returnsVoid, generation);
return synthesizedType.Construct(delegateSignature);
// The distinction between by-ref kinds is ignored for dynamic call-sites.
static RefKind getRefKind(RefKind refKind) => refKind == RefKind.None ? RefKind.None : RefKind.Ref;
}
private BoundExpression GetArgumentInfo(
MethodSymbol argumentInfoFactory,
BoundExpression boundArgument,
string? name,
RefKind refKind,
bool isStaticType)
{
CSharpArgumentInfoFlags flags = 0;
if (isStaticType)
{
flags |= CSharpArgumentInfoFlags.IsStaticType;
}
if (name != null)
{
flags |= CSharpArgumentInfoFlags.NamedArgument;
}
Debug.Assert(refKind == RefKind.None || refKind == RefKind.Ref || refKind == RefKind.Out, "unexpected refKind in dynamic");
// by-ref type doesn't trigger dynamic dispatch and it can't be a null literal => set UseCompileTimeType
if (refKind == RefKind.Out)
{
flags |= CSharpArgumentInfoFlags.IsOut | CSharpArgumentInfoFlags.UseCompileTimeType;
}
else if (refKind == RefKind.Ref)
{
flags |= CSharpArgumentInfoFlags.IsRef | CSharpArgumentInfoFlags.UseCompileTimeType;
}
var argType = boundArgument.Type;
// Check "literal" constant.
// What the runtime binder does with this LiteralConstant flag is just to create a constant,
// which is a compelling enough reason to make sure that on the production end of the binder
// data, we do the inverse (i.e., use the LiteralConstant flag whenever we encounter a constant
// argument.
// And in fact, the bug being fixed with this change is that the compiler will consider constants
// for numeric and enum conversions even if they are not literals (such as, (1-1) --> enum), but
// the runtime binder didn't. So we do need to set this flag whenever we see a constant.
// But the complication is that null values lose their type when they get to the runtime binder,
// and so we need a way to distinguish a null constant of any given type from the null literal.
// The design is simple! We use UseCompileTimeType to determine whether we care about the type of
// a null constant argument, so that the null literal gets "LiteralConstant" whereas every other
// constant gets "LiteralConstant | UseCompileTimeType". Because obviously UseCompileTimeType is
// wrong for the null literal.
// We care, because we want to prevent this from working:
//
// const C x = null;
// class C { public void M(SomeUnrelatedReferenceType x) { } }
// ...
// dynamic d = new C(); d.M(x); // This will pass a null constant and the type is gone!
//
// as well as the alternative where x is a const null of type object.
if (boundArgument.ConstantValue != null)
{
flags |= CSharpArgumentInfoFlags.Constant;
}
// Check compile time type.
// See also DynamicRewriter::GenerateCallingObjectFlags.
if (argType is { } && !argType.IsDynamic())
{
flags |= CSharpArgumentInfoFlags.UseCompileTimeType;
}
return _factory.Call(null, argumentInfoFactory, _factory.Literal((int)flags), _factory.Literal(name));
}
private static ImmutableArray<BoundExpression> GetCallSiteArguments(BoundExpression callSiteFieldAccess, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right)
{
var result = new BoundExpression[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0)];
int j = 0;
result[j++] = callSiteFieldAccess;
if (receiver != null)
{
result[j++] = receiver;
}
arguments.CopyTo(result, j);
j += arguments.Length;
if (right != null)
{
result[j++] = right;
}
return result.AsImmutableOrNull();
}
private TypeSymbol[] MakeCallSiteDelegateSignature(TypeSymbol callSiteType, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right, TypeSymbol resultType)
{
var systemObjectType = _factory.SpecialType(SpecialType.System_Object);
var result = new TypeSymbol[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0) + (resultType.IsVoidType() ? 0 : 1)];
int j = 0;
// CallSite:
result[j++] = callSiteType;
// receiver:
if (receiver != null)
{
result[j++] = receiver.Type ?? systemObjectType;
}
// argument types:
for (int i = 0; i < arguments.Length; i++)
{
result[j++] = arguments[i].Type ?? systemObjectType;
}
// right hand side of an assignment:
if (right != null)
{
result[j++] = right.Type ?? systemObjectType;
}
// return type:
if (j < result.Length)
{
result[j++] = resultType ?? systemObjectType;
}
return result;
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/Core.Wpf/BraceMatching/BraceMatchingTypeFormatDefinitions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching
{
internal sealed class BraceMatchingTypeFormatDefinitions
{
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeDefinitions.BraceMatchingName)]
[Name(ClassificationTypeDefinitions.BraceMatchingName)]
[Order(After = Priority.High)]
[UserVisible(true)]
private class BraceMatchingFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public BraceMatchingFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.Brace_Matching;
this.BackgroundColor = Color.FromRgb(0xDB, 0xE0, 0xCC);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching
{
internal sealed class BraceMatchingTypeFormatDefinitions
{
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = ClassificationTypeDefinitions.BraceMatchingName)]
[Name(ClassificationTypeDefinitions.BraceMatchingName)]
[Order(After = Priority.High)]
[UserVisible(true)]
private class BraceMatchingFormatDefinition : ClassificationFormatDefinition
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public BraceMatchingFormatDefinition()
{
this.DisplayName = EditorFeaturesResources.Brace_Matching;
this.BackgroundColor = Color.FromRgb(0xDB, 0xE0, 0xCC);
}
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.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.Xml.Linq
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Test.Utilities.VBInstrumentationChecker
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.DynamicAnalysis.UnitTests
Public Class DynamicInstrumentationTests
Inherits BasicTestBase
<Fact>
Public Sub SimpleCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
End Sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim checker = New VBInstrumentationChecker()
checker.Method(1, 1, "Public Sub Main").
True("TestMain()").
True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()")
checker.Method(2, 1, "Sub TestMain()")
checker.Method(5, 1).
True().
False().
True().
True().
True().
True().
True().
True().
True().
True().
True().
True()
Dim verifier As CompilationVerifier = CompileAndVerify(source, checker.ExpectedOutput)
checker.CompleteCheck(verifier.Compilation, testSource)
verifier.VerifyIL(
"Program.TestMain",
<![CDATA[{
// Code size 57 (0x39)
.maxstack 5
.locals init (Boolean() V_0)
IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0005: ldtoken "Sub Program.TestMain()"
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID"
IL_0014: ldtoken "Sub Program.TestMain()"
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0023: ldtoken "Sub Program.TestMain()"
IL_0028: ldelema "Boolean()"
IL_002d: ldc.i4.1
IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()"
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ret
}
]]>.Value)
verifier.VerifyIL(
".cctor",
<![CDATA[
{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldtoken Max Method Token Index
IL_0005: newarr "Boolean()"
IL_000a: stsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_000f: ldstr ##MVID##
IL_0014: newobj "Sub System.Guid..ctor(String)"
IL_0019: stsfld "System.Guid <PrivateImplementationDetails>.MVID"
IL_001e: ret
}
]]>.Value)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub MyTemplateNotCovered()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
End Sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 8
File 1
True
True
True
Method 9
File 1
True
Method 12
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
' Explicitly define the "_MyType" pre-processor definition so that the "My" template code is added to
' the compilation. The "My" template code returns a special "VisualBasicSyntaxNode" that reports an invalid
' path. The "DynamicAnalysisInjector" skips instrumenting such code.
Dim preprocessorSymbols = ImmutableArray.Create(New KeyValuePair(Of String, Object)("_MyType", "Console"))
Dim parseOptions = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols)
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput, TestOptions.ReleaseExe.WithParseOptions(parseOptions))
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub MultipleFilesCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Called()
End Sub
End Module
]]>
</file>
Dim testSource1 As XElement = <file name="d.vb">
<![CDATA[
Module More
Sub Called() ' Method 3
Another()
Another()
End Sub
End Module
]]>
</file>
Dim testSource2 As XElement = <file name="e.vb">
<![CDATA[
Module EvenMore
Sub Another() ' Method 4
End Sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(testSource1)
source.Add(testSource2)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
Method 3
File 2
True
True
True
Method 4
File 3
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub MethodsOfGenericTypesCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Class MyBox(Of T As Class)
ReadOnly _value As T
Public Sub New(value As T)
_value = value
End Sub
Public Function GetValue() As T
If _value Is Nothing Then
Return Nothing
End If
Return _value
End Function
End Class
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Dim x As MyBox(Of Object) = New MyBox(Of Object)(Nothing)
System.Console.WriteLine(If(x.GetValue() Is Nothing, "null", x.GetValue().ToString()))
Dim s As MyBox(Of String) = New MyBox(Of String)("Hello")
System.Console.WriteLine(If(s.GetValue() Is Nothing, "null", s.GetValue()))
End Sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[null
Hello
Flushing
Method 1
File 1
True
True
Method 2
File 1
True
True
True
True
Method 3
File 1
True
True
True
Method 4
File 1
True
True
True
True
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyIL(
"MyBox(Of T).GetValue",
<![CDATA[
{
// Code size 100 (0x64)
.maxstack 5
.locals init (T V_0, //GetValue
Boolean() V_1)
IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0005: ldtoken "Function MyBox(Of T).GetValue() As T"
IL_000a: ldelem.ref
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID"
IL_0014: ldtoken "Function MyBox(Of T).GetValue() As T"
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0023: ldtoken "Function MyBox(Of T).GetValue() As T"
IL_0028: ldelema "Boolean()"
IL_002d: ldc.i4.4
IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()"
IL_0033: stloc.1
IL_0034: ldloc.1
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ldloc.1
IL_0039: ldc.i4.2
IL_003a: ldc.i4.1
IL_003b: stelem.i1
IL_003c: ldarg.0
IL_003d: ldfld "MyBox(Of T)._value As T"
IL_0042: box "T"
IL_0047: brtrue.s IL_0057
IL_0049: ldloc.1
IL_004a: ldc.i4.1
IL_004b: ldc.i4.1
IL_004c: stelem.i1
IL_004d: ldloca.s V_0
IL_004f: initobj "T"
IL_0055: br.s IL_0062
IL_0057: ldloc.1
IL_0058: ldc.i4.3
IL_0059: ldc.i4.1
IL_005a: stelem.i1
IL_005b: ldarg.0
IL_005c: ldfld "MyBox(Of T)._value As T"
IL_0061: stloc.0
IL_0062: ldloc.0
IL_0063: ret
}
]]>.Value)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub LambdaCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain()
Dim y As Integer = 5
Dim tester As System.Func(Of Integer, Integer) = Function(x)
While x > 10
Return y
End While
Return x
End Function
Dim identity As System.Func(Of Integer, Integer) = Function(x) x
y = 75
If tester(20) > 50 AndAlso identity(20) = 20 Then
System.Console.WriteLine("OK")
Else
System.Console.WriteLine("Bad")
End If
End sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[OK
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
False
True
True
True
True
True
False
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub IteratorCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
For Each number In Goo()
System.Console.WriteLine(number)
Next
For Each number In Goo()
System.Console.WriteLine(number)
Next
End Sub
Public Iterator Function Goo() As System.Collections.Generic.IEnumerable(Of Integer) ' Method 3
For counter = 1 To 5
Yield counter
Next
End Function
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[1
2
3
4
5
1
2
3
4
5
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
Method 3
File 1
True
True
Method 6
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyIL(
"Program.VB$StateMachine_2_Goo.MoveNext()",
<![CDATA[
{
// Code size 149 (0x95)
.maxstack 5
.locals init (Integer V_0,
Boolean() V_1)
IL_0000: ldarg.0
IL_0001: ldfld "Program.VB$StateMachine_2_Goo.$State As Integer"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0010
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq.s IL_0073
IL_000e: ldc.i4.0
IL_000f: ret
IL_0010: ldarg.0
IL_0011: ldc.i4.m1
IL_0012: dup
IL_0013: stloc.0
IL_0014: stfld "Program.VB$StateMachine_2_Goo.$State As Integer"
IL_0019: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_001e: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)"
IL_0023: ldelem.ref
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: brtrue.s IL_004d
IL_0028: ldsfld "System.Guid <PrivateImplementationDetails>.MVID"
IL_002d: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)"
IL_0032: ldtoken Source Document 0
IL_0037: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_003c: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)"
IL_0041: ldelema "Boolean()"
IL_0046: ldc.i4.2
IL_0047: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()"
IL_004c: stloc.1
IL_004d: ldloc.1
IL_004e: ldc.i4.0
IL_004f: ldc.i4.1
IL_0050: stelem.i1
IL_0051: ldloc.1
IL_0052: ldc.i4.1
IL_0053: ldc.i4.1
IL_0054: stelem.i1
IL_0055: ldarg.0
IL_0056: ldc.i4.1
IL_0057: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer"
IL_005c: ldarg.0
IL_005d: ldarg.0
IL_005e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer"
IL_0063: stfld "Program.VB$StateMachine_2_Goo.$Current As Integer"
IL_0068: ldarg.0
IL_0069: ldc.i4.1
IL_006a: dup
IL_006b: stloc.0
IL_006c: stfld "Program.VB$StateMachine_2_Goo.$State As Integer"
IL_0071: ldc.i4.1
IL_0072: ret
IL_0073: ldarg.0
IL_0074: ldc.i4.m1
IL_0075: dup
IL_0076: stloc.0
IL_0077: stfld "Program.VB$StateMachine_2_Goo.$State As Integer"
IL_007c: ldarg.0
IL_007d: ldarg.0
IL_007e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer"
IL_0083: ldc.i4.1
IL_0084: add.ovf
IL_0085: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer"
IL_008a: ldarg.0
IL_008b: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer"
IL_0090: ldc.i4.5
IL_0091: ble.s IL_005c
IL_0093: ldc.i4.0
IL_0094: ret
}
]]>.Value)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub AsyncCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Console.WriteLine(Outer("Goo").Result)
End Sub
Async Function Outer(s As String) As Task(Of String) ' Method 3
Dim s1 As String = Await First(s)
Dim s2 As String = Await Second(s)
Return s1 + s2
End Function
Async Function First(s As String) As Task(Of String) ' Method 4
Dim result As String = Await Second(s) + "Glue"
If result.Length > 2 Then
Return result
Else
Return "Too Short"
End If
End Function
Async Function Second(s As String) As Task(Of String) ' Method 5
Dim doubled As String = ""
If s.Length > 2 Then
doubled = s + s
Else
doubled = "HuhHuh"
End If
Return Await Task.Factory.StartNew(Function() doubled)
End Function
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[GooGooGlueGooGoo
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
Method 3
File 1
True
True
True
True
Method 4
File 1
True
True
True
False
True
Method 5
File 1
True
True
True
False
True
True
True
Method 8
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyIL(
"Program.VB$StateMachine_4_Second.MoveNext()",
<![CDATA[
{
// Code size 375 (0x177)
.maxstack 6
.locals init (String V_0,
Integer V_1,
Program._Closure$__4-0 V_2, //$VB$Closure_0
System.Runtime.CompilerServices.TaskAwaiter(Of String) V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld "Program.VB$StateMachine_4_Second.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse IL_010e
IL_000d: newobj "Sub Program._Closure$__4-0..ctor()"
IL_0012: stloc.2
IL_0013: ldloc.2
IL_0014: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0019: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)"
IL_001e: ldelem.ref
IL_001f: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_0024: ldloc.2
IL_0025: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_002a: brtrue.s IL_0056
IL_002c: ldloc.2
IL_002d: ldsfld "System.Guid <PrivateImplementationDetails>.MVID"
IL_0032: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)"
IL_0037: ldtoken Source Document 0
IL_003c: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0041: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)"
IL_0046: ldelema "Boolean()"
IL_004b: ldc.i4.7
IL_004c: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()"
IL_0051: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_0056: ldloc.2
IL_0057: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_005c: ldc.i4.0
IL_005d: ldc.i4.1
IL_005e: stelem.i1
IL_005f: ldloc.2
IL_0060: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_0065: ldc.i4.1
IL_0066: ldc.i4.1
IL_0067: stelem.i1
IL_0068: ldloc.2
IL_0069: ldstr ""
IL_006e: stfld "Program._Closure$__4-0.$VB$Local_doubled As String"
IL_0073: ldloc.2
IL_0074: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_0079: ldc.i4.4
IL_007a: ldc.i4.1
IL_007b: stelem.i1
IL_007c: ldarg.0
IL_007d: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String"
IL_0082: callvirt "Function String.get_Length() As Integer"
IL_0087: ldc.i4.2
IL_0088: ble.s IL_00ac
IL_008a: ldloc.2
IL_008b: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_0090: ldc.i4.2
IL_0091: ldc.i4.1
IL_0092: stelem.i1
IL_0093: ldloc.2
IL_0094: ldarg.0
IL_0095: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String"
IL_009a: ldarg.0
IL_009b: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String"
IL_00a0: call "Function String.Concat(String, String) As String"
IL_00a5: stfld "Program._Closure$__4-0.$VB$Local_doubled As String"
IL_00aa: br.s IL_00c0
IL_00ac: ldloc.2
IL_00ad: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_00b2: ldc.i4.3
IL_00b3: ldc.i4.1
IL_00b4: stelem.i1
IL_00b5: ldloc.2
IL_00b6: ldstr "HuhHuh"
IL_00bb: stfld "Program._Closure$__4-0.$VB$Local_doubled As String"
IL_00c0: ldloc.2
IL_00c1: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_00c6: ldc.i4.6
IL_00c7: ldc.i4.1
IL_00c8: stelem.i1
IL_00c9: call "Function System.Threading.Tasks.Task.get_Factory() As System.Threading.Tasks.TaskFactory"
IL_00ce: ldloc.2
IL_00cf: ldftn "Function Program._Closure$__4-0._Lambda$__0() As String"
IL_00d5: newobj "Sub System.Func(Of String)..ctor(Object, System.IntPtr)"
IL_00da: callvirt "Function System.Threading.Tasks.TaskFactory.StartNew(Of String)(System.Func(Of String)) As System.Threading.Tasks.Task(Of String)"
IL_00df: callvirt "Function System.Threading.Tasks.Task(Of String).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_00e4: stloc.3
IL_00e5: ldloca.s V_3
IL_00e7: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).get_IsCompleted() As Boolean"
IL_00ec: brtrue.s IL_012a
IL_00ee: ldarg.0
IL_00ef: ldc.i4.0
IL_00f0: dup
IL_00f1: stloc.1
IL_00f2: stfld "Program.VB$StateMachine_4_Second.$State As Integer"
IL_00f7: ldarg.0
IL_00f8: ldloc.3
IL_00f9: stfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_00fe: ldarg.0
IL_00ff: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_0104: ldloca.s V_3
IL_0106: ldarg.0
IL_0107: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of String), Program.VB$StateMachine_4_Second)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of String), ByRef Program.VB$StateMachine_4_Second)"
IL_010c: leave.s IL_0176
IL_010e: ldarg.0
IL_010f: ldc.i4.m1
IL_0110: dup
IL_0111: stloc.1
IL_0112: stfld "Program.VB$StateMachine_4_Second.$State As Integer"
IL_0117: ldarg.0
IL_0118: ldfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_011d: stloc.3
IL_011e: ldarg.0
IL_011f: ldflda "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_0124: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_012a: ldloca.s V_3
IL_012c: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).GetResult() As String"
IL_0131: ldloca.s V_3
IL_0133: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_0139: stloc.0
IL_013a: leave.s IL_0160
}
catch System.Exception
{
IL_013c: dup
IL_013d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0142: stloc.s V_4
IL_0144: ldarg.0
IL_0145: ldc.i4.s -2
IL_0147: stfld "Program.VB$StateMachine_4_Second.$State As Integer"
IL_014c: ldarg.0
IL_014d: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_0152: ldloc.s V_4
IL_0154: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetException(System.Exception)"
IL_0159: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_015e: leave.s IL_0176
}
IL_0160: ldarg.0
IL_0161: ldc.i4.s -2
IL_0163: dup
IL_0164: stloc.1
IL_0165: stfld "Program.VB$StateMachine_4_Second.$State As Integer"
IL_016a: ldarg.0
IL_016b: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_0170: ldloc.0
IL_0171: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetResult(String)"
IL_0176: ret
}
]]>.Value)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub LoopsCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Function TestIf(a As Boolean, b As Boolean) As Integer ' Method 1
Dim x As Integer = 0
If a Then x += 1 Else x += 10
If a Then
x += 1
ElseIf a AndAlso b Then
x += 10
Else
x += 100
End If
If b Then
x += 1
End If
If a AndAlso b Then
x += 10
End If
Return x
End Function
Function TestDoLoops() As Integer ' Method 2
Dim x As Integer = 100
While x < 150
x += 1
End While
While x < 150
x += 1
End While
Do While x < 200
x += 1
Loop
Do Until x = 200
x += 1
Loop
Do
x += 1
Loop While x < 200
Do
x += 1
Loop Until x = 202
Do
Return x
Loop
End Function
Sub TestForLoops() ' Method 3
Dim x As Integer = 0
Dim y As Integer = 10
Dim z As Integer = 3
For a As Integer = x To y Step z
z += 1
Next
For b As Integer = 1 To 10
z += 1
Next
For Each c As Integer In {x, y, z}
z += 1
Next
End Sub
Public Sub Main(args As String())
TestIf(False, False)
TestIf(True, False)
TestDoLoops()
TestForLoops()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
True
True
True
False
True
True
True
False
True
False
True
True
Method 2
File 1
True
True
True
True
False
True
True
True
False
True
True
True
True
True
True
Method 3
File 1
True
True
True
True
True
True
True
True
True
True
Method 4
File 1
True
True
True
True
True
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TryAndSelectCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub TryAndSelect() ' Method 1
Dim y As Integer = 0
Try
Try
For x As Integer = 0 To 10
Select Case x
Case 0
y += 1
Case 1
Throw New System.Exception()
Case >= 2
y += 1
Case Else
y += 1
End Select
Next
Catch e As System.Exception
y += 1
End Try
Finally
y += 1
End Try
End Sub
Public Sub Main(args As String())
TryAndSelect()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
True
True
True
False
False
True
True
Method 2
File 1
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub BranchesCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub Branches() ' Method 1
Dim y As Integer = 0
MyLabel:
Do
Exit Do
y += 1
Loop
For x As Integer = 1 To 10
Exit For
y += 1
Next
Try
Exit Try
y += 1
Catch ex As System.Exception
End Try
Select Case y
Case 0
Exit Select
y += 0
End Select
If y = 0 Then
Exit Sub
End If
GoTo MyLabel
End Sub
Public Sub Main(args As String()) ' Method 2
Branches()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
False
True
True
False
True
False
True
True
False
True
True
False
Method 2
File 1
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub StaticLocalsCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub TestMain() ' Method 1
Dim x As Integer = 1
Static y As Integer = 2
If x + y = 3 Then
Dim a As Integer = 10
Static b As Integer = 20
If a + b = 31 Then
Return
End If
End If
End Sub
Public Sub Main(args As String()) ' Method 2
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
True
True
False
True
True
Method 2
File 1
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub OddCornersCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub TestMain() ' Method 1
Dim h As New HasEvents()
h.Stuff()
End Sub
Class HasEvents
WithEvents f As HasEvents
Sub New() ' Method 9
AddHandler Mumble, AddressOf Handler
End Sub
Event Mumble()
Event Stumble()
Sub Handler() Handles Me.Stumble ' Method 14
End Sub
Sub Stuff() ' Method 15
f = New HasEvents()
RaiseEvent Mumble()
RaiseEvent Stumble()
RemoveHandler Mumble, AddressOf Handler
Dim meme As HasEvents = Me + Me
End Sub
Shared Operator +(x As HasEvents, y As HasEvents) As HasEvents ' Method 16
Return x
End Operator
End Class
Public Sub Main(args As String()) ' Method 2
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
Method 10
File 1
True
True
Method 15
File 1
True
Method 16
File 1
True
True
True
True
True
True
Method 17
File 1
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DoubleDeclarationsCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub TestMain() ' Method 1
Dim x, y As Integer, z As String
Dim a As Integer = 10, b As Integer = 20, c as Integer = 30
If a = 11 Then
Dim aa, bb As Integer
Dim cc As Integer, dd As Integer
Return
End If
If a + b + c = 61 Then
x = 10
z = "Howdy"
End If
Dim o1 As Object, o2 As New Object(), o3 as New Object(), o4 As Object
End Sub
Public Sub Main(args As String()) ' Method 2
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
True
False
True
False
False
True
True
True
Method 2
File 1
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics(
Diagnostic(ERRID.WRN_UnusedLocal, "y").WithArguments("y").WithLocation(3, 16),
Diagnostic(ERRID.WRN_UnusedLocal, "o1").WithArguments("o1").WithLocation(14, 13),
Diagnostic(ERRID.WRN_UnusedLocal, "aa").WithArguments("aa").WithLocation(6, 17),
Diagnostic(ERRID.WRN_UnusedLocal, "o4").WithArguments("o4").WithLocation(14, 67),
Diagnostic(ERRID.WRN_UnusedLocal, "bb").WithArguments("bb").WithLocation(6, 21),
Diagnostic(ERRID.WRN_UnusedLocal, "cc").WithArguments("cc").WithLocation(7, 17),
Diagnostic(ERRID.WRN_UnusedLocal, "dd").WithArguments("dd").WithLocation(7, 32))
End Sub
<Fact>
Public Sub PropertiesCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub TestMain() ' Method 1
xxx = 12
yyy = 11
yyy = zzz
End Sub
Public Sub Main(args As String()) ' Method 2
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Property xxx As Integer
Set ' Method 3
End Set
Get
Return 12
End Get
End Property
Property yyy
Property zzz As Integer
Set
End Set
Get ' Method 8
If yyy > 10 Then
Return 40
End If
Return 50
End Get
End Property
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
Method 8
File 1
True
True
True
False
Method 11
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestFieldInitializersCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Private x As Integer
Public Sub Main() ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Dim local As New C() : local = New C(1, 2)
End Sub
End Module
Class C
Shared Function Init() As Integer ' Method 3
Return 33
End Function
Sub New() ' Method 4
_z = 12
End Sub
Shared Sub New() ' Method 5
s_z = 123
End Sub
Private _x As Integer = Init()
Private _y As Integer = Init() + 12
Private _z As Integer
Private Shared s_x As Integer = Init()
Private Shared s_y As Integer = Init() + 153
Private Shared s_z As Integer
Sub New(x As Integer) ' Method 6
_z = x
End Sub
Sub New(a As Integer, b As Integer) ' Method 7
_z = a + b
End Sub
Property A As Integer = 1234
Shared Property B As Integer = 5678
End Class
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
Method 4
File 1
True
True
True
True
True
Method 5
File 1
True
True
True
True
True
Method 7
File 1
True
True
True
True
True
Method 14
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestImplicitConstructorCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Private x As Integer
Public Sub Main() ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Dim local As New C()
Dim x As Integer = local._x + C.s_x
End Sub
End Module
Class C
' Method 3 is the implicit shared constructor.
' Method 4 is the implicit instance constructor.
Shared Function Init() As Integer ' Method 5
Return 33
End Function
Public _x As Integer = Init()
Public _y As Integer = Init() + 12
Public Shared s_x As Integer = Init()
Public Shared s_y As Integer = Init() + 153
Public Shared s_z As Integer = 144
Property A As Integer = 1234
Shared Property B As Integer = 5678
End Class
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
True
True
Method 4
File 1
True
True
True
Method 5
File 1
True
True
Method 12
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestImplicitConstructorsWithLambdasCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Private x As Integer
Public Sub Main() ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Dim y As Integer = C.s_c._function()
Dim dd As New D()
Dim z As Integer = dd._c._function()
Dim zz As Integer = D.s_c._function()
Dim zzz As Integer = dd._c1._function()
Dim zzzz As Integer = F.s_c._function()
End Sub
End Module
Class C
Public Sub New(f As System.Func(Of Integer)) ' Method 4
_function = f
End Sub
Shared Public s_c As New C(Function () 15)
Public _function as System.Func(Of Integer)
End Class
Partial Class D
End Class
Partial Class D
Public _c As C = New C(Function() 120)
Public Shared s_c As C = New C(Function() 144)
Public _c1 As New C(Function()
Return 130
End Function)
Public Shared s_c1 As New C(Function()
Return 156
End Function)
End Class
Partial Class D
End Class
Structure E
Public Shared s_c As C = New C(Function() 1444)
Public Shared s_c1 As New C(Function()
Return 1567
End Function)
End Structure
Module F
Public s_c As New C(Function()
Return 333
End Function)
End Module
' Method 3 is the synthesized shared constructor for C.
' Method 5 is the synthesized shared constructor for D.
' Method 6 is the synthesized instance constructor for D.
' Method 7 (which is not called, and so does not appear in the output) is the synthesized shared constructor for E.
' Method 8 is the synthesized shared constructor for F.
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
True
True
Method 3
File 1
True
True
Method 4
File 1
True
True
Method 5
File 1
True
True
False
True
Method 6
File 1
True
True
True
True
Method 8
File 1
True
True
Method 11
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub MissingMethodNeededForAnalysis()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Namespace System
Public Class [Object] : End Class
Public Structure Int32 : End Structure
Public Structure [Boolean] : End Structure
Public Class [String] : End Class
Public Class Exception : End Class
Public Class ValueType : End Class
Public Class [Enum] : End Class
Public Structure Void : End Structure
Public Class Guid : End Class
End Namespace
Namespace System
Public Class Console
Public Shared Sub WriteLine(s As String)
End Sub
Public Shared Sub WriteLine(i As Integer)
End Sub
Public Shared Sub WriteLine(b As Boolean)
End Sub
End Class
End Namespace
Class Program
Public Shared Sub Main(args As String())
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Shared Sub TestMain()
End Sub
End Class
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim diagnostics As ImmutableArray(Of Diagnostic) = CreateCompilation(source).GetEmitDiagnostics(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
For Each Diagnostic As Diagnostic In diagnostics
If Diagnostic.Code = ERRID.ERR_MissingRuntimeHelper AndAlso Diagnostic.Arguments(0).Equals("System.Guid..ctor") Then
Return
End If
Next
Assert.True(False)
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Method()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
<ExcludeFromCodeCoverage>
Sub M1()
Console.WriteLine(1)
End Sub
Sub M2()
Console.WriteLine(1)
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C.M1")
AssertInstrumented(verifier, "C.M2")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Ctor()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
Dim a As Integer = 1
<ExcludeFromCodeCoverage>
Public Sub New()
Console.WriteLine(3)
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C..ctor")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Cctor()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
Shared a As Integer = 1
<ExcludeFromCodeCoverage>
Shared Sub New()
Console.WriteLine(3)
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C..cctor")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InMethod()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
<ExcludeFromCodeCoverage>
Shared Sub M1()
Dim s = New Action(Sub() Console.WriteLine(1))
s.Invoke()
End Sub
Shared Sub M2()
Dim s = New Action(Sub() Console.WriteLine(2))
s.Invoke()
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C.M1")
AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__1-0")
AssertInstrumented(verifier, "C.M2")
AssertInstrumented(verifier, "C._Closure$__2-0._Lambda$__0")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InInitializers()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
Dim [IF] As Action = Sub() Console.WriteLine(1)
ReadOnly Property IP As Action = Sub() Console.WriteLine(2)
Shared SF As Action = Sub() Console.WriteLine(3)
Shared ReadOnly Property SP As Action = Sub() Console.WriteLine(4)
<ExcludeFromCodeCoverage>
Sub New()
End Sub
Shared Sub New()
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
verifier.VerifyDiagnostics()
AssertNotInstrumented(verifier, "C..ctor")
AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-0")
AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-1")
AssertInstrumented(verifier, "C..cctor")
AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__0")
AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__1")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InAccessors()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
<ExcludeFromCodeCoverage>
Property P1 As Integer
Get
Dim s = Sub() Console.WriteLine(1)
s()
Return 1
End Get
Set
Dim s = Sub() Console.WriteLine(2)
s()
End Set
End Property
Property P2 As Integer
Get
Dim s = Sub() Console.WriteLine(3)
s()
Return 3
End Get
Set
Dim s = Sub() Console.WriteLine(4)
s()
End Set
End Property
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C.get_P1")
AssertNotInstrumented(verifier, "C.set_P1")
AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__2-0")
AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__3-0")
AssertInstrumented(verifier, "C.get_P2")
AssertInstrumented(verifier, "C.set_P2")
AssertInstrumented(verifier, "C._Closure$__6-0._Lambda$__0")
AssertInstrumented(verifier, "C._Closure$__5-0._Lambda$__0")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Type()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
<ExcludeFromCodeCoverage>
Class C
Dim x As Integer = 1
Shared Sub New()
End Sub
Sub M1()
Console.WriteLine(1)
End Sub
Property P As Integer
Get
Return 1
End Get
Set
End Set
End Property
Custom Event E As Action
AddHandler(v As Action)
End AddHandler
RemoveHandler(v As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
Class D
Dim x As Integer = 1
Shared Sub New()
End Sub
Sub M1()
Console.WriteLine(1)
End Sub
Property P As Integer
Get
Return 1
End Get
Set
End Set
End Property
Custom Event E As Action
AddHandler(v As Action)
End AddHandler
RemoveHandler(v As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C..ctor")
AssertNotInstrumented(verifier, "C..cctor")
AssertNotInstrumented(verifier, "C.M1")
AssertNotInstrumented(verifier, "C.get_P")
AssertNotInstrumented(verifier, "C.set_P")
AssertNotInstrumented(verifier, "C.add_E")
AssertNotInstrumented(verifier, "C.remove_E")
AssertNotInstrumented(verifier, "C.raise_E")
AssertInstrumented(verifier, "D..ctor")
AssertInstrumented(verifier, "D..cctor")
AssertInstrumented(verifier, "D.M1")
AssertInstrumented(verifier, "D.get_P")
AssertInstrumented(verifier, "D.set_P")
AssertInstrumented(verifier, "D.add_E")
AssertInstrumented(verifier, "D.remove_E")
AssertInstrumented(verifier, "D.raise_E")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_NestedType()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class A
Class B1
<ExcludeFromCodeCoverage>
Class C
Sub M1()
Console.WriteLine(1)
End Sub
End Class
Sub M2()
Console.WriteLine(2)
End Sub
End Class
<ExcludeFromCodeCoverage>
Partial Class B2
Partial Class C1
Sub M3()
Console.WriteLine(3)
End Sub
End Class
Class C2
Sub M4()
Console.WriteLine(4)
End Sub
End Class
Sub M5()
Console.WriteLine(5)
End Sub
End Class
Partial Class B2
<ExcludeFromCodeCoverage>
Partial Class C1
Sub M6()
Console.WriteLine(6)
End Sub
End Class
Sub M7()
Console.WriteLine(7)
End Sub
End Class
Sub M8()
Console.WriteLine(8)
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "A.B1.C.M1")
AssertInstrumented(verifier, "A.B1.M2")
AssertNotInstrumented(verifier, "A.B2.C1.M3")
AssertNotInstrumented(verifier, "A.B2.C2.M4")
AssertNotInstrumented(verifier, "A.B2.C1.M6")
AssertNotInstrumented(verifier, "A.B2.M7")
AssertInstrumented(verifier, "A.M8")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Accessors()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
<ExcludeFromCodeCoverage>
Property P1 As Integer
Get
Return 1
End Get
Set
End Set
End Property
<ExcludeFromCodeCoverage>
Custom Event E1 As Action
AddHandler(v As Action)
End AddHandler
RemoveHandler(v As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Property P2 As Integer
Get
Return 2
End Get
Set
End Set
End Property
Custom Event E2 As Action
AddHandler(v As Action)
End AddHandler
RemoveHandler(v As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C.get_P1")
AssertNotInstrumented(verifier, "C.set_P1")
AssertNotInstrumented(verifier, "C.add_E1")
AssertNotInstrumented(verifier, "C.remove_E1")
AssertNotInstrumented(verifier, "C.raise_E1")
AssertInstrumented(verifier, "C.get_P2")
AssertInstrumented(verifier, "C.set_P2")
AssertInstrumented(verifier, "C.add_E2")
AssertInstrumented(verifier, "C.remove_E2")
AssertInstrumented(verifier, "C.raise_E2")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Good()
Dim source = "
Imports System.Diagnostics.CodeAnalysis
Namespace System.Diagnostics.CodeAnalysis
<AttributeUsage(AttributeTargets.Class)>
Public Class ExcludeFromCodeCoverageAttribute
Inherits Attribute
Public Sub New()
End Sub
End Class
End Namespace
<ExcludeFromCodeCoverage>
Class C
Sub M()
End Sub
End Class
Class D
Sub M()
End Sub
End Class
"
Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
c.VerifyDiagnostics()
Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
c.VerifyEmitDiagnostics()
AssertNotInstrumented(verifier, "C.M")
AssertInstrumented(verifier, "D.M")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Bad()
Dim source = "
Imports System.Diagnostics.CodeAnalysis
Namespace System.Diagnostics.CodeAnalysis
<AttributeUsage(AttributeTargets.Class)>
Public Class ExcludeFromCodeCoverageAttribute
Inherits Attribute
Public Sub New(x As Integer)
End Sub
End Class
End Namespace
<ExcludeFromCodeCoverage(1)>
Class C
Sub M()
End Sub
End Class
Class D
Sub M()
End Sub
End Class
"
Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
c.VerifyDiagnostics()
Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
c.VerifyEmitDiagnostics()
AssertInstrumented(verifier, "C.M")
AssertInstrumented(verifier, "D.M")
End Sub
<Fact>
Public Sub TestPartialMethodsWithImplementation()
Dim testSource = <file name="c.vb">
<![CDATA[
Imports System
Partial Class Class1
Private Partial Sub Method1(x as Integer)
End Sub
Public Sub Method2(x as Integer)
Console.WriteLine("Method2: x = {0}", x)
Method1(x)
End Sub
End Class
Partial Class Class1
Private Sub Method1(x as Integer)
Console.WriteLine("Method1: x = {0}", x)
If x > 0
Console.WriteLine("Method1: x > 0")
Method1(0)
ElseIf x < 0
Console.WriteLine("Method1: x < 0")
End If
End Sub
End Class
Module Program
Public Sub Main()
Test()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub Test()
Console.WriteLine("Test")
Dim c = new Class1()
c.Method2(1)
End Sub
End Module
]]>
</file>
Dim source = <compilation>
<%= testSource %>
<%= InstrumentationHelperSource %>
</compilation>
Dim checker = New VBInstrumentationChecker()
checker.Method(1, 1, "New", expectBodySpan:=False)
checker.Method(2, 1, "Private Sub Method1(x as Integer)").
True("Console.WriteLine(""Method1: x = {0}"", x)").
True("Console.WriteLine(""Method1: x > 0"")").
True("Method1(0)").
False("Console.WriteLine(""Method1: x < 0"")").
True("x < 0").
True("x > 0")
checker.Method(3, 1, "Public Sub Method2(x as Integer)").
True("Console.WriteLine(""Method2: x = {0}"", x)").
True("Method1(x)")
checker.Method(4, 1, "Public Sub Main()").
True("Test()").
True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()")
checker.Method(5, 1, "Sub Test()").
True("Console.WriteLine(""Test"")").
True("new Class1()").
True("c.Method2(1)")
checker.Method(8, 1).
True().
False().
True().
True().
True().
True().
True().
True().
True().
True().
True().
True()
Dim expectedOutput = "Test
Method2: x = 1
Method1: x = 1
Method1: x > 0
Method1: x = 0
" + XCDataToString(checker.ExpectedOutput)
Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe)
checker.CompleteCheck(verifier.Compilation, testSource)
verifier.VerifyDiagnostics()
verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe)
checker.CompleteCheck(verifier.Compilation, testSource)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestPartialMethodsWithoutImplementation()
Dim testSource = <file name="c.vb">
<![CDATA[
Imports System
Partial Class Class1
Private Partial Sub Method1(x as Integer)
End Sub
Public Sub Method2(x as Integer)
Console.WriteLine("Method2: x = {0}", x)
Method1(x)
End Sub
End Class
Module Program
Public Sub Main()
Test()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub Test()
Console.WriteLine("Test")
Dim c = new Class1()
c.Method2(1)
End Sub
End Module
]]>
</file>
Dim source = <compilation>
<%= testSource %>
<%= InstrumentationHelperSource %>
</compilation>
Dim checker = New VBInstrumentationChecker()
checker.Method(1, 1, "New", expectBodySpan:=False)
checker.Method(2, 1, "Public Sub Method2(x as Integer)").
True("Console.WriteLine(""Method2: x = {0}"", x)")
checker.Method(3, 1, "Public Sub Main()").
True("Test()").
True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()")
checker.Method(4, 1, "Sub Test()").
True("Console.WriteLine(""Test"")").
True("new Class1()").
True("c.Method2(1)")
checker.Method(7, 1).
True().
False().
True().
True().
True().
True().
True().
True().
True().
True().
True().
True()
Dim expectedOutput = "Test
Method2: x = 1
" + XCDataToString(checker.ExpectedOutput)
Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe)
checker.CompleteCheck(verifier.Compilation, testSource)
verifier.VerifyDiagnostics()
verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe)
checker.CompleteCheck(verifier.Compilation, testSource)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestSynthesizedConstructorWithSpansInMultipleFilesCoverage()
Dim source1 = <file name="aa.vb">
<![CDATA[
Imports System
Partial Class Class1
Dim a As Action(Of Integer) =
Sub(i As Integer)
Console.WriteLine(i)
End Sub
End Class
Module Program
Public Sub Main()
Test()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub Test()
Console.WriteLine("Test")
Dim c = new Class1()
c.Method1(1)
End Sub
End Module
]]>
</file>
Dim source2 = <file name="bb.vb">
<![CDATA[
Imports System
Partial Class Class1
Dim x As Integer = 1
Sub Method1(i As Integer)
a(i)
Console.WriteLine(x)
Console.WriteLine(y)
Console.WriteLine(z)
End Sub
End Class
]]>
</file>
Dim source3 = <file name="cc.vb">
<![CDATA[
Partial Class Class1
Dim y As Integer = 2
Dim z As Integer = 3
End Class
]]>
</file>
Dim source = <compilation>
<%= source1 %>
<%= source2 %>
<%= source3 %>
<%= InstrumentationHelperSource %>
</compilation>
Dim expectedOutput = <![CDATA[Test
1
1
2
3
Flushing
Method 1
File 1
File 2
File 3
True
True
True
True
True
Method 2
File 2
True
True
True
True
True
Method 3
File 1
True
True
True
Method 4
File 1
True
True
True
True
Method 7
File 4
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe)
verifier.VerifyDiagnostics()
verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestSynthesizedStaticConstructorWithSpansInMultipleFilesCoverage()
Dim source1 = <file name="aa.vb">
<![CDATA[
Imports System
Partial Class Class1
Shared Dim a As Action(Of Integer) =
Sub(i As Integer)
Console.WriteLine(i)
End Sub
End Class
Module Program
Public Sub Main()
Test()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub Test()
Console.WriteLine("Test")
Dim c = new Class1()
Class1.Method1(1)
End Sub
End Module
]]>
</file>
Dim source2 = <file name="bb.vb">
<![CDATA[
Imports System
Partial Class Class1
Shared Dim x As Integer = 1
Shared Sub Method1(i As Integer)
a(i)
Console.WriteLine(x)
Console.WriteLine(y)
Console.WriteLine(z)
End Sub
End Class
]]>
</file>
Dim source3 = <file name="cc.vb">
<![CDATA[
Partial Class Class1
Shared Dim y As Integer = 2
Shared Dim z As Integer = 3
End Class
]]>
</file>
Dim source = <compilation>
<%= source1 %>
<%= source2 %>
<%= source3 %>
<%= InstrumentationHelperSource %>
</compilation>
Dim expectedOutput = <![CDATA[Test
1
1
2
3
Flushing
Method 1
File 1
File 2
File 3
True
True
True
True
True
Method 2
File 1
Method 3
File 2
True
True
True
True
True
Method 4
File 1
True
True
True
Method 5
File 1
True
True
True
True
Method 8
File 4
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe)
verifier.VerifyDiagnostics()
verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe)
verifier.VerifyDiagnostics()
End Sub
Private Shared Sub AssertNotInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String)
AssertInstrumented(verifier, qualifiedMethodName, expected:=False)
End Sub
Private Shared Sub AssertInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String, Optional expected As Boolean = True)
Dim il = verifier.VisualizeIL(qualifiedMethodName)
' Tests using this helper are constructed such that instrumented methods contain a call to CreatePayload,
' lambdas a reference to payload Boolean array.
Dim instrumented = il.Contains("CreatePayload") OrElse il.Contains("As Boolean()")
Assert.True(expected = instrumented, $"Method '{qualifiedMethodName}' should {If(expected, "be", "not be")} instrumented. Actual IL:{Environment.NewLine}{il}")
End Sub
Private Function CreateCompilation(source As XElement) As Compilation
Return CreateEmptyCompilationWithReferences(source, references:=New MetadataReference() {}, options:=TestOptions.ReleaseExe.WithDeterministic(True))
End Function
Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As XCData = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier
Return CompileAndVerify(source,
LatestVbReferences,
XCDataToString(expectedOutput),
options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True),
emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
End Function
Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier
Return CompileAndVerify(source,
LatestVbReferences,
expectedOutput,
options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True),
emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
End Function
Private Overloads Function CompileAndVerify(source As String, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier
Return CompileAndVerifyEx(source,
LatestVbReferences,
expectedOutput,
options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True),
emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)),
targetFramework:=TargetFramework.Empty)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Test.Utilities.VBInstrumentationChecker
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.DynamicAnalysis.UnitTests
Public Class DynamicInstrumentationTests
Inherits BasicTestBase
<Fact>
Public Sub SimpleCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
End Sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim checker = New VBInstrumentationChecker()
checker.Method(1, 1, "Public Sub Main").
True("TestMain()").
True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()")
checker.Method(2, 1, "Sub TestMain()")
checker.Method(5, 1).
True().
False().
True().
True().
True().
True().
True().
True().
True().
True().
True().
True()
Dim verifier As CompilationVerifier = CompileAndVerify(source, checker.ExpectedOutput)
checker.CompleteCheck(verifier.Compilation, testSource)
verifier.VerifyIL(
"Program.TestMain",
<![CDATA[{
// Code size 57 (0x39)
.maxstack 5
.locals init (Boolean() V_0)
IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0005: ldtoken "Sub Program.TestMain()"
IL_000a: ldelem.ref
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID"
IL_0014: ldtoken "Sub Program.TestMain()"
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0023: ldtoken "Sub Program.TestMain()"
IL_0028: ldelema "Boolean()"
IL_002d: ldc.i4.1
IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()"
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ret
}
]]>.Value)
verifier.VerifyIL(
".cctor",
<![CDATA[
{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldtoken Max Method Token Index
IL_0005: newarr "Boolean()"
IL_000a: stsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_000f: ldstr ##MVID##
IL_0014: newobj "Sub System.Guid..ctor(String)"
IL_0019: stsfld "System.Guid <PrivateImplementationDetails>.MVID"
IL_001e: ret
}
]]>.Value)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub MyTemplateNotCovered()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
End Sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 8
File 1
True
True
True
Method 9
File 1
True
Method 12
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
' Explicitly define the "_MyType" pre-processor definition so that the "My" template code is added to
' the compilation. The "My" template code returns a special "VisualBasicSyntaxNode" that reports an invalid
' path. The "DynamicAnalysisInjector" skips instrumenting such code.
Dim preprocessorSymbols = ImmutableArray.Create(New KeyValuePair(Of String, Object)("_MyType", "Console"))
Dim parseOptions = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols)
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput, TestOptions.ReleaseExe.WithParseOptions(parseOptions))
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub MultipleFilesCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Called()
End Sub
End Module
]]>
</file>
Dim testSource1 As XElement = <file name="d.vb">
<![CDATA[
Module More
Sub Called() ' Method 3
Another()
Another()
End Sub
End Module
]]>
</file>
Dim testSource2 As XElement = <file name="e.vb">
<![CDATA[
Module EvenMore
Sub Another() ' Method 4
End Sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(testSource1)
source.Add(testSource2)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
Method 3
File 2
True
True
True
Method 4
File 3
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub MethodsOfGenericTypesCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Class MyBox(Of T As Class)
ReadOnly _value As T
Public Sub New(value As T)
_value = value
End Sub
Public Function GetValue() As T
If _value Is Nothing Then
Return Nothing
End If
Return _value
End Function
End Class
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Dim x As MyBox(Of Object) = New MyBox(Of Object)(Nothing)
System.Console.WriteLine(If(x.GetValue() Is Nothing, "null", x.GetValue().ToString()))
Dim s As MyBox(Of String) = New MyBox(Of String)("Hello")
System.Console.WriteLine(If(s.GetValue() Is Nothing, "null", s.GetValue()))
End Sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[null
Hello
Flushing
Method 1
File 1
True
True
Method 2
File 1
True
True
True
True
Method 3
File 1
True
True
True
Method 4
File 1
True
True
True
True
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyIL(
"MyBox(Of T).GetValue",
<![CDATA[
{
// Code size 100 (0x64)
.maxstack 5
.locals init (T V_0, //GetValue
Boolean() V_1)
IL_0000: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0005: ldtoken "Function MyBox(Of T).GetValue() As T"
IL_000a: ldelem.ref
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: brtrue.s IL_0034
IL_000f: ldsfld "System.Guid <PrivateImplementationDetails>.MVID"
IL_0014: ldtoken "Function MyBox(Of T).GetValue() As T"
IL_0019: ldtoken Source Document 0
IL_001e: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0023: ldtoken "Function MyBox(Of T).GetValue() As T"
IL_0028: ldelema "Boolean()"
IL_002d: ldc.i4.4
IL_002e: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()"
IL_0033: stloc.1
IL_0034: ldloc.1
IL_0035: ldc.i4.0
IL_0036: ldc.i4.1
IL_0037: stelem.i1
IL_0038: ldloc.1
IL_0039: ldc.i4.2
IL_003a: ldc.i4.1
IL_003b: stelem.i1
IL_003c: ldarg.0
IL_003d: ldfld "MyBox(Of T)._value As T"
IL_0042: box "T"
IL_0047: brtrue.s IL_0057
IL_0049: ldloc.1
IL_004a: ldc.i4.1
IL_004b: ldc.i4.1
IL_004c: stelem.i1
IL_004d: ldloca.s V_0
IL_004f: initobj "T"
IL_0055: br.s IL_0062
IL_0057: ldloc.1
IL_0058: ldc.i4.3
IL_0059: ldc.i4.1
IL_005a: stelem.i1
IL_005b: ldarg.0
IL_005c: ldfld "MyBox(Of T)._value As T"
IL_0061: stloc.0
IL_0062: ldloc.0
IL_0063: ret
}
]]>.Value)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub LambdaCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain()
Dim y As Integer = 5
Dim tester As System.Func(Of Integer, Integer) = Function(x)
While x > 10
Return y
End While
Return x
End Function
Dim identity As System.Func(Of Integer, Integer) = Function(x) x
y = 75
If tester(20) > 50 AndAlso identity(20) = 20 Then
System.Console.WriteLine("OK")
Else
System.Console.WriteLine("Bad")
End If
End sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[OK
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
False
True
True
True
True
True
False
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub IteratorCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
For Each number In Goo()
System.Console.WriteLine(number)
Next
For Each number In Goo()
System.Console.WriteLine(number)
Next
End Sub
Public Iterator Function Goo() As System.Collections.Generic.IEnumerable(Of Integer) ' Method 3
For counter = 1 To 5
Yield counter
Next
End Function
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[1
2
3
4
5
1
2
3
4
5
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
Method 3
File 1
True
True
Method 6
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyIL(
"Program.VB$StateMachine_2_Goo.MoveNext()",
<![CDATA[
{
// Code size 149 (0x95)
.maxstack 5
.locals init (Integer V_0,
Boolean() V_1)
IL_0000: ldarg.0
IL_0001: ldfld "Program.VB$StateMachine_2_Goo.$State As Integer"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0010
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq.s IL_0073
IL_000e: ldc.i4.0
IL_000f: ret
IL_0010: ldarg.0
IL_0011: ldc.i4.m1
IL_0012: dup
IL_0013: stloc.0
IL_0014: stfld "Program.VB$StateMachine_2_Goo.$State As Integer"
IL_0019: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_001e: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)"
IL_0023: ldelem.ref
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: brtrue.s IL_004d
IL_0028: ldsfld "System.Guid <PrivateImplementationDetails>.MVID"
IL_002d: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)"
IL_0032: ldtoken Source Document 0
IL_0037: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_003c: ldtoken "Function Program.Goo() As System.Collections.Generic.IEnumerable(Of Integer)"
IL_0041: ldelema "Boolean()"
IL_0046: ldc.i4.2
IL_0047: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()"
IL_004c: stloc.1
IL_004d: ldloc.1
IL_004e: ldc.i4.0
IL_004f: ldc.i4.1
IL_0050: stelem.i1
IL_0051: ldloc.1
IL_0052: ldc.i4.1
IL_0053: ldc.i4.1
IL_0054: stelem.i1
IL_0055: ldarg.0
IL_0056: ldc.i4.1
IL_0057: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer"
IL_005c: ldarg.0
IL_005d: ldarg.0
IL_005e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer"
IL_0063: stfld "Program.VB$StateMachine_2_Goo.$Current As Integer"
IL_0068: ldarg.0
IL_0069: ldc.i4.1
IL_006a: dup
IL_006b: stloc.0
IL_006c: stfld "Program.VB$StateMachine_2_Goo.$State As Integer"
IL_0071: ldc.i4.1
IL_0072: ret
IL_0073: ldarg.0
IL_0074: ldc.i4.m1
IL_0075: dup
IL_0076: stloc.0
IL_0077: stfld "Program.VB$StateMachine_2_Goo.$State As Integer"
IL_007c: ldarg.0
IL_007d: ldarg.0
IL_007e: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer"
IL_0083: ldc.i4.1
IL_0084: add.ovf
IL_0085: stfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer"
IL_008a: ldarg.0
IL_008b: ldfld "Program.VB$StateMachine_2_Goo.$VB$ResumableLocal_counter$0 As Integer"
IL_0090: ldc.i4.5
IL_0091: ble.s IL_005c
IL_0093: ldc.i4.0
IL_0094: ret
}
]]>.Value)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub AsyncCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Imports System
Imports System.Threading.Tasks
Module Program
Public Sub Main(args As String()) ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Console.WriteLine(Outer("Goo").Result)
End Sub
Async Function Outer(s As String) As Task(Of String) ' Method 3
Dim s1 As String = Await First(s)
Dim s2 As String = Await Second(s)
Return s1 + s2
End Function
Async Function First(s As String) As Task(Of String) ' Method 4
Dim result As String = Await Second(s) + "Glue"
If result.Length > 2 Then
Return result
Else
Return "Too Short"
End If
End Function
Async Function Second(s As String) As Task(Of String) ' Method 5
Dim doubled As String = ""
If s.Length > 2 Then
doubled = s + s
Else
doubled = "HuhHuh"
End If
Return Await Task.Factory.StartNew(Function() doubled)
End Function
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[GooGooGlueGooGoo
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
Method 3
File 1
True
True
True
True
Method 4
File 1
True
True
True
False
True
Method 5
File 1
True
True
True
False
True
True
True
Method 8
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyIL(
"Program.VB$StateMachine_4_Second.MoveNext()",
<![CDATA[
{
// Code size 375 (0x177)
.maxstack 6
.locals init (String V_0,
Integer V_1,
Program._Closure$__4-0 V_2, //$VB$Closure_0
System.Runtime.CompilerServices.TaskAwaiter(Of String) V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld "Program.VB$StateMachine_4_Second.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse IL_010e
IL_000d: newobj "Sub Program._Closure$__4-0..ctor()"
IL_0012: stloc.2
IL_0013: ldloc.2
IL_0014: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0019: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)"
IL_001e: ldelem.ref
IL_001f: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_0024: ldloc.2
IL_0025: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_002a: brtrue.s IL_0056
IL_002c: ldloc.2
IL_002d: ldsfld "System.Guid <PrivateImplementationDetails>.MVID"
IL_0032: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)"
IL_0037: ldtoken Source Document 0
IL_003c: ldsfld "Boolean()() <PrivateImplementationDetails>.PayloadRoot0"
IL_0041: ldtoken "Function Program.Second(String) As System.Threading.Tasks.Task(Of String)"
IL_0046: ldelema "Boolean()"
IL_004b: ldc.i4.7
IL_004c: call "Function Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, Integer, Integer, ByRef Boolean(), Integer) As Boolean()"
IL_0051: stfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_0056: ldloc.2
IL_0057: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_005c: ldc.i4.0
IL_005d: ldc.i4.1
IL_005e: stelem.i1
IL_005f: ldloc.2
IL_0060: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_0065: ldc.i4.1
IL_0066: ldc.i4.1
IL_0067: stelem.i1
IL_0068: ldloc.2
IL_0069: ldstr ""
IL_006e: stfld "Program._Closure$__4-0.$VB$Local_doubled As String"
IL_0073: ldloc.2
IL_0074: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_0079: ldc.i4.4
IL_007a: ldc.i4.1
IL_007b: stelem.i1
IL_007c: ldarg.0
IL_007d: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String"
IL_0082: callvirt "Function String.get_Length() As Integer"
IL_0087: ldc.i4.2
IL_0088: ble.s IL_00ac
IL_008a: ldloc.2
IL_008b: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_0090: ldc.i4.2
IL_0091: ldc.i4.1
IL_0092: stelem.i1
IL_0093: ldloc.2
IL_0094: ldarg.0
IL_0095: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String"
IL_009a: ldarg.0
IL_009b: ldfld "Program.VB$StateMachine_4_Second.$VB$Local_s As String"
IL_00a0: call "Function String.Concat(String, String) As String"
IL_00a5: stfld "Program._Closure$__4-0.$VB$Local_doubled As String"
IL_00aa: br.s IL_00c0
IL_00ac: ldloc.2
IL_00ad: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_00b2: ldc.i4.3
IL_00b3: ldc.i4.1
IL_00b4: stelem.i1
IL_00b5: ldloc.2
IL_00b6: ldstr "HuhHuh"
IL_00bb: stfld "Program._Closure$__4-0.$VB$Local_doubled As String"
IL_00c0: ldloc.2
IL_00c1: ldfld "Program._Closure$__4-0.$VB$NonLocal_2 As Boolean()"
IL_00c6: ldc.i4.6
IL_00c7: ldc.i4.1
IL_00c8: stelem.i1
IL_00c9: call "Function System.Threading.Tasks.Task.get_Factory() As System.Threading.Tasks.TaskFactory"
IL_00ce: ldloc.2
IL_00cf: ldftn "Function Program._Closure$__4-0._Lambda$__0() As String"
IL_00d5: newobj "Sub System.Func(Of String)..ctor(Object, System.IntPtr)"
IL_00da: callvirt "Function System.Threading.Tasks.TaskFactory.StartNew(Of String)(System.Func(Of String)) As System.Threading.Tasks.Task(Of String)"
IL_00df: callvirt "Function System.Threading.Tasks.Task(Of String).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_00e4: stloc.3
IL_00e5: ldloca.s V_3
IL_00e7: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).get_IsCompleted() As Boolean"
IL_00ec: brtrue.s IL_012a
IL_00ee: ldarg.0
IL_00ef: ldc.i4.0
IL_00f0: dup
IL_00f1: stloc.1
IL_00f2: stfld "Program.VB$StateMachine_4_Second.$State As Integer"
IL_00f7: ldarg.0
IL_00f8: ldloc.3
IL_00f9: stfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_00fe: ldarg.0
IL_00ff: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_0104: ldloca.s V_3
IL_0106: ldarg.0
IL_0107: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of String), Program.VB$StateMachine_4_Second)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of String), ByRef Program.VB$StateMachine_4_Second)"
IL_010c: leave.s IL_0176
IL_010e: ldarg.0
IL_010f: ldc.i4.m1
IL_0110: dup
IL_0111: stloc.1
IL_0112: stfld "Program.VB$StateMachine_4_Second.$State As Integer"
IL_0117: ldarg.0
IL_0118: ldfld "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_011d: stloc.3
IL_011e: ldarg.0
IL_011f: ldflda "Program.VB$StateMachine_4_Second.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_0124: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_012a: ldloca.s V_3
IL_012c: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).GetResult() As String"
IL_0131: ldloca.s V_3
IL_0133: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_0139: stloc.0
IL_013a: leave.s IL_0160
}
catch System.Exception
{
IL_013c: dup
IL_013d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0142: stloc.s V_4
IL_0144: ldarg.0
IL_0145: ldc.i4.s -2
IL_0147: stfld "Program.VB$StateMachine_4_Second.$State As Integer"
IL_014c: ldarg.0
IL_014d: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_0152: ldloc.s V_4
IL_0154: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetException(System.Exception)"
IL_0159: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_015e: leave.s IL_0176
}
IL_0160: ldarg.0
IL_0161: ldc.i4.s -2
IL_0163: dup
IL_0164: stloc.1
IL_0165: stfld "Program.VB$StateMachine_4_Second.$State As Integer"
IL_016a: ldarg.0
IL_016b: ldflda "Program.VB$StateMachine_4_Second.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_0170: ldloc.0
IL_0171: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetResult(String)"
IL_0176: ret
}
]]>.Value)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub LoopsCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Function TestIf(a As Boolean, b As Boolean) As Integer ' Method 1
Dim x As Integer = 0
If a Then x += 1 Else x += 10
If a Then
x += 1
ElseIf a AndAlso b Then
x += 10
Else
x += 100
End If
If b Then
x += 1
End If
If a AndAlso b Then
x += 10
End If
Return x
End Function
Function TestDoLoops() As Integer ' Method 2
Dim x As Integer = 100
While x < 150
x += 1
End While
While x < 150
x += 1
End While
Do While x < 200
x += 1
Loop
Do Until x = 200
x += 1
Loop
Do
x += 1
Loop While x < 200
Do
x += 1
Loop Until x = 202
Do
Return x
Loop
End Function
Sub TestForLoops() ' Method 3
Dim x As Integer = 0
Dim y As Integer = 10
Dim z As Integer = 3
For a As Integer = x To y Step z
z += 1
Next
For b As Integer = 1 To 10
z += 1
Next
For Each c As Integer In {x, y, z}
z += 1
Next
End Sub
Public Sub Main(args As String())
TestIf(False, False)
TestIf(True, False)
TestDoLoops()
TestForLoops()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
True
True
True
False
True
True
True
False
True
False
True
True
Method 2
File 1
True
True
True
True
False
True
True
True
False
True
True
True
True
True
True
Method 3
File 1
True
True
True
True
True
True
True
True
True
True
Method 4
File 1
True
True
True
True
True
True
Method 7
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TryAndSelectCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub TryAndSelect() ' Method 1
Dim y As Integer = 0
Try
Try
For x As Integer = 0 To 10
Select Case x
Case 0
y += 1
Case 1
Throw New System.Exception()
Case >= 2
y += 1
Case Else
y += 1
End Select
Next
Catch e As System.Exception
y += 1
End Try
Finally
y += 1
End Try
End Sub
Public Sub Main(args As String())
TryAndSelect()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
True
True
True
False
False
True
True
Method 2
File 1
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub BranchesCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub Branches() ' Method 1
Dim y As Integer = 0
MyLabel:
Do
Exit Do
y += 1
Loop
For x As Integer = 1 To 10
Exit For
y += 1
Next
Try
Exit Try
y += 1
Catch ex As System.Exception
End Try
Select Case y
Case 0
Exit Select
y += 0
End Select
If y = 0 Then
Exit Sub
End If
GoTo MyLabel
End Sub
Public Sub Main(args As String()) ' Method 2
Branches()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
False
True
True
False
True
False
True
True
False
True
True
False
Method 2
File 1
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub StaticLocalsCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub TestMain() ' Method 1
Dim x As Integer = 1
Static y As Integer = 2
If x + y = 3 Then
Dim a As Integer = 10
Static b As Integer = 20
If a + b = 31 Then
Return
End If
End If
End Sub
Public Sub Main(args As String()) ' Method 2
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
True
True
False
True
True
Method 2
File 1
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub OddCornersCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub TestMain() ' Method 1
Dim h As New HasEvents()
h.Stuff()
End Sub
Class HasEvents
WithEvents f As HasEvents
Sub New() ' Method 9
AddHandler Mumble, AddressOf Handler
End Sub
Event Mumble()
Event Stumble()
Sub Handler() Handles Me.Stumble ' Method 14
End Sub
Sub Stuff() ' Method 15
f = New HasEvents()
RaiseEvent Mumble()
RaiseEvent Stumble()
RemoveHandler Mumble, AddressOf Handler
Dim meme As HasEvents = Me + Me
End Sub
Shared Operator +(x As HasEvents, y As HasEvents) As HasEvents ' Method 16
Return x
End Operator
End Class
Public Sub Main(args As String()) ' Method 2
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
Method 10
File 1
True
True
Method 15
File 1
True
Method 16
File 1
True
True
True
True
True
True
Method 17
File 1
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub DoubleDeclarationsCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub TestMain() ' Method 1
Dim x, y As Integer, z As String
Dim a As Integer = 10, b As Integer = 20, c as Integer = 30
If a = 11 Then
Dim aa, bb As Integer
Dim cc As Integer, dd As Integer
Return
End If
If a + b + c = 61 Then
x = 10
z = "Howdy"
End If
Dim o1 As Object, o2 As New Object(), o3 as New Object(), o4 As Object
End Sub
Public Sub Main(args As String()) ' Method 2
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
True
False
True
False
False
True
True
True
Method 2
File 1
True
True
True
Method 5
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics(
Diagnostic(ERRID.WRN_UnusedLocal, "y").WithArguments("y").WithLocation(3, 16),
Diagnostic(ERRID.WRN_UnusedLocal, "o1").WithArguments("o1").WithLocation(14, 13),
Diagnostic(ERRID.WRN_UnusedLocal, "aa").WithArguments("aa").WithLocation(6, 17),
Diagnostic(ERRID.WRN_UnusedLocal, "o4").WithArguments("o4").WithLocation(14, 67),
Diagnostic(ERRID.WRN_UnusedLocal, "bb").WithArguments("bb").WithLocation(6, 21),
Diagnostic(ERRID.WRN_UnusedLocal, "cc").WithArguments("cc").WithLocation(7, 17),
Diagnostic(ERRID.WRN_UnusedLocal, "dd").WithArguments("dd").WithLocation(7, 32))
End Sub
<Fact>
Public Sub PropertiesCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Sub TestMain() ' Method 1
xxx = 12
yyy = 11
yyy = zzz
End Sub
Public Sub Main(args As String()) ' Method 2
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Property xxx As Integer
Set ' Method 3
End Set
Get
Return 12
End Get
End Property
Property yyy
Property zzz As Integer
Set
End Set
Get ' Method 8
If yyy > 10 Then
Return 40
End If
Return 50
End Get
End Property
End Module
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
Method 8
File 1
True
True
True
False
Method 11
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestFieldInitializersCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Private x As Integer
Public Sub Main() ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Dim local As New C() : local = New C(1, 2)
End Sub
End Module
Class C
Shared Function Init() As Integer ' Method 3
Return 33
End Function
Sub New() ' Method 4
_z = 12
End Sub
Shared Sub New() ' Method 5
s_z = 123
End Sub
Private _x As Integer = Init()
Private _y As Integer = Init() + 12
Private _z As Integer
Private Shared s_x As Integer = Init()
Private Shared s_y As Integer = Init() + 153
Private Shared s_z As Integer
Sub New(x As Integer) ' Method 6
_z = x
End Sub
Sub New(a As Integer, b As Integer) ' Method 7
_z = a + b
End Sub
Property A As Integer = 1234
Shared Property B As Integer = 5678
End Class
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
Method 4
File 1
True
True
True
True
True
Method 5
File 1
True
True
True
True
True
Method 7
File 1
True
True
True
True
True
Method 14
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestImplicitConstructorCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Private x As Integer
Public Sub Main() ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Dim local As New C()
Dim x As Integer = local._x + C.s_x
End Sub
End Module
Class C
' Method 3 is the implicit shared constructor.
' Method 4 is the implicit instance constructor.
Shared Function Init() As Integer ' Method 5
Return 33
End Function
Public _x As Integer = Init()
Public _y As Integer = Init() + 12
Public Shared s_x As Integer = Init()
Public Shared s_y As Integer = Init() + 153
Public Shared s_z As Integer = 144
Property A As Integer = 1234
Shared Property B As Integer = 5678
End Class
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
Method 3
File 1
True
True
True
True
Method 4
File 1
True
True
True
Method 5
File 1
True
True
Method 12
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestImplicitConstructorsWithLambdasCoverage()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Module Program
Private x As Integer
Public Sub Main() ' Method 1
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub TestMain() ' Method 2
Dim y As Integer = C.s_c._function()
Dim dd As New D()
Dim z As Integer = dd._c._function()
Dim zz As Integer = D.s_c._function()
Dim zzz As Integer = dd._c1._function()
Dim zzzz As Integer = F.s_c._function()
End Sub
End Module
Class C
Public Sub New(f As System.Func(Of Integer)) ' Method 4
_function = f
End Sub
Shared Public s_c As New C(Function () 15)
Public _function as System.Func(Of Integer)
End Class
Partial Class D
End Class
Partial Class D
Public _c As C = New C(Function() 120)
Public Shared s_c As C = New C(Function() 144)
Public _c1 As New C(Function()
Return 130
End Function)
Public Shared s_c1 As New C(Function()
Return 156
End Function)
End Class
Partial Class D
End Class
Structure E
Public Shared s_c As C = New C(Function() 1444)
Public Shared s_c1 As New C(Function()
Return 1567
End Function)
End Structure
Module F
Public s_c As New C(Function()
Return 333
End Function)
End Module
' Method 3 is the synthesized shared constructor for C.
' Method 5 is the synthesized shared constructor for D.
' Method 6 is the synthesized instance constructor for D.
' Method 7 (which is not called, and so does not appear in the output) is the synthesized shared constructor for E.
' Method 8 is the synthesized shared constructor for F.
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim expectedOutput As XCData = <![CDATA[
Flushing
Method 1
File 1
True
True
True
Method 2
File 1
True
True
True
True
True
True
True
Method 3
File 1
True
True
Method 4
File 1
True
True
Method 5
File 1
True
True
False
True
Method 6
File 1
True
True
True
True
Method 8
File 1
True
True
Method 11
File 1
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier As CompilationVerifier = CompileAndVerify(source, expectedOutput)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub MissingMethodNeededForAnalysis()
Dim testSource As XElement = <file name="c.vb">
<![CDATA[
Namespace System
Public Class [Object] : End Class
Public Structure Int32 : End Structure
Public Structure [Boolean] : End Structure
Public Class [String] : End Class
Public Class Exception : End Class
Public Class ValueType : End Class
Public Class [Enum] : End Class
Public Structure Void : End Structure
Public Class Guid : End Class
End Namespace
Namespace System
Public Class Console
Public Shared Sub WriteLine(s As String)
End Sub
Public Shared Sub WriteLine(i As Integer)
End Sub
Public Shared Sub WriteLine(b As Boolean)
End Sub
End Class
End Namespace
Class Program
Public Shared Sub Main(args As String())
TestMain()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Shared Sub TestMain()
End Sub
End Class
]]>
</file>
Dim source As Xml.Linq.XElement = <compilation></compilation>
source.Add(testSource)
source.Add(InstrumentationHelperSource)
Dim diagnostics As ImmutableArray(Of Diagnostic) = CreateCompilation(source).GetEmitDiagnostics(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
For Each Diagnostic As Diagnostic In diagnostics
If Diagnostic.Code = ERRID.ERR_MissingRuntimeHelper AndAlso Diagnostic.Arguments(0).Equals("System.Guid..ctor") Then
Return
End If
Next
Assert.True(False)
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Method()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
<ExcludeFromCodeCoverage>
Sub M1()
Console.WriteLine(1)
End Sub
Sub M2()
Console.WriteLine(1)
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C.M1")
AssertInstrumented(verifier, "C.M2")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Ctor()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
Dim a As Integer = 1
<ExcludeFromCodeCoverage>
Public Sub New()
Console.WriteLine(3)
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C..ctor")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Cctor()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
Shared a As Integer = 1
<ExcludeFromCodeCoverage>
Shared Sub New()
Console.WriteLine(3)
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C..cctor")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InMethod()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
<ExcludeFromCodeCoverage>
Shared Sub M1()
Dim s = New Action(Sub() Console.WriteLine(1))
s.Invoke()
End Sub
Shared Sub M2()
Dim s = New Action(Sub() Console.WriteLine(2))
s.Invoke()
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C.M1")
AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__1-0")
AssertInstrumented(verifier, "C.M2")
AssertInstrumented(verifier, "C._Closure$__2-0._Lambda$__0")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InInitializers()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
Dim [IF] As Action = Sub() Console.WriteLine(1)
ReadOnly Property IP As Action = Sub() Console.WriteLine(2)
Shared SF As Action = Sub() Console.WriteLine(3)
Shared ReadOnly Property SP As Action = Sub() Console.WriteLine(4)
<ExcludeFromCodeCoverage>
Sub New()
End Sub
Shared Sub New()
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
verifier.VerifyDiagnostics()
AssertNotInstrumented(verifier, "C..ctor")
AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-0")
AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__8-1")
AssertInstrumented(verifier, "C..cctor")
AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__0")
AssertInstrumented(verifier, "C._Closure$__9-0._Lambda$__1")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Lambdas_InAccessors()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
<ExcludeFromCodeCoverage>
Property P1 As Integer
Get
Dim s = Sub() Console.WriteLine(1)
s()
Return 1
End Get
Set
Dim s = Sub() Console.WriteLine(2)
s()
End Set
End Property
Property P2 As Integer
Get
Dim s = Sub() Console.WriteLine(3)
s()
Return 3
End Get
Set
Dim s = Sub() Console.WriteLine(4)
s()
End Set
End Property
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C.get_P1")
AssertNotInstrumented(verifier, "C.set_P1")
AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__2-0")
AssertNotInstrumented(verifier, "C._Closure$__._Lambda$__3-0")
AssertInstrumented(verifier, "C.get_P2")
AssertInstrumented(verifier, "C.set_P2")
AssertInstrumented(verifier, "C._Closure$__6-0._Lambda$__0")
AssertInstrumented(verifier, "C._Closure$__5-0._Lambda$__0")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Type()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
<ExcludeFromCodeCoverage>
Class C
Dim x As Integer = 1
Shared Sub New()
End Sub
Sub M1()
Console.WriteLine(1)
End Sub
Property P As Integer
Get
Return 1
End Get
Set
End Set
End Property
Custom Event E As Action
AddHandler(v As Action)
End AddHandler
RemoveHandler(v As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
Class D
Dim x As Integer = 1
Shared Sub New()
End Sub
Sub M1()
Console.WriteLine(1)
End Sub
Property P As Integer
Get
Return 1
End Get
Set
End Set
End Property
Custom Event E As Action
AddHandler(v As Action)
End AddHandler
RemoveHandler(v As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C..ctor")
AssertNotInstrumented(verifier, "C..cctor")
AssertNotInstrumented(verifier, "C.M1")
AssertNotInstrumented(verifier, "C.get_P")
AssertNotInstrumented(verifier, "C.set_P")
AssertNotInstrumented(verifier, "C.add_E")
AssertNotInstrumented(verifier, "C.remove_E")
AssertNotInstrumented(verifier, "C.raise_E")
AssertInstrumented(verifier, "D..ctor")
AssertInstrumented(verifier, "D..cctor")
AssertInstrumented(verifier, "D.M1")
AssertInstrumented(verifier, "D.get_P")
AssertInstrumented(verifier, "D.set_P")
AssertInstrumented(verifier, "D.add_E")
AssertInstrumented(verifier, "D.remove_E")
AssertInstrumented(verifier, "D.raise_E")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_NestedType()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class A
Class B1
<ExcludeFromCodeCoverage>
Class C
Sub M1()
Console.WriteLine(1)
End Sub
End Class
Sub M2()
Console.WriteLine(2)
End Sub
End Class
<ExcludeFromCodeCoverage>
Partial Class B2
Partial Class C1
Sub M3()
Console.WriteLine(3)
End Sub
End Class
Class C2
Sub M4()
Console.WriteLine(4)
End Sub
End Class
Sub M5()
Console.WriteLine(5)
End Sub
End Class
Partial Class B2
<ExcludeFromCodeCoverage>
Partial Class C1
Sub M6()
Console.WriteLine(6)
End Sub
End Class
Sub M7()
Console.WriteLine(7)
End Sub
End Class
Sub M8()
Console.WriteLine(8)
End Sub
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "A.B1.C.M1")
AssertInstrumented(verifier, "A.B1.M2")
AssertNotInstrumented(verifier, "A.B2.C1.M3")
AssertNotInstrumented(verifier, "A.B2.C2.M4")
AssertNotInstrumented(verifier, "A.B2.C1.M6")
AssertNotInstrumented(verifier, "A.B2.M7")
AssertInstrumented(verifier, "A.M8")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_Accessors()
Dim source = "
Imports System
Imports System.Diagnostics.CodeAnalysis
Class C
<ExcludeFromCodeCoverage>
Property P1 As Integer
Get
Return 1
End Get
Set
End Set
End Property
<ExcludeFromCodeCoverage>
Custom Event E1 As Action
AddHandler(v As Action)
End AddHandler
RemoveHandler(v As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Property P2 As Integer
Get
Return 2
End Get
Set
End Set
End Property
Custom Event E2 As Action
AddHandler(v As Action)
End AddHandler
RemoveHandler(v As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
"
Dim verifier = CompileAndVerify(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
AssertNotInstrumented(verifier, "C.get_P1")
AssertNotInstrumented(verifier, "C.set_P1")
AssertNotInstrumented(verifier, "C.add_E1")
AssertNotInstrumented(verifier, "C.remove_E1")
AssertNotInstrumented(verifier, "C.raise_E1")
AssertInstrumented(verifier, "C.get_P2")
AssertInstrumented(verifier, "C.set_P2")
AssertInstrumented(verifier, "C.add_E2")
AssertInstrumented(verifier, "C.remove_E2")
AssertInstrumented(verifier, "C.raise_E2")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Good()
Dim source = "
Imports System.Diagnostics.CodeAnalysis
Namespace System.Diagnostics.CodeAnalysis
<AttributeUsage(AttributeTargets.Class)>
Public Class ExcludeFromCodeCoverageAttribute
Inherits Attribute
Public Sub New()
End Sub
End Class
End Namespace
<ExcludeFromCodeCoverage>
Class C
Sub M()
End Sub
End Class
Class D
Sub M()
End Sub
End Class
"
Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
c.VerifyDiagnostics()
Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
c.VerifyEmitDiagnostics()
AssertNotInstrumented(verifier, "C.M")
AssertInstrumented(verifier, "D.M")
End Sub
<Fact>
Public Sub ExcludeFromCodeCoverageAttribute_CustomDefinition_Bad()
Dim source = "
Imports System.Diagnostics.CodeAnalysis
Namespace System.Diagnostics.CodeAnalysis
<AttributeUsage(AttributeTargets.Class)>
Public Class ExcludeFromCodeCoverageAttribute
Inherits Attribute
Public Sub New(x As Integer)
End Sub
End Class
End Namespace
<ExcludeFromCodeCoverage(1)>
Class C
Sub M()
End Sub
End Class
Class D
Sub M()
End Sub
End Class
"
Dim c = CreateCompilationWithMscorlib40(source & InstrumentationHelperSourceStr, options:=TestOptions.ReleaseDll)
c.VerifyDiagnostics()
Dim verifier = CompileAndVerify(c, emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
c.VerifyEmitDiagnostics()
AssertInstrumented(verifier, "C.M")
AssertInstrumented(verifier, "D.M")
End Sub
<Fact>
Public Sub TestPartialMethodsWithImplementation()
Dim testSource = <file name="c.vb">
<![CDATA[
Imports System
Partial Class Class1
Private Partial Sub Method1(x as Integer)
End Sub
Public Sub Method2(x as Integer)
Console.WriteLine("Method2: x = {0}", x)
Method1(x)
End Sub
End Class
Partial Class Class1
Private Sub Method1(x as Integer)
Console.WriteLine("Method1: x = {0}", x)
If x > 0
Console.WriteLine("Method1: x > 0")
Method1(0)
ElseIf x < 0
Console.WriteLine("Method1: x < 0")
End If
End Sub
End Class
Module Program
Public Sub Main()
Test()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub Test()
Console.WriteLine("Test")
Dim c = new Class1()
c.Method2(1)
End Sub
End Module
]]>
</file>
Dim source = <compilation>
<%= testSource %>
<%= InstrumentationHelperSource %>
</compilation>
Dim checker = New VBInstrumentationChecker()
checker.Method(1, 1, "New", expectBodySpan:=False)
checker.Method(2, 1, "Private Sub Method1(x as Integer)").
True("Console.WriteLine(""Method1: x = {0}"", x)").
True("Console.WriteLine(""Method1: x > 0"")").
True("Method1(0)").
False("Console.WriteLine(""Method1: x < 0"")").
True("x < 0").
True("x > 0")
checker.Method(3, 1, "Public Sub Method2(x as Integer)").
True("Console.WriteLine(""Method2: x = {0}"", x)").
True("Method1(x)")
checker.Method(4, 1, "Public Sub Main()").
True("Test()").
True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()")
checker.Method(5, 1, "Sub Test()").
True("Console.WriteLine(""Test"")").
True("new Class1()").
True("c.Method2(1)")
checker.Method(8, 1).
True().
False().
True().
True().
True().
True().
True().
True().
True().
True().
True().
True()
Dim expectedOutput = "Test
Method2: x = 1
Method1: x = 1
Method1: x > 0
Method1: x = 0
" + XCDataToString(checker.ExpectedOutput)
Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe)
checker.CompleteCheck(verifier.Compilation, testSource)
verifier.VerifyDiagnostics()
verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe)
checker.CompleteCheck(verifier.Compilation, testSource)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestPartialMethodsWithoutImplementation()
Dim testSource = <file name="c.vb">
<![CDATA[
Imports System
Partial Class Class1
Private Partial Sub Method1(x as Integer)
End Sub
Public Sub Method2(x as Integer)
Console.WriteLine("Method2: x = {0}", x)
Method1(x)
End Sub
End Class
Module Program
Public Sub Main()
Test()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub Test()
Console.WriteLine("Test")
Dim c = new Class1()
c.Method2(1)
End Sub
End Module
]]>
</file>
Dim source = <compilation>
<%= testSource %>
<%= InstrumentationHelperSource %>
</compilation>
Dim checker = New VBInstrumentationChecker()
checker.Method(1, 1, "New", expectBodySpan:=False)
checker.Method(2, 1, "Public Sub Method2(x as Integer)").
True("Console.WriteLine(""Method2: x = {0}"", x)")
checker.Method(3, 1, "Public Sub Main()").
True("Test()").
True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()")
checker.Method(4, 1, "Sub Test()").
True("Console.WriteLine(""Test"")").
True("new Class1()").
True("c.Method2(1)")
checker.Method(7, 1).
True().
False().
True().
True().
True().
True().
True().
True().
True().
True().
True().
True()
Dim expectedOutput = "Test
Method2: x = 1
" + XCDataToString(checker.ExpectedOutput)
Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe)
checker.CompleteCheck(verifier.Compilation, testSource)
verifier.VerifyDiagnostics()
verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe)
checker.CompleteCheck(verifier.Compilation, testSource)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestSynthesizedConstructorWithSpansInMultipleFilesCoverage()
Dim source1 = <file name="aa.vb">
<![CDATA[
Imports System
Partial Class Class1
Dim a As Action(Of Integer) =
Sub(i As Integer)
Console.WriteLine(i)
End Sub
End Class
Module Program
Public Sub Main()
Test()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub Test()
Console.WriteLine("Test")
Dim c = new Class1()
c.Method1(1)
End Sub
End Module
]]>
</file>
Dim source2 = <file name="bb.vb">
<![CDATA[
Imports System
Partial Class Class1
Dim x As Integer = 1
Sub Method1(i As Integer)
a(i)
Console.WriteLine(x)
Console.WriteLine(y)
Console.WriteLine(z)
End Sub
End Class
]]>
</file>
Dim source3 = <file name="cc.vb">
<![CDATA[
Partial Class Class1
Dim y As Integer = 2
Dim z As Integer = 3
End Class
]]>
</file>
Dim source = <compilation>
<%= source1 %>
<%= source2 %>
<%= source3 %>
<%= InstrumentationHelperSource %>
</compilation>
Dim expectedOutput = <![CDATA[Test
1
1
2
3
Flushing
Method 1
File 1
File 2
File 3
True
True
True
True
True
Method 2
File 2
True
True
True
True
True
Method 3
File 1
True
True
True
Method 4
File 1
True
True
True
True
Method 7
File 4
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe)
verifier.VerifyDiagnostics()
verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe)
verifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestSynthesizedStaticConstructorWithSpansInMultipleFilesCoverage()
Dim source1 = <file name="aa.vb">
<![CDATA[
Imports System
Partial Class Class1
Shared Dim a As Action(Of Integer) =
Sub(i As Integer)
Console.WriteLine(i)
End Sub
End Class
Module Program
Public Sub Main()
Test()
Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
End Sub
Sub Test()
Console.WriteLine("Test")
Dim c = new Class1()
Class1.Method1(1)
End Sub
End Module
]]>
</file>
Dim source2 = <file name="bb.vb">
<![CDATA[
Imports System
Partial Class Class1
Shared Dim x As Integer = 1
Shared Sub Method1(i As Integer)
a(i)
Console.WriteLine(x)
Console.WriteLine(y)
Console.WriteLine(z)
End Sub
End Class
]]>
</file>
Dim source3 = <file name="cc.vb">
<![CDATA[
Partial Class Class1
Shared Dim y As Integer = 2
Shared Dim z As Integer = 3
End Class
]]>
</file>
Dim source = <compilation>
<%= source1 %>
<%= source2 %>
<%= source3 %>
<%= InstrumentationHelperSource %>
</compilation>
Dim expectedOutput = <![CDATA[Test
1
1
2
3
Flushing
Method 1
File 1
File 2
File 3
True
True
True
True
True
Method 2
File 1
Method 3
File 2
True
True
True
True
True
Method 4
File 1
True
True
True
Method 5
File 1
True
True
True
True
Method 8
File 4
True
True
False
True
True
True
True
True
True
True
True
True
True
]]>
Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe)
verifier.VerifyDiagnostics()
verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe)
verifier.VerifyDiagnostics()
End Sub
Private Shared Sub AssertNotInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String)
AssertInstrumented(verifier, qualifiedMethodName, expected:=False)
End Sub
Private Shared Sub AssertInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String, Optional expected As Boolean = True)
Dim il = verifier.VisualizeIL(qualifiedMethodName)
' Tests using this helper are constructed such that instrumented methods contain a call to CreatePayload,
' lambdas a reference to payload Boolean array.
Dim instrumented = il.Contains("CreatePayload") OrElse il.Contains("As Boolean()")
Assert.True(expected = instrumented, $"Method '{qualifiedMethodName}' should {If(expected, "be", "not be")} instrumented. Actual IL:{Environment.NewLine}{il}")
End Sub
Private Function CreateCompilation(source As XElement) As Compilation
Return CreateEmptyCompilationWithReferences(source, references:=New MetadataReference() {}, options:=TestOptions.ReleaseExe.WithDeterministic(True))
End Function
Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As XCData = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier
Return CompileAndVerify(source,
LatestVbReferences,
XCDataToString(expectedOutput),
options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True),
emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
End Function
Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier
Return CompileAndVerify(source,
LatestVbReferences,
expectedOutput,
options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True),
emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
End Function
Private Overloads Function CompileAndVerify(source As String, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier
Return CompileAndVerifyEx(source,
LatestVbReferences,
expectedOutput,
options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True),
emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)),
targetFramework:=TargetFramework.Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Workspaces/Core/Portable/Workspace/Solution/DocumentState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class DocumentState : TextDocumentState
{
private static readonly Func<string?, PreservationMode, string> s_fullParseLog = (path, mode) => $"{path} : {mode}";
private static readonly ConditionalWeakTable<SyntaxTree, DocumentId> s_syntaxTreeToIdMap =
new();
private readonly HostLanguageServices _languageServices;
private readonly ParseOptions? _options;
// null if the document doesn't support syntax trees:
private readonly ValueSource<TreeAndVersion>? _treeSource;
protected DocumentState(
HostLanguageServices languageServices,
SolutionServices solutionServices,
IDocumentServiceProvider? documentServiceProvider,
DocumentInfo.DocumentAttributes attributes,
ParseOptions? options,
SourceText? sourceText,
ValueSource<TextAndVersion> textSource,
ValueSource<TreeAndVersion>? treeSource)
: base(solutionServices, documentServiceProvider, attributes, sourceText, textSource)
{
_languageServices = languageServices;
_options = options;
_treeSource = treeSource;
}
public DocumentState(
DocumentInfo info,
ParseOptions? options,
HostLanguageServices languageServices,
SolutionServices services)
: base(info, services)
{
_languageServices = languageServices;
_options = options;
// If this is document that doesn't support syntax, then don't even bother holding
// onto any tree source. It will never be used to get a tree, and can only hurt us
// by possibly holding onto data that might cause a slow memory leak.
if (languageServices.SyntaxTreeFactory == null)
{
_treeSource = null;
}
else
{
Contract.ThrowIfNull(options);
_treeSource = CreateLazyFullyParsedTree(
base.TextAndVersionSource,
info.Id.ProjectId,
GetSyntaxTreeFilePath(info.Attributes),
options,
languageServices);
}
}
internal bool SupportsSyntaxTree
=> _treeSource != null;
public HostLanguageServices LanguageServices
=> _languageServices;
public ParseOptions? ParseOptions
=> _options;
public SourceCodeKind SourceCodeKind
=> ParseOptions == null ? Attributes.SourceCodeKind : ParseOptions.Kind;
public bool IsGenerated
=> Attributes.IsGenerated;
// This is the string used to represent the FilePath property on a SyntaxTree object.
// if the document does not yet have a file path, use the document's name instead in regular code
// or an empty string in script code.
private static string GetSyntaxTreeFilePath(DocumentInfo.DocumentAttributes info)
{
if (info.FilePath != null)
{
return info.FilePath;
}
return info.SourceCodeKind == SourceCodeKind.Regular
? info.Name
: "";
}
protected static ValueSource<TreeAndVersion> CreateLazyFullyParsedTree(
ValueSource<TextAndVersion> newTextSource,
ProjectId cacheKey,
string? filePath,
ParseOptions options,
HostLanguageServices languageServices,
PreservationMode mode = PreservationMode.PreserveValue)
{
return new AsyncLazy<TreeAndVersion>(
c => FullyParseTreeAsync(newTextSource, cacheKey, filePath, options, languageServices, mode, c),
c => FullyParseTree(newTextSource, cacheKey, filePath, options, languageServices, mode, c),
cacheResult: true);
}
private static async Task<TreeAndVersion> FullyParseTreeAsync(
ValueSource<TextAndVersion> newTextSource,
ProjectId cacheKey,
string? filePath,
ParseOptions options,
HostLanguageServices languageServices,
PreservationMode mode,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Workspace_Document_State_FullyParseSyntaxTree, s_fullParseLog, filePath, mode, cancellationToken))
{
var textAndVersion = await newTextSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
return CreateTreeAndVersion(newTextSource, cacheKey, filePath, options, languageServices, mode, textAndVersion, cancellationToken);
}
}
private static TreeAndVersion FullyParseTree(
ValueSource<TextAndVersion> newTextSource,
ProjectId cacheKey,
string? filePath,
ParseOptions options,
HostLanguageServices languageServices,
PreservationMode mode,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Workspace_Document_State_FullyParseSyntaxTree, s_fullParseLog, filePath, mode, cancellationToken))
{
var textAndVersion = newTextSource.GetValue(cancellationToken);
return CreateTreeAndVersion(newTextSource, cacheKey, filePath, options, languageServices, mode, textAndVersion, cancellationToken);
}
}
private static TreeAndVersion CreateTreeAndVersion(
ValueSource<TextAndVersion> newTextSource,
ProjectId cacheKey,
string? filePath,
ParseOptions options,
HostLanguageServices languageServices,
PreservationMode mode,
TextAndVersion textAndVersion,
CancellationToken cancellationToken)
{
var text = textAndVersion.Text;
var treeFactory = languageServices.GetRequiredService<ISyntaxTreeFactoryService>();
var tree = treeFactory.ParseSyntaxTree(filePath, options, text, cancellationToken);
var root = tree.GetRoot(cancellationToken);
if (mode == PreservationMode.PreserveValue && treeFactory.CanCreateRecoverableTree(root))
{
tree = treeFactory.CreateRecoverableTree(cacheKey, tree.FilePath, tree.Options, newTextSource, text.Encoding, root);
}
Contract.ThrowIfNull(tree);
CheckTree(tree, text);
// text version for this document should be unique. use it as a starting point.
return TreeAndVersion.Create(tree, textAndVersion.Version);
}
private static ValueSource<TreeAndVersion> CreateLazyIncrementallyParsedTree(
ValueSource<TreeAndVersion> oldTreeSource,
ValueSource<TextAndVersion> newTextSource)
{
return new AsyncLazy<TreeAndVersion>(
c => IncrementallyParseTreeAsync(oldTreeSource, newTextSource, c),
c => IncrementallyParseTree(oldTreeSource, newTextSource, c),
cacheResult: true);
}
private static async Task<TreeAndVersion> IncrementallyParseTreeAsync(
ValueSource<TreeAndVersion> oldTreeSource,
ValueSource<TextAndVersion> newTextSource,
CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.Workspace_Document_State_IncrementallyParseSyntaxTree, cancellationToken))
{
var newTextAndVersion = await newTextSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
var oldTreeAndVersion = await oldTreeSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
return IncrementallyParse(newTextAndVersion, oldTreeAndVersion, cancellationToken);
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static TreeAndVersion IncrementallyParseTree(
ValueSource<TreeAndVersion> oldTreeSource,
ValueSource<TextAndVersion> newTextSource,
CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.Workspace_Document_State_IncrementallyParseSyntaxTree, cancellationToken))
{
var newTextAndVersion = newTextSource.GetValue(cancellationToken);
var oldTreeAndVersion = oldTreeSource.GetValue(cancellationToken);
return IncrementallyParse(newTextAndVersion, oldTreeAndVersion, cancellationToken);
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static TreeAndVersion IncrementallyParse(
TextAndVersion newTextAndVersion,
TreeAndVersion oldTreeAndVersion,
CancellationToken cancellationToken)
{
var newText = newTextAndVersion.Text;
var oldTree = oldTreeAndVersion.Tree;
var oldText = oldTree.GetText(cancellationToken);
var newTree = oldTree.WithChangedText(newText);
Contract.ThrowIfNull(newTree);
CheckTree(newTree, newText, oldTree, oldText);
return MakeNewTreeAndVersion(oldTree, oldText, oldTreeAndVersion.Version, newTree, newText, newTextAndVersion.Version);
}
private static TreeAndVersion MakeNewTreeAndVersion(SyntaxTree oldTree, SourceText oldText, VersionStamp oldVersion, SyntaxTree newTree, SourceText newText, VersionStamp newVersion)
{
var topLevelChanged = TopLevelChanged(oldTree, oldText, newTree, newText);
var version = topLevelChanged ? newVersion : oldVersion;
return TreeAndVersion.Create(newTree, version);
}
private const int MaxTextChangeRangeLength = 1024 * 4;
private static bool TopLevelChanged(SyntaxTree oldTree, SourceText oldText, SyntaxTree newTree, SourceText newText)
{
// ** currently, it doesn't do any text based quick check. we can add them later if current logic is not performant enough for typing case.
var change = newText.GetEncompassingTextChangeRange(oldText);
if (change == default)
{
// nothing has changed
return false;
}
// if texts are small enough, just use the equivalent to find out whether there was top level edits
if (oldText.Length < MaxTextChangeRangeLength && newText.Length < MaxTextChangeRangeLength)
{
var topLevel = !newTree.IsEquivalentTo(oldTree, topLevel: true);
return topLevel;
}
// okay, text is not small and whole text is changed, then we always treat it as top level edit
if (change.NewLength == newText.Length)
{
return true;
}
// if changes are small enough, we use IsEquivalentTo to find out whether there was a top level edit
if (change.Span.Length < MaxTextChangeRangeLength && change.NewLength < MaxTextChangeRangeLength)
{
var topLevel = !newTree.IsEquivalentTo(oldTree, topLevel: true);
return topLevel;
}
// otherwise, we always consider top level change
return true;
}
public bool HasContentChanged(DocumentState oldState)
{
return oldState._treeSource != _treeSource
|| HasTextChanged(oldState, ignoreUnchangeableDocument: false);
}
[Obsolete("Use TextDocumentState.HasTextChanged")]
public bool HasTextChanged(DocumentState oldState)
=> HasTextChanged(oldState, ignoreUnchangeableDocument: false);
public DocumentState UpdateParseOptions(ParseOptions options)
{
var originalSourceKind = this.SourceCodeKind;
var newState = this.SetParseOptions(options);
if (newState.SourceCodeKind != originalSourceKind)
{
newState = newState.UpdateSourceCodeKind(originalSourceKind);
}
return newState;
}
private DocumentState SetParseOptions(ParseOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (!SupportsSyntaxTree)
{
throw new InvalidOperationException();
}
var newTreeSource = CreateLazyFullyParsedTree(
TextAndVersionSource,
Id.ProjectId,
GetSyntaxTreeFilePath(Attributes),
options,
_languageServices);
return new DocumentState(
LanguageServices,
solutionServices,
Services,
Attributes.With(sourceCodeKind: options.Kind),
options,
sourceText,
TextAndVersionSource,
newTreeSource);
}
public DocumentState UpdateSourceCodeKind(SourceCodeKind kind)
{
if (this.ParseOptions == null || kind == this.SourceCodeKind)
{
return this;
}
return this.SetParseOptions(this.ParseOptions.WithKind(kind));
}
// TODO: https://github.com/dotnet/roslyn/issues/37125
// if FilePath is null, then this will change the name of the underlying tree, but we aren't producing a new tree in that case.
public DocumentState UpdateName(string name)
=> UpdateAttributes(Attributes.With(name: name));
public DocumentState UpdateFolders(IReadOnlyList<string> folders)
=> UpdateAttributes(Attributes.With(folders: folders));
private DocumentState UpdateAttributes(DocumentInfo.DocumentAttributes attributes)
{
Debug.Assert(attributes != Attributes);
return new DocumentState(
_languageServices,
solutionServices,
Services,
attributes,
_options,
sourceText,
TextAndVersionSource,
_treeSource);
}
public DocumentState UpdateFilePath(string? filePath)
{
var newAttributes = Attributes.With(filePath: filePath);
Debug.Assert(newAttributes != Attributes);
// TODO: it's overkill to fully reparse the tree if we had the tree already; all we have to do is update the
// file path and diagnostic options for that tree.
var newTreeSource = SupportsSyntaxTree ?
CreateLazyFullyParsedTree(
TextAndVersionSource,
Id.ProjectId,
GetSyntaxTreeFilePath(newAttributes),
_options!,
_languageServices) : null;
return new DocumentState(
_languageServices,
solutionServices,
Services,
newAttributes,
_options,
sourceText,
TextAndVersionSource,
newTreeSource);
}
public new DocumentState UpdateText(SourceText newText, PreservationMode mode)
=> (DocumentState)base.UpdateText(newText, mode);
public new DocumentState UpdateText(TextAndVersion newTextAndVersion, PreservationMode mode)
=> (DocumentState)base.UpdateText(newTextAndVersion, mode);
protected override TextDocumentState UpdateText(ValueSource<TextAndVersion> newTextSource, PreservationMode mode, bool incremental)
{
ValueSource<TreeAndVersion>? newTreeSource;
if (_treeSource == null)
{
newTreeSource = null;
}
else if (incremental)
{
newTreeSource = CreateLazyIncrementallyParsedTree(_treeSource, newTextSource);
}
else
{
newTreeSource = CreateLazyFullyParsedTree(
newTextSource,
Id.ProjectId,
GetSyntaxTreeFilePath(Attributes),
_options!,
_languageServices,
mode); // TODO: understand why the mode is given here. If we're preserving text by identity, why also preserve the tree?
}
return new DocumentState(
LanguageServices,
solutionServices,
Services,
Attributes,
_options,
sourceText: null,
textSource: newTextSource,
treeSource: newTreeSource);
}
internal DocumentState UpdateText(TextLoader loader, SourceText? text, PreservationMode mode)
{
var documentState = (DocumentState)UpdateText(loader, mode);
// If we are given a SourceText directly, fork it since we didn't pass that into the base.
// TODO: understand why this is being called this way at all. It seems we only have a text in a specific case
// when we are opening a file, when it seems this could have just called the other overload that took a
// TextAndVersion that could have just pinned the object directly.
if (text == null)
{
return documentState;
}
return new DocumentState(
LanguageServices,
solutionServices,
Services,
Attributes,
_options,
sourceText: text,
textSource: documentState.TextAndVersionSource,
treeSource: documentState._treeSource);
}
internal DocumentState UpdateTree(SyntaxNode newRoot, PreservationMode mode)
{
if (!SupportsSyntaxTree)
{
throw new InvalidOperationException();
}
var newTextVersion = GetNewerVersion();
var newTreeVersion = GetNewTreeVersionForUpdatedTree(newRoot, newTextVersion, mode);
// determine encoding
Encoding? encoding;
if (TryGetSyntaxTree(out var priorTree))
{
// this is most likely available since UpdateTree is normally called after modifying the existing tree.
encoding = priorTree.Encoding;
}
else if (TryGetText(out var priorText))
{
encoding = priorText.Encoding;
}
else
{
// the existing encoding was never observed so is unknown.
encoding = null;
}
var syntaxTreeFactory = _languageServices.GetRequiredService<ISyntaxTreeFactoryService>();
var filePath = GetSyntaxTreeFilePath(Attributes);
Contract.ThrowIfNull(_options);
var (text, tree) = CreateRecoverableTextAndTree(newRoot, filePath, newTextVersion, newTreeVersion, encoding, Attributes, _options, syntaxTreeFactory, mode);
return new DocumentState(
LanguageServices,
solutionServices,
Services,
Attributes,
_options,
sourceText: null,
textSource: text,
treeSource: new ConstantValueSource<TreeAndVersion>(tree));
}
private VersionStamp GetNewTreeVersionForUpdatedTree(SyntaxNode newRoot, VersionStamp newTextVersion, PreservationMode mode)
{
RoslynDebug.Assert(_treeSource != null);
if (mode != PreservationMode.PreserveIdentity)
{
return newTextVersion;
}
if (!_treeSource.TryGetValue(out var oldTreeAndVersion) || !oldTreeAndVersion!.Tree.TryGetRoot(out var oldRoot))
{
return newTextVersion;
}
return oldRoot.IsEquivalentTo(newRoot, topLevel: true) ? oldTreeAndVersion.Version : newTextVersion;
}
// use static method so we don't capture references to this
private static (ValueSource<TextAndVersion>, TreeAndVersion) CreateRecoverableTextAndTree(
SyntaxNode newRoot,
string filePath,
VersionStamp textVersion,
VersionStamp treeVersion,
Encoding? encoding,
DocumentInfo.DocumentAttributes attributes,
ParseOptions options,
ISyntaxTreeFactoryService factory,
PreservationMode mode)
{
SyntaxTree tree;
ValueSource<TextAndVersion> lazyTextAndVersion;
if (mode == PreservationMode.PreserveIdentity || !factory.CanCreateRecoverableTree(newRoot))
{
tree = factory.CreateSyntaxTree(filePath, options, encoding, newRoot);
// its okay to use a strong cached AsyncLazy here because the compiler layer SyntaxTree will also keep the text alive once its built.
lazyTextAndVersion = new TreeTextSource(
new AsyncLazy<SourceText>(
c => tree.GetTextAsync(c),
c => tree.GetText(c),
cacheResult: true),
textVersion,
filePath);
}
else
{
// There is a strange circularity here: the creation of lazyTextAndVersion reads this local, but will see it as non-null since it
// only uses it through a lambda that won't have ran. The assignment exists to placate the definite-assignment analysis (which is
// right to be suspicious of this).
tree = null!;
// Uses CachedWeakValueSource so the document and tree will return the same SourceText instance across multiple accesses as long
// as the text is referenced elsewhere.
lazyTextAndVersion = new TreeTextSource(
new WeaklyCachedValueSource<SourceText>(
new AsyncLazy<SourceText>(
// Build text from root, so recoverable tree won't cycle.
async cancellationToken => (await tree.GetRootAsync(cancellationToken).ConfigureAwait(false)).GetText(encoding),
cancellationToken => tree.GetRoot(cancellationToken).GetText(encoding),
cacheResult: false)),
textVersion,
filePath);
tree = factory.CreateRecoverableTree(attributes.Id.ProjectId, filePath, options, lazyTextAndVersion, encoding, newRoot);
}
return (lazyTextAndVersion, TreeAndVersion.Create(tree, treeVersion));
}
internal override Task<Diagnostic?> GetLoadDiagnosticAsync(CancellationToken cancellationToken)
{
if (TextAndVersionSource is TreeTextSource)
{
return SpecializedTasks.Null<Diagnostic>();
}
return base.GetLoadDiagnosticAsync(cancellationToken);
}
private VersionStamp GetNewerVersion()
{
if (TextAndVersionSource.TryGetValue(out var textAndVersion))
{
return textAndVersion!.Version.GetNewerVersion();
}
if (_treeSource != null && _treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
return treeAndVersion.Version.GetNewerVersion();
}
return VersionStamp.Create();
}
public bool TryGetSyntaxTree([NotNullWhen(returnValue: true)] out SyntaxTree? syntaxTree)
{
syntaxTree = null;
if (_treeSource != null && _treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
syntaxTree = treeAndVersion.Tree;
BindSyntaxTreeToId(syntaxTree, Id);
return true;
}
return false;
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
public async ValueTask<SyntaxTree> GetSyntaxTreeAsync(CancellationToken cancellationToken)
{
// operation should only be performed on documents that support syntax trees
RoslynDebug.Assert(_treeSource != null);
var treeAndVersion = await _treeSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
// make sure there is an association between this tree and this doc id before handing it out
BindSyntaxTreeToId(treeAndVersion.Tree, this.Id);
return treeAndVersion.Tree;
}
internal SyntaxTree GetSyntaxTree(CancellationToken cancellationToken)
{
// operation should only be performed on documents that support syntax trees
RoslynDebug.Assert(_treeSource != null);
var treeAndVersion = _treeSource.GetValue(cancellationToken);
// make sure there is an association between this tree and this doc id before handing it out
BindSyntaxTreeToId(treeAndVersion.Tree, this.Id);
return treeAndVersion.Tree;
}
public bool TryGetTopLevelChangeTextVersion(out VersionStamp version)
{
if (_treeSource != null && _treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
version = treeAndVersion.Version;
return true;
}
else
{
version = default;
return false;
}
}
public override async Task<VersionStamp> GetTopLevelChangeTextVersionAsync(CancellationToken cancellationToken)
{
if (_treeSource == null)
{
return await GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
}
if (_treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
return treeAndVersion.Version;
}
treeAndVersion = await _treeSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
return treeAndVersion.Version;
}
private static void BindSyntaxTreeToId(SyntaxTree tree, DocumentId id)
{
if (!s_syntaxTreeToIdMap.TryGetValue(tree, out var existingId))
{
// Avoid closing over parameter 'id' on the method's fast path
var localId = id;
existingId = s_syntaxTreeToIdMap.GetValue(tree, t => localId);
}
Contract.ThrowIfFalse(existingId == id);
}
public static DocumentId? GetDocumentIdForTree(SyntaxTree tree)
{
s_syntaxTreeToIdMap.TryGetValue(tree, out var id);
return id;
}
private static void CheckTree(
SyntaxTree newTree,
SourceText newText,
SyntaxTree? oldTree = null,
SourceText? oldText = null)
{
// this should be always true
if (newTree.Length == newText.Length)
{
return;
}
var newTreeContent = newTree.GetRoot().ToFullString();
var newTextContent = newText.ToString();
var oldTreeContent = oldTree?.GetRoot().ToFullString();
var oldTextContent = oldText?.ToString();
// we time to time see (incremental) parsing bug where text <-> tree round tripping is broken.
// send NFW for those cases
FatalError.ReportAndCatch(new Exception($"tree and text has different length {newTree.Length} vs {newText.Length}"));
// this will make sure that these variables are not thrown away in the dump
GC.KeepAlive(newTreeContent);
GC.KeepAlive(newTextContent);
GC.KeepAlive(oldTreeContent);
GC.KeepAlive(oldTextContent);
GC.KeepAlive(newTree);
GC.KeepAlive(newText);
GC.KeepAlive(oldTree);
GC.KeepAlive(oldText);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial class DocumentState : TextDocumentState
{
private static readonly Func<string?, PreservationMode, string> s_fullParseLog = (path, mode) => $"{path} : {mode}";
private static readonly ConditionalWeakTable<SyntaxTree, DocumentId> s_syntaxTreeToIdMap =
new();
private readonly HostLanguageServices _languageServices;
private readonly ParseOptions? _options;
// null if the document doesn't support syntax trees:
private readonly ValueSource<TreeAndVersion>? _treeSource;
protected DocumentState(
HostLanguageServices languageServices,
SolutionServices solutionServices,
IDocumentServiceProvider? documentServiceProvider,
DocumentInfo.DocumentAttributes attributes,
ParseOptions? options,
SourceText? sourceText,
ValueSource<TextAndVersion> textSource,
ValueSource<TreeAndVersion>? treeSource)
: base(solutionServices, documentServiceProvider, attributes, sourceText, textSource)
{
_languageServices = languageServices;
_options = options;
_treeSource = treeSource;
}
public DocumentState(
DocumentInfo info,
ParseOptions? options,
HostLanguageServices languageServices,
SolutionServices services)
: base(info, services)
{
_languageServices = languageServices;
_options = options;
// If this is document that doesn't support syntax, then don't even bother holding
// onto any tree source. It will never be used to get a tree, and can only hurt us
// by possibly holding onto data that might cause a slow memory leak.
if (languageServices.SyntaxTreeFactory == null)
{
_treeSource = null;
}
else
{
Contract.ThrowIfNull(options);
_treeSource = CreateLazyFullyParsedTree(
base.TextAndVersionSource,
info.Id.ProjectId,
GetSyntaxTreeFilePath(info.Attributes),
options,
languageServices);
}
}
internal bool SupportsSyntaxTree
=> _treeSource != null;
public HostLanguageServices LanguageServices
=> _languageServices;
public ParseOptions? ParseOptions
=> _options;
public SourceCodeKind SourceCodeKind
=> ParseOptions == null ? Attributes.SourceCodeKind : ParseOptions.Kind;
public bool IsGenerated
=> Attributes.IsGenerated;
// This is the string used to represent the FilePath property on a SyntaxTree object.
// if the document does not yet have a file path, use the document's name instead in regular code
// or an empty string in script code.
private static string GetSyntaxTreeFilePath(DocumentInfo.DocumentAttributes info)
{
if (info.FilePath != null)
{
return info.FilePath;
}
return info.SourceCodeKind == SourceCodeKind.Regular
? info.Name
: "";
}
protected static ValueSource<TreeAndVersion> CreateLazyFullyParsedTree(
ValueSource<TextAndVersion> newTextSource,
ProjectId cacheKey,
string? filePath,
ParseOptions options,
HostLanguageServices languageServices,
PreservationMode mode = PreservationMode.PreserveValue)
{
return new AsyncLazy<TreeAndVersion>(
c => FullyParseTreeAsync(newTextSource, cacheKey, filePath, options, languageServices, mode, c),
c => FullyParseTree(newTextSource, cacheKey, filePath, options, languageServices, mode, c),
cacheResult: true);
}
private static async Task<TreeAndVersion> FullyParseTreeAsync(
ValueSource<TextAndVersion> newTextSource,
ProjectId cacheKey,
string? filePath,
ParseOptions options,
HostLanguageServices languageServices,
PreservationMode mode,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Workspace_Document_State_FullyParseSyntaxTree, s_fullParseLog, filePath, mode, cancellationToken))
{
var textAndVersion = await newTextSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
return CreateTreeAndVersion(newTextSource, cacheKey, filePath, options, languageServices, mode, textAndVersion, cancellationToken);
}
}
private static TreeAndVersion FullyParseTree(
ValueSource<TextAndVersion> newTextSource,
ProjectId cacheKey,
string? filePath,
ParseOptions options,
HostLanguageServices languageServices,
PreservationMode mode,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Workspace_Document_State_FullyParseSyntaxTree, s_fullParseLog, filePath, mode, cancellationToken))
{
var textAndVersion = newTextSource.GetValue(cancellationToken);
return CreateTreeAndVersion(newTextSource, cacheKey, filePath, options, languageServices, mode, textAndVersion, cancellationToken);
}
}
private static TreeAndVersion CreateTreeAndVersion(
ValueSource<TextAndVersion> newTextSource,
ProjectId cacheKey,
string? filePath,
ParseOptions options,
HostLanguageServices languageServices,
PreservationMode mode,
TextAndVersion textAndVersion,
CancellationToken cancellationToken)
{
var text = textAndVersion.Text;
var treeFactory = languageServices.GetRequiredService<ISyntaxTreeFactoryService>();
var tree = treeFactory.ParseSyntaxTree(filePath, options, text, cancellationToken);
var root = tree.GetRoot(cancellationToken);
if (mode == PreservationMode.PreserveValue && treeFactory.CanCreateRecoverableTree(root))
{
tree = treeFactory.CreateRecoverableTree(cacheKey, tree.FilePath, tree.Options, newTextSource, text.Encoding, root);
}
Contract.ThrowIfNull(tree);
CheckTree(tree, text);
// text version for this document should be unique. use it as a starting point.
return TreeAndVersion.Create(tree, textAndVersion.Version);
}
private static ValueSource<TreeAndVersion> CreateLazyIncrementallyParsedTree(
ValueSource<TreeAndVersion> oldTreeSource,
ValueSource<TextAndVersion> newTextSource)
{
return new AsyncLazy<TreeAndVersion>(
c => IncrementallyParseTreeAsync(oldTreeSource, newTextSource, c),
c => IncrementallyParseTree(oldTreeSource, newTextSource, c),
cacheResult: true);
}
private static async Task<TreeAndVersion> IncrementallyParseTreeAsync(
ValueSource<TreeAndVersion> oldTreeSource,
ValueSource<TextAndVersion> newTextSource,
CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.Workspace_Document_State_IncrementallyParseSyntaxTree, cancellationToken))
{
var newTextAndVersion = await newTextSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
var oldTreeAndVersion = await oldTreeSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
return IncrementallyParse(newTextAndVersion, oldTreeAndVersion, cancellationToken);
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static TreeAndVersion IncrementallyParseTree(
ValueSource<TreeAndVersion> oldTreeSource,
ValueSource<TextAndVersion> newTextSource,
CancellationToken cancellationToken)
{
try
{
using (Logger.LogBlock(FunctionId.Workspace_Document_State_IncrementallyParseSyntaxTree, cancellationToken))
{
var newTextAndVersion = newTextSource.GetValue(cancellationToken);
var oldTreeAndVersion = oldTreeSource.GetValue(cancellationToken);
return IncrementallyParse(newTextAndVersion, oldTreeAndVersion, cancellationToken);
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static TreeAndVersion IncrementallyParse(
TextAndVersion newTextAndVersion,
TreeAndVersion oldTreeAndVersion,
CancellationToken cancellationToken)
{
var newText = newTextAndVersion.Text;
var oldTree = oldTreeAndVersion.Tree;
var oldText = oldTree.GetText(cancellationToken);
var newTree = oldTree.WithChangedText(newText);
Contract.ThrowIfNull(newTree);
CheckTree(newTree, newText, oldTree, oldText);
return MakeNewTreeAndVersion(oldTree, oldText, oldTreeAndVersion.Version, newTree, newText, newTextAndVersion.Version);
}
private static TreeAndVersion MakeNewTreeAndVersion(SyntaxTree oldTree, SourceText oldText, VersionStamp oldVersion, SyntaxTree newTree, SourceText newText, VersionStamp newVersion)
{
var topLevelChanged = TopLevelChanged(oldTree, oldText, newTree, newText);
var version = topLevelChanged ? newVersion : oldVersion;
return TreeAndVersion.Create(newTree, version);
}
private const int MaxTextChangeRangeLength = 1024 * 4;
private static bool TopLevelChanged(SyntaxTree oldTree, SourceText oldText, SyntaxTree newTree, SourceText newText)
{
// ** currently, it doesn't do any text based quick check. we can add them later if current logic is not performant enough for typing case.
var change = newText.GetEncompassingTextChangeRange(oldText);
if (change == default)
{
// nothing has changed
return false;
}
// if texts are small enough, just use the equivalent to find out whether there was top level edits
if (oldText.Length < MaxTextChangeRangeLength && newText.Length < MaxTextChangeRangeLength)
{
var topLevel = !newTree.IsEquivalentTo(oldTree, topLevel: true);
return topLevel;
}
// okay, text is not small and whole text is changed, then we always treat it as top level edit
if (change.NewLength == newText.Length)
{
return true;
}
// if changes are small enough, we use IsEquivalentTo to find out whether there was a top level edit
if (change.Span.Length < MaxTextChangeRangeLength && change.NewLength < MaxTextChangeRangeLength)
{
var topLevel = !newTree.IsEquivalentTo(oldTree, topLevel: true);
return topLevel;
}
// otherwise, we always consider top level change
return true;
}
public bool HasContentChanged(DocumentState oldState)
{
return oldState._treeSource != _treeSource
|| HasTextChanged(oldState, ignoreUnchangeableDocument: false);
}
[Obsolete("Use TextDocumentState.HasTextChanged")]
public bool HasTextChanged(DocumentState oldState)
=> HasTextChanged(oldState, ignoreUnchangeableDocument: false);
public DocumentState UpdateParseOptions(ParseOptions options)
{
var originalSourceKind = this.SourceCodeKind;
var newState = this.SetParseOptions(options);
if (newState.SourceCodeKind != originalSourceKind)
{
newState = newState.UpdateSourceCodeKind(originalSourceKind);
}
return newState;
}
private DocumentState SetParseOptions(ParseOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (!SupportsSyntaxTree)
{
throw new InvalidOperationException();
}
var newTreeSource = CreateLazyFullyParsedTree(
TextAndVersionSource,
Id.ProjectId,
GetSyntaxTreeFilePath(Attributes),
options,
_languageServices);
return new DocumentState(
LanguageServices,
solutionServices,
Services,
Attributes.With(sourceCodeKind: options.Kind),
options,
sourceText,
TextAndVersionSource,
newTreeSource);
}
public DocumentState UpdateSourceCodeKind(SourceCodeKind kind)
{
if (this.ParseOptions == null || kind == this.SourceCodeKind)
{
return this;
}
return this.SetParseOptions(this.ParseOptions.WithKind(kind));
}
// TODO: https://github.com/dotnet/roslyn/issues/37125
// if FilePath is null, then this will change the name of the underlying tree, but we aren't producing a new tree in that case.
public DocumentState UpdateName(string name)
=> UpdateAttributes(Attributes.With(name: name));
public DocumentState UpdateFolders(IReadOnlyList<string> folders)
=> UpdateAttributes(Attributes.With(folders: folders));
private DocumentState UpdateAttributes(DocumentInfo.DocumentAttributes attributes)
{
Debug.Assert(attributes != Attributes);
return new DocumentState(
_languageServices,
solutionServices,
Services,
attributes,
_options,
sourceText,
TextAndVersionSource,
_treeSource);
}
public DocumentState UpdateFilePath(string? filePath)
{
var newAttributes = Attributes.With(filePath: filePath);
Debug.Assert(newAttributes != Attributes);
// TODO: it's overkill to fully reparse the tree if we had the tree already; all we have to do is update the
// file path and diagnostic options for that tree.
var newTreeSource = SupportsSyntaxTree ?
CreateLazyFullyParsedTree(
TextAndVersionSource,
Id.ProjectId,
GetSyntaxTreeFilePath(newAttributes),
_options!,
_languageServices) : null;
return new DocumentState(
_languageServices,
solutionServices,
Services,
newAttributes,
_options,
sourceText,
TextAndVersionSource,
newTreeSource);
}
public new DocumentState UpdateText(SourceText newText, PreservationMode mode)
=> (DocumentState)base.UpdateText(newText, mode);
public new DocumentState UpdateText(TextAndVersion newTextAndVersion, PreservationMode mode)
=> (DocumentState)base.UpdateText(newTextAndVersion, mode);
protected override TextDocumentState UpdateText(ValueSource<TextAndVersion> newTextSource, PreservationMode mode, bool incremental)
{
ValueSource<TreeAndVersion>? newTreeSource;
if (_treeSource == null)
{
newTreeSource = null;
}
else if (incremental)
{
newTreeSource = CreateLazyIncrementallyParsedTree(_treeSource, newTextSource);
}
else
{
newTreeSource = CreateLazyFullyParsedTree(
newTextSource,
Id.ProjectId,
GetSyntaxTreeFilePath(Attributes),
_options!,
_languageServices,
mode); // TODO: understand why the mode is given here. If we're preserving text by identity, why also preserve the tree?
}
return new DocumentState(
LanguageServices,
solutionServices,
Services,
Attributes,
_options,
sourceText: null,
textSource: newTextSource,
treeSource: newTreeSource);
}
internal DocumentState UpdateText(TextLoader loader, SourceText? text, PreservationMode mode)
{
var documentState = (DocumentState)UpdateText(loader, mode);
// If we are given a SourceText directly, fork it since we didn't pass that into the base.
// TODO: understand why this is being called this way at all. It seems we only have a text in a specific case
// when we are opening a file, when it seems this could have just called the other overload that took a
// TextAndVersion that could have just pinned the object directly.
if (text == null)
{
return documentState;
}
return new DocumentState(
LanguageServices,
solutionServices,
Services,
Attributes,
_options,
sourceText: text,
textSource: documentState.TextAndVersionSource,
treeSource: documentState._treeSource);
}
internal DocumentState UpdateTree(SyntaxNode newRoot, PreservationMode mode)
{
if (!SupportsSyntaxTree)
{
throw new InvalidOperationException();
}
var newTextVersion = GetNewerVersion();
var newTreeVersion = GetNewTreeVersionForUpdatedTree(newRoot, newTextVersion, mode);
// determine encoding
Encoding? encoding;
if (TryGetSyntaxTree(out var priorTree))
{
// this is most likely available since UpdateTree is normally called after modifying the existing tree.
encoding = priorTree.Encoding;
}
else if (TryGetText(out var priorText))
{
encoding = priorText.Encoding;
}
else
{
// the existing encoding was never observed so is unknown.
encoding = null;
}
var syntaxTreeFactory = _languageServices.GetRequiredService<ISyntaxTreeFactoryService>();
var filePath = GetSyntaxTreeFilePath(Attributes);
Contract.ThrowIfNull(_options);
var (text, tree) = CreateRecoverableTextAndTree(newRoot, filePath, newTextVersion, newTreeVersion, encoding, Attributes, _options, syntaxTreeFactory, mode);
return new DocumentState(
LanguageServices,
solutionServices,
Services,
Attributes,
_options,
sourceText: null,
textSource: text,
treeSource: new ConstantValueSource<TreeAndVersion>(tree));
}
private VersionStamp GetNewTreeVersionForUpdatedTree(SyntaxNode newRoot, VersionStamp newTextVersion, PreservationMode mode)
{
RoslynDebug.Assert(_treeSource != null);
if (mode != PreservationMode.PreserveIdentity)
{
return newTextVersion;
}
if (!_treeSource.TryGetValue(out var oldTreeAndVersion) || !oldTreeAndVersion!.Tree.TryGetRoot(out var oldRoot))
{
return newTextVersion;
}
return oldRoot.IsEquivalentTo(newRoot, topLevel: true) ? oldTreeAndVersion.Version : newTextVersion;
}
// use static method so we don't capture references to this
private static (ValueSource<TextAndVersion>, TreeAndVersion) CreateRecoverableTextAndTree(
SyntaxNode newRoot,
string filePath,
VersionStamp textVersion,
VersionStamp treeVersion,
Encoding? encoding,
DocumentInfo.DocumentAttributes attributes,
ParseOptions options,
ISyntaxTreeFactoryService factory,
PreservationMode mode)
{
SyntaxTree tree;
ValueSource<TextAndVersion> lazyTextAndVersion;
if (mode == PreservationMode.PreserveIdentity || !factory.CanCreateRecoverableTree(newRoot))
{
tree = factory.CreateSyntaxTree(filePath, options, encoding, newRoot);
// its okay to use a strong cached AsyncLazy here because the compiler layer SyntaxTree will also keep the text alive once its built.
lazyTextAndVersion = new TreeTextSource(
new AsyncLazy<SourceText>(
c => tree.GetTextAsync(c),
c => tree.GetText(c),
cacheResult: true),
textVersion,
filePath);
}
else
{
// There is a strange circularity here: the creation of lazyTextAndVersion reads this local, but will see it as non-null since it
// only uses it through a lambda that won't have ran. The assignment exists to placate the definite-assignment analysis (which is
// right to be suspicious of this).
tree = null!;
// Uses CachedWeakValueSource so the document and tree will return the same SourceText instance across multiple accesses as long
// as the text is referenced elsewhere.
lazyTextAndVersion = new TreeTextSource(
new WeaklyCachedValueSource<SourceText>(
new AsyncLazy<SourceText>(
// Build text from root, so recoverable tree won't cycle.
async cancellationToken => (await tree.GetRootAsync(cancellationToken).ConfigureAwait(false)).GetText(encoding),
cancellationToken => tree.GetRoot(cancellationToken).GetText(encoding),
cacheResult: false)),
textVersion,
filePath);
tree = factory.CreateRecoverableTree(attributes.Id.ProjectId, filePath, options, lazyTextAndVersion, encoding, newRoot);
}
return (lazyTextAndVersion, TreeAndVersion.Create(tree, treeVersion));
}
internal override Task<Diagnostic?> GetLoadDiagnosticAsync(CancellationToken cancellationToken)
{
if (TextAndVersionSource is TreeTextSource)
{
return SpecializedTasks.Null<Diagnostic>();
}
return base.GetLoadDiagnosticAsync(cancellationToken);
}
private VersionStamp GetNewerVersion()
{
if (TextAndVersionSource.TryGetValue(out var textAndVersion))
{
return textAndVersion!.Version.GetNewerVersion();
}
if (_treeSource != null && _treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
return treeAndVersion.Version.GetNewerVersion();
}
return VersionStamp.Create();
}
public bool TryGetSyntaxTree([NotNullWhen(returnValue: true)] out SyntaxTree? syntaxTree)
{
syntaxTree = null;
if (_treeSource != null && _treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
syntaxTree = treeAndVersion.Tree;
BindSyntaxTreeToId(syntaxTree, Id);
return true;
}
return false;
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)]
public async ValueTask<SyntaxTree> GetSyntaxTreeAsync(CancellationToken cancellationToken)
{
// operation should only be performed on documents that support syntax trees
RoslynDebug.Assert(_treeSource != null);
var treeAndVersion = await _treeSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
// make sure there is an association between this tree and this doc id before handing it out
BindSyntaxTreeToId(treeAndVersion.Tree, this.Id);
return treeAndVersion.Tree;
}
internal SyntaxTree GetSyntaxTree(CancellationToken cancellationToken)
{
// operation should only be performed on documents that support syntax trees
RoslynDebug.Assert(_treeSource != null);
var treeAndVersion = _treeSource.GetValue(cancellationToken);
// make sure there is an association between this tree and this doc id before handing it out
BindSyntaxTreeToId(treeAndVersion.Tree, this.Id);
return treeAndVersion.Tree;
}
public bool TryGetTopLevelChangeTextVersion(out VersionStamp version)
{
if (_treeSource != null && _treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
version = treeAndVersion.Version;
return true;
}
else
{
version = default;
return false;
}
}
public override async Task<VersionStamp> GetTopLevelChangeTextVersionAsync(CancellationToken cancellationToken)
{
if (_treeSource == null)
{
return await GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
}
if (_treeSource.TryGetValue(out var treeAndVersion) && treeAndVersion != null)
{
return treeAndVersion.Version;
}
treeAndVersion = await _treeSource.GetValueAsync(cancellationToken).ConfigureAwait(false);
return treeAndVersion.Version;
}
private static void BindSyntaxTreeToId(SyntaxTree tree, DocumentId id)
{
if (!s_syntaxTreeToIdMap.TryGetValue(tree, out var existingId))
{
// Avoid closing over parameter 'id' on the method's fast path
var localId = id;
existingId = s_syntaxTreeToIdMap.GetValue(tree, t => localId);
}
Contract.ThrowIfFalse(existingId == id);
}
public static DocumentId? GetDocumentIdForTree(SyntaxTree tree)
{
s_syntaxTreeToIdMap.TryGetValue(tree, out var id);
return id;
}
private static void CheckTree(
SyntaxTree newTree,
SourceText newText,
SyntaxTree? oldTree = null,
SourceText? oldText = null)
{
// this should be always true
if (newTree.Length == newText.Length)
{
return;
}
var newTreeContent = newTree.GetRoot().ToFullString();
var newTextContent = newText.ToString();
var oldTreeContent = oldTree?.GetRoot().ToFullString();
var oldTextContent = oldText?.ToString();
// we time to time see (incremental) parsing bug where text <-> tree round tripping is broken.
// send NFW for those cases
FatalError.ReportAndCatch(new Exception($"tree and text has different length {newTree.Length} vs {newText.Length}"));
// this will make sure that these variables are not thrown away in the dump
GC.KeepAlive(newTreeContent);
GC.KeepAlive(newTextContent);
GC.KeepAlive(oldTreeContent);
GC.KeepAlive(oldTextContent);
GC.KeepAlive(newTree);
GC.KeepAlive(newText);
GC.KeepAlive(oldTree);
GC.KeepAlive(oldText);
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionResult.ExpressionResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpSelectionResult
{
private class ExpressionResult : CSharpSelectionResult
{
public ExpressionResult(
OperationStatus status,
TextSpan originalSpan,
TextSpan finalSpan,
OptionSet options,
bool selectionInExpression,
SemanticDocument document,
SyntaxAnnotation firstTokenAnnotation,
SyntaxAnnotation lastTokenAnnotation)
: base(status, originalSpan, finalSpan, options, selectionInExpression, document, firstTokenAnnotation, lastTokenAnnotation)
{
}
public override bool ContainingScopeHasAsyncKeyword()
=> false;
public override SyntaxNode? GetContainingScope()
{
Contract.ThrowIfNull(SemanticDocument);
Contract.ThrowIfFalse(SelectionInExpression);
var firstToken = GetFirstTokenInSelection();
var lastToken = GetLastTokenInSelection();
var scope = firstToken.GetCommonRoot(lastToken).GetAncestorOrThis<ExpressionSyntax>();
if (scope == null)
return null;
return CSharpSyntaxFacts.Instance.GetRootStandaloneExpression(scope);
}
public override ITypeSymbol? GetContainingScopeType()
{
if (!(GetContainingScope() is ExpressionSyntax node))
{
throw ExceptionUtilities.Unreachable;
}
var model = SemanticDocument.SemanticModel;
// special case for array initializer and explicit cast
if (node.IsArrayInitializer())
{
var variableDeclExpression = node.GetAncestorOrThis<VariableDeclarationSyntax>();
if (variableDeclExpression != null)
{
return model.GetTypeInfo(variableDeclExpression.Type).Type;
}
}
if (node.IsExpressionInCast())
{
// bug # 12774 and # 4780
// if the expression is under cast, we use the heuristic below
// 1. if regular binding returns a meaningful type, we use it as it is
// 2. if it doesn't, even if the cast itself wasn't included in the selection, we will treat it
// as it was in the selection
var regularType = GetRegularExpressionType(model, node);
if (regularType != null)
{
return regularType;
}
if (node.Parent is CastExpressionSyntax castExpression)
{
return model.GetTypeInfo(castExpression).Type;
}
}
return GetRegularExpressionType(model, node);
}
private static ITypeSymbol? GetRegularExpressionType(SemanticModel semanticModel, ExpressionSyntax node)
{
// regular case. always use ConvertedType to get implicit conversion right.
var expression = node.GetUnparenthesizedExpression();
var info = semanticModel.GetTypeInfo(expression);
var conv = semanticModel.GetConversion(expression);
if (info.ConvertedType == null || info.ConvertedType.IsErrorType())
{
// there is no implicit conversion involved. no need to go further
return info.GetTypeWithAnnotatedNullability();
}
// always use converted type if method group
if ((!node.IsKind(SyntaxKind.ObjectCreationExpression) && semanticModel.GetMemberGroup(expression).Length > 0) ||
IsCoClassImplicitConversion(info, conv, semanticModel.Compilation.CoClassType()))
{
return info.GetConvertedTypeWithAnnotatedNullability();
}
// check implicit conversion
if (conv.IsImplicit && (conv.IsConstantExpression || conv.IsEnumeration))
{
return info.GetConvertedTypeWithAnnotatedNullability();
}
// use FormattableString if conversion between String and FormattableString
if (info.Type?.SpecialType == SpecialType.System_String &&
info.ConvertedType?.IsFormattableStringOrIFormattable() == true)
{
return info.GetConvertedTypeWithAnnotatedNullability();
}
// always try to use type that is more specific than object type if possible.
return !info.Type.IsObjectType() ? info.GetTypeWithAnnotatedNullability() : info.GetConvertedTypeWithAnnotatedNullability();
}
}
private static bool IsCoClassImplicitConversion(TypeInfo info, Conversion conversion, ISymbol? coclassSymbol)
{
if (!conversion.IsImplicit ||
info.ConvertedType == null ||
info.ConvertedType.TypeKind != TypeKind.Interface)
{
return false;
}
// let's see whether this interface has coclass attribute
return info.ConvertedType.GetAttributes().Any(c => c.AttributeClass?.Equals(coclassSymbol) == 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpSelectionResult
{
private class ExpressionResult : CSharpSelectionResult
{
public ExpressionResult(
OperationStatus status,
TextSpan originalSpan,
TextSpan finalSpan,
OptionSet options,
bool selectionInExpression,
SemanticDocument document,
SyntaxAnnotation firstTokenAnnotation,
SyntaxAnnotation lastTokenAnnotation)
: base(status, originalSpan, finalSpan, options, selectionInExpression, document, firstTokenAnnotation, lastTokenAnnotation)
{
}
public override bool ContainingScopeHasAsyncKeyword()
=> false;
public override SyntaxNode? GetContainingScope()
{
Contract.ThrowIfNull(SemanticDocument);
Contract.ThrowIfFalse(SelectionInExpression);
var firstToken = GetFirstTokenInSelection();
var lastToken = GetLastTokenInSelection();
var scope = firstToken.GetCommonRoot(lastToken).GetAncestorOrThis<ExpressionSyntax>();
if (scope == null)
return null;
return CSharpSyntaxFacts.Instance.GetRootStandaloneExpression(scope);
}
public override ITypeSymbol? GetContainingScopeType()
{
if (!(GetContainingScope() is ExpressionSyntax node))
{
throw ExceptionUtilities.Unreachable;
}
var model = SemanticDocument.SemanticModel;
// special case for array initializer and explicit cast
if (node.IsArrayInitializer())
{
var variableDeclExpression = node.GetAncestorOrThis<VariableDeclarationSyntax>();
if (variableDeclExpression != null)
{
return model.GetTypeInfo(variableDeclExpression.Type).Type;
}
}
if (node.IsExpressionInCast())
{
// bug # 12774 and # 4780
// if the expression is under cast, we use the heuristic below
// 1. if regular binding returns a meaningful type, we use it as it is
// 2. if it doesn't, even if the cast itself wasn't included in the selection, we will treat it
// as it was in the selection
var regularType = GetRegularExpressionType(model, node);
if (regularType != null)
{
return regularType;
}
if (node.Parent is CastExpressionSyntax castExpression)
{
return model.GetTypeInfo(castExpression).Type;
}
}
return GetRegularExpressionType(model, node);
}
private static ITypeSymbol? GetRegularExpressionType(SemanticModel semanticModel, ExpressionSyntax node)
{
// regular case. always use ConvertedType to get implicit conversion right.
var expression = node.GetUnparenthesizedExpression();
var info = semanticModel.GetTypeInfo(expression);
var conv = semanticModel.GetConversion(expression);
if (info.ConvertedType == null || info.ConvertedType.IsErrorType())
{
// there is no implicit conversion involved. no need to go further
return info.GetTypeWithAnnotatedNullability();
}
// always use converted type if method group
if ((!node.IsKind(SyntaxKind.ObjectCreationExpression) && semanticModel.GetMemberGroup(expression).Length > 0) ||
IsCoClassImplicitConversion(info, conv, semanticModel.Compilation.CoClassType()))
{
return info.GetConvertedTypeWithAnnotatedNullability();
}
// check implicit conversion
if (conv.IsImplicit && (conv.IsConstantExpression || conv.IsEnumeration))
{
return info.GetConvertedTypeWithAnnotatedNullability();
}
// use FormattableString if conversion between String and FormattableString
if (info.Type?.SpecialType == SpecialType.System_String &&
info.ConvertedType?.IsFormattableStringOrIFormattable() == true)
{
return info.GetConvertedTypeWithAnnotatedNullability();
}
// always try to use type that is more specific than object type if possible.
return !info.Type.IsObjectType() ? info.GetTypeWithAnnotatedNullability() : info.GetConvertedTypeWithAnnotatedNullability();
}
}
private static bool IsCoClassImplicitConversion(TypeInfo info, Conversion conversion, ISymbol? coclassSymbol)
{
if (!conversion.IsImplicit ||
info.ConvertedType == null ||
info.ConvertedType.TypeKind != TypeKind.Interface)
{
return false;
}
// let's see whether this interface has coclass attribute
return info.ConvertedType.GetAttributes().Any(c => c.AttributeClass?.Equals(coclassSymbol) == true);
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/CSharpTest2/Recommendations/TheoryDataKeywordsIndicatingLocalFunction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
internal class TheoryDataKeywordsIndicatingLocalFunction : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[] { "extern" };
yield return new object[] { "static extern" };
yield return new object[] { "extern static" };
yield return new object[] { "async" };
yield return new object[] { "static async" };
yield return new object[] { "async static" };
yield return new object[] { "unsafe" };
yield return new object[] { "static unsafe" };
yield return new object[] { "unsafe static" };
yield return new object[] { "async unsafe" };
yield return new object[] { "unsafe async" };
yield return new object[] { "unsafe extern" };
yield return new object[] { "extern unsafe" };
yield return new object[] { "extern unsafe async static" };
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
internal class TheoryDataKeywordsIndicatingLocalFunction : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[] { "extern" };
yield return new object[] { "static extern" };
yield return new object[] { "extern static" };
yield return new object[] { "async" };
yield return new object[] { "static async" };
yield return new object[] { "async static" };
yield return new object[] { "unsafe" };
yield return new object[] { "static unsafe" };
yield return new object[] { "unsafe static" };
yield return new object[] { "async unsafe" };
yield return new object[] { "unsafe async" };
yield return new object[] { "unsafe extern" };
yield return new object[] { "extern unsafe" };
yield return new object[] { "extern unsafe async static" };
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/CSharp/Portable/Symbols/Source/FieldSymbolWithAttributesAndModifiers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal abstract class FieldSymbolWithAttributesAndModifiers : FieldSymbol, IAttributeTargetSymbol
{
private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag;
protected SymbolCompletionState state;
internal abstract Location ErrorLocation { get; }
protected abstract DeclarationModifiers Modifiers { get; }
/// <summary>
/// Gets the syntax list of custom attributes applied on the symbol.
/// </summary>
protected abstract SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList { get; }
protected abstract IAttributeTargetSymbol AttributeOwner { get; }
IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner
=> this.AttributeOwner;
AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation
=> AttributeLocation.Field;
AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations
=> AttributeLocation.Field;
internal sealed override bool HasComplete(CompletionPart part)
=> state.HasComplete(part);
public sealed override bool IsStatic
=> (Modifiers & DeclarationModifiers.Static) != 0;
public sealed override bool IsReadOnly
=> (Modifiers & DeclarationModifiers.ReadOnly) != 0;
public sealed override Accessibility DeclaredAccessibility
=> ModifierUtils.EffectiveAccessibility(Modifiers);
public sealed override bool IsConst
=> (Modifiers & DeclarationModifiers.Const) != 0;
public sealed override bool IsVolatile
=> (Modifiers & DeclarationModifiers.Volatile) != 0;
public sealed override bool IsFixedSizeBuffer
=> (Modifiers & DeclarationModifiers.Fixed) != 0;
/// <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()
=> this.GetAttributesBag().Attributes;
/// <summary>
/// Returns a bag of applied custom attributes and data decoded from well-known attributes.
/// Returns an empty bag if there are no attributes applied on the symbol.
/// </summary>
/// <remarks>
/// Forces binding and decoding of attributes.
/// </remarks>
private CustomAttributesBag<CSharpAttributeData> GetAttributesBag()
{
var bag = _lazyCustomAttributesBag;
if (bag != null && bag.IsSealed)
{
return bag;
}
if (LoadAndValidateAttributes(OneOrMany.Create(this.AttributeDeclarationSyntaxList), ref _lazyCustomAttributesBag))
{
var completed = state.NotePartComplete(CompletionPart.Attributes);
Debug.Assert(completed);
}
Debug.Assert(_lazyCustomAttributesBag.IsSealed);
return _lazyCustomAttributesBag;
}
/// <summary>
/// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes.
/// </summary>
/// <remarks>
/// Forces binding and decoding of attributes.
/// </remarks>
protected FieldWellKnownAttributeData GetDecodedWellKnownAttributeData()
{
var attributesBag = _lazyCustomAttributesBag;
if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed)
{
attributesBag = this.GetAttributesBag();
}
return (FieldWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData;
}
internal sealed override CSharpAttributeData EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments)
{
CSharpAttributeData boundAttribute;
ObsoleteAttributeData obsoleteData;
if (EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref arguments, out boundAttribute, out obsoleteData))
{
if (obsoleteData != null)
{
arguments.GetOrCreateData<CommonFieldEarlyWellKnownAttributeData>().ObsoleteAttributeData = obsoleteData;
}
return boundAttribute;
}
return base.EarlyDecodeWellKnownAttribute(ref arguments);
}
/// <summary>
/// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute.
/// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet.
/// </summary>
internal sealed override ObsoleteAttributeData ObsoleteAttributeData
{
get
{
var containingSourceType = (SourceMemberContainerTypeSymbol)ContainingType;
if (!containingSourceType.AnyMemberHasAttributes)
{
return null;
}
var lazyCustomAttributesBag = _lazyCustomAttributesBag;
if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed)
{
var data = (CommonFieldEarlyWellKnownAttributeData)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData;
return data != null ? data.ObsoleteAttributeData : null;
}
return ObsoleteAttributeData.Uninitialized;
}
}
internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
{
Debug.Assert((object)arguments.AttributeSyntaxOpt != null);
var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics;
var attribute = arguments.Attribute;
Debug.Assert(!attribute.HasErrors);
Debug.Assert(arguments.SymbolPart == AttributeLocation.None);
if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasSpecialNameAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.NonSerializedAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasNonSerializedAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.FieldOffsetAttribute))
{
if (this.IsStatic || this.IsConst)
{
// CS0637: The FieldOffset attribute is not allowed on static or const fields
diagnostics.Add(ErrorCode.ERR_StructOffsetOnBadField, arguments.AttributeSyntaxOpt.Name.Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName());
}
else
{
int offset = attribute.CommonConstructorArguments[0].DecodeValue<int>(SpecialType.System_Int32);
if (offset < 0)
{
// Dev10 reports CS0647: "Error emitting attribute ..."
CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, arguments.AttributeSyntaxOpt);
diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName());
offset = 0;
}
// Set field offset even if the attribute specifies an invalid value, so that
// post-validation knows that the attribute is applied and reports better errors.
arguments.GetOrCreateData<FieldWellKnownAttributeData>().SetFieldOffset(offset);
}
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.MarshalAsAttribute))
{
MarshalAsAttributeDecoder<FieldWellKnownAttributeData, AttributeSyntax, CSharpAttributeData, AttributeLocation>.Decode(ref arguments, AttributeTargets.Field, MessageProvider.Instance);
}
else if (ReportExplicitUseOfReservedAttributes(in arguments,
ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NativeIntegerAttribute))
{
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.DateTimeConstantAttribute))
{
VerifyConstantValueMatches(attribute.DecodeDateTimeConstantValue(), ref arguments);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.DecimalConstantAttribute))
{
VerifyConstantValueMatches(attribute.DecodeDecimalConstantValue(), ref arguments);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.AllowNullAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasAllowNullAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.DisallowNullAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasDisallowNullAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasMaybeNullAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasNotNullAttribute = true;
}
}
public override FlowAnalysisAnnotations FlowAnalysisAnnotations
=> DecodeFlowAnalysisAttributes(GetDecodedWellKnownAttributeData());
private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(FieldWellKnownAttributeData attributeData)
{
var annotations = FlowAnalysisAnnotations.None;
if (attributeData != null)
{
if (attributeData.HasAllowNullAttribute) annotations |= FlowAnalysisAnnotations.AllowNull;
if (attributeData.HasDisallowNullAttribute) annotations |= FlowAnalysisAnnotations.DisallowNull;
if (attributeData.HasMaybeNullAttribute) annotations |= FlowAnalysisAnnotations.MaybeNull;
if (attributeData.HasNotNullAttribute) annotations |= FlowAnalysisAnnotations.NotNull;
}
return annotations;
}
/// <summary>
/// Verify the constant value matches the default value from any earlier attribute
/// (DateTimeConstantAttribute or DecimalConstantAttribute).
/// If not, report ERR_FieldHasMultipleDistinctConstantValues.
/// </summary>
private void VerifyConstantValueMatches(ConstantValue attrValue, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
{
if (!attrValue.IsBad)
{
var data = arguments.GetOrCreateData<FieldWellKnownAttributeData>();
ConstantValue constValue;
var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics;
if (this.IsConst)
{
if (this.Type.SpecialType == SpecialType.System_Decimal)
{
constValue = this.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false);
if ((object)constValue != null && !constValue.IsBad && constValue != attrValue)
{
diagnostics.Add(ErrorCode.ERR_FieldHasMultipleDistinctConstantValues, arguments.AttributeSyntaxOpt.Location);
}
}
else
{
diagnostics.Add(ErrorCode.ERR_FieldHasMultipleDistinctConstantValues, arguments.AttributeSyntaxOpt.Location);
}
if (data.ConstValue == CodeAnalysis.ConstantValue.Unset)
{
data.ConstValue = attrValue;
}
}
else
{
constValue = data.ConstValue;
if (constValue != CodeAnalysis.ConstantValue.Unset)
{
if (constValue != attrValue)
{
diagnostics.Add(ErrorCode.ERR_FieldHasMultipleDistinctConstantValues, arguments.AttributeSyntaxOpt.Location);
}
}
else
{
data.ConstValue = attrValue;
}
}
}
}
internal override void PostDecodeWellKnownAttributes(ImmutableArray<CSharpAttributeData> boundAttributes, ImmutableArray<AttributeSyntax> allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData)
{
Debug.Assert(!boundAttributes.IsDefault);
Debug.Assert(!allAttributeSyntaxNodes.IsDefault);
Debug.Assert(boundAttributes.Length == allAttributeSyntaxNodes.Length);
Debug.Assert(_lazyCustomAttributesBag != null);
Debug.Assert(_lazyCustomAttributesBag.IsDecodedWellKnownAttributeDataComputed);
Debug.Assert(symbolPart == AttributeLocation.None);
var data = (FieldWellKnownAttributeData)decodedData;
int? fieldOffset = data != null ? data.Offset : null;
if (fieldOffset.HasValue)
{
if (this.ContainingType.Layout.Kind != LayoutKind.Explicit)
{
Debug.Assert(boundAttributes.Any());
// error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)
int i = boundAttributes.IndexOfAttribute(this, AttributeDescription.FieldOffsetAttribute);
diagnostics.Add(ErrorCode.ERR_StructOffsetOnBadStruct, allAttributeSyntaxNodes[i].Name.Location);
}
}
else if (!this.IsStatic && !this.IsConst)
{
if (this.ContainingType.Layout.Kind == LayoutKind.Explicit)
{
// error CS0625: '<field>': instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute
diagnostics.Add(ErrorCode.ERR_MissingStructOffset, this.ErrorLocation, this.AttributeOwner);
}
}
base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData);
}
internal sealed override bool HasSpecialName
{
get
{
if (this.HasRuntimeSpecialName)
{
return true;
}
var data = GetDecodedWellKnownAttributeData();
return data != null && data.HasSpecialNameAttribute;
}
}
internal sealed override bool IsNotSerialized
{
get
{
var data = GetDecodedWellKnownAttributeData();
return data != null && data.HasNonSerializedAttribute;
}
}
internal sealed override MarshalPseudoCustomAttributeData MarshallingInformation
{
get
{
var data = GetDecodedWellKnownAttributeData();
return data != null ? data.MarshallingInformation : null;
}
}
internal sealed override int? TypeLayoutOffset
{
get
{
var data = GetDecodedWellKnownAttributeData();
return data != null ? data.Offset : null;
}
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
var compilation = this.DeclaringCompilation;
var type = this.TypeWithAnnotations;
if (type.Type.ContainsDynamic())
{
AddSynthesizedAttribute(ref attributes,
compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length));
}
if (type.Type.ContainsNativeInteger())
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type));
}
if (type.Type.ContainsTupleNames())
{
AddSynthesizedAttribute(ref attributes,
compilation.SynthesizeTupleNamesAttribute(type.Type));
}
if (compilation.ShouldEmitNullableAttributes(this))
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, ContainingType.GetNullableContextValue(), type));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal abstract class FieldSymbolWithAttributesAndModifiers : FieldSymbol, IAttributeTargetSymbol
{
private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag;
protected SymbolCompletionState state;
internal abstract Location ErrorLocation { get; }
protected abstract DeclarationModifiers Modifiers { get; }
/// <summary>
/// Gets the syntax list of custom attributes applied on the symbol.
/// </summary>
protected abstract SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList { get; }
protected abstract IAttributeTargetSymbol AttributeOwner { get; }
IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner
=> this.AttributeOwner;
AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation
=> AttributeLocation.Field;
AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations
=> AttributeLocation.Field;
internal sealed override bool HasComplete(CompletionPart part)
=> state.HasComplete(part);
public sealed override bool IsStatic
=> (Modifiers & DeclarationModifiers.Static) != 0;
public sealed override bool IsReadOnly
=> (Modifiers & DeclarationModifiers.ReadOnly) != 0;
public sealed override Accessibility DeclaredAccessibility
=> ModifierUtils.EffectiveAccessibility(Modifiers);
public sealed override bool IsConst
=> (Modifiers & DeclarationModifiers.Const) != 0;
public sealed override bool IsVolatile
=> (Modifiers & DeclarationModifiers.Volatile) != 0;
public sealed override bool IsFixedSizeBuffer
=> (Modifiers & DeclarationModifiers.Fixed) != 0;
/// <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()
=> this.GetAttributesBag().Attributes;
/// <summary>
/// Returns a bag of applied custom attributes and data decoded from well-known attributes.
/// Returns an empty bag if there are no attributes applied on the symbol.
/// </summary>
/// <remarks>
/// Forces binding and decoding of attributes.
/// </remarks>
private CustomAttributesBag<CSharpAttributeData> GetAttributesBag()
{
var bag = _lazyCustomAttributesBag;
if (bag != null && bag.IsSealed)
{
return bag;
}
if (LoadAndValidateAttributes(OneOrMany.Create(this.AttributeDeclarationSyntaxList), ref _lazyCustomAttributesBag))
{
var completed = state.NotePartComplete(CompletionPart.Attributes);
Debug.Assert(completed);
}
Debug.Assert(_lazyCustomAttributesBag.IsSealed);
return _lazyCustomAttributesBag;
}
/// <summary>
/// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes.
/// </summary>
/// <remarks>
/// Forces binding and decoding of attributes.
/// </remarks>
protected FieldWellKnownAttributeData GetDecodedWellKnownAttributeData()
{
var attributesBag = _lazyCustomAttributesBag;
if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed)
{
attributesBag = this.GetAttributesBag();
}
return (FieldWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData;
}
internal sealed override CSharpAttributeData EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments)
{
CSharpAttributeData boundAttribute;
ObsoleteAttributeData obsoleteData;
if (EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref arguments, out boundAttribute, out obsoleteData))
{
if (obsoleteData != null)
{
arguments.GetOrCreateData<CommonFieldEarlyWellKnownAttributeData>().ObsoleteAttributeData = obsoleteData;
}
return boundAttribute;
}
return base.EarlyDecodeWellKnownAttribute(ref arguments);
}
/// <summary>
/// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute.
/// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet.
/// </summary>
internal sealed override ObsoleteAttributeData ObsoleteAttributeData
{
get
{
var containingSourceType = (SourceMemberContainerTypeSymbol)ContainingType;
if (!containingSourceType.AnyMemberHasAttributes)
{
return null;
}
var lazyCustomAttributesBag = _lazyCustomAttributesBag;
if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed)
{
var data = (CommonFieldEarlyWellKnownAttributeData)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData;
return data != null ? data.ObsoleteAttributeData : null;
}
return ObsoleteAttributeData.Uninitialized;
}
}
internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
{
Debug.Assert((object)arguments.AttributeSyntaxOpt != null);
var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics;
var attribute = arguments.Attribute;
Debug.Assert(!attribute.HasErrors);
Debug.Assert(arguments.SymbolPart == AttributeLocation.None);
if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasSpecialNameAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.NonSerializedAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasNonSerializedAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.FieldOffsetAttribute))
{
if (this.IsStatic || this.IsConst)
{
// CS0637: The FieldOffset attribute is not allowed on static or const fields
diagnostics.Add(ErrorCode.ERR_StructOffsetOnBadField, arguments.AttributeSyntaxOpt.Name.Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName());
}
else
{
int offset = attribute.CommonConstructorArguments[0].DecodeValue<int>(SpecialType.System_Int32);
if (offset < 0)
{
// Dev10 reports CS0647: "Error emitting attribute ..."
CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, arguments.AttributeSyntaxOpt);
diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName());
offset = 0;
}
// Set field offset even if the attribute specifies an invalid value, so that
// post-validation knows that the attribute is applied and reports better errors.
arguments.GetOrCreateData<FieldWellKnownAttributeData>().SetFieldOffset(offset);
}
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.MarshalAsAttribute))
{
MarshalAsAttributeDecoder<FieldWellKnownAttributeData, AttributeSyntax, CSharpAttributeData, AttributeLocation>.Decode(ref arguments, AttributeTargets.Field, MessageProvider.Instance);
}
else if (ReportExplicitUseOfReservedAttributes(in arguments,
ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NativeIntegerAttribute))
{
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.DateTimeConstantAttribute))
{
VerifyConstantValueMatches(attribute.DecodeDateTimeConstantValue(), ref arguments);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.DecimalConstantAttribute))
{
VerifyConstantValueMatches(attribute.DecodeDecimalConstantValue(), ref arguments);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.AllowNullAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasAllowNullAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.DisallowNullAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasDisallowNullAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasMaybeNullAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullAttribute))
{
arguments.GetOrCreateData<FieldWellKnownAttributeData>().HasNotNullAttribute = true;
}
}
public override FlowAnalysisAnnotations FlowAnalysisAnnotations
=> DecodeFlowAnalysisAttributes(GetDecodedWellKnownAttributeData());
private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(FieldWellKnownAttributeData attributeData)
{
var annotations = FlowAnalysisAnnotations.None;
if (attributeData != null)
{
if (attributeData.HasAllowNullAttribute) annotations |= FlowAnalysisAnnotations.AllowNull;
if (attributeData.HasDisallowNullAttribute) annotations |= FlowAnalysisAnnotations.DisallowNull;
if (attributeData.HasMaybeNullAttribute) annotations |= FlowAnalysisAnnotations.MaybeNull;
if (attributeData.HasNotNullAttribute) annotations |= FlowAnalysisAnnotations.NotNull;
}
return annotations;
}
/// <summary>
/// Verify the constant value matches the default value from any earlier attribute
/// (DateTimeConstantAttribute or DecimalConstantAttribute).
/// If not, report ERR_FieldHasMultipleDistinctConstantValues.
/// </summary>
private void VerifyConstantValueMatches(ConstantValue attrValue, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
{
if (!attrValue.IsBad)
{
var data = arguments.GetOrCreateData<FieldWellKnownAttributeData>();
ConstantValue constValue;
var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics;
if (this.IsConst)
{
if (this.Type.SpecialType == SpecialType.System_Decimal)
{
constValue = this.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false);
if ((object)constValue != null && !constValue.IsBad && constValue != attrValue)
{
diagnostics.Add(ErrorCode.ERR_FieldHasMultipleDistinctConstantValues, arguments.AttributeSyntaxOpt.Location);
}
}
else
{
diagnostics.Add(ErrorCode.ERR_FieldHasMultipleDistinctConstantValues, arguments.AttributeSyntaxOpt.Location);
}
if (data.ConstValue == CodeAnalysis.ConstantValue.Unset)
{
data.ConstValue = attrValue;
}
}
else
{
constValue = data.ConstValue;
if (constValue != CodeAnalysis.ConstantValue.Unset)
{
if (constValue != attrValue)
{
diagnostics.Add(ErrorCode.ERR_FieldHasMultipleDistinctConstantValues, arguments.AttributeSyntaxOpt.Location);
}
}
else
{
data.ConstValue = attrValue;
}
}
}
}
internal override void PostDecodeWellKnownAttributes(ImmutableArray<CSharpAttributeData> boundAttributes, ImmutableArray<AttributeSyntax> allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData)
{
Debug.Assert(!boundAttributes.IsDefault);
Debug.Assert(!allAttributeSyntaxNodes.IsDefault);
Debug.Assert(boundAttributes.Length == allAttributeSyntaxNodes.Length);
Debug.Assert(_lazyCustomAttributesBag != null);
Debug.Assert(_lazyCustomAttributesBag.IsDecodedWellKnownAttributeDataComputed);
Debug.Assert(symbolPart == AttributeLocation.None);
var data = (FieldWellKnownAttributeData)decodedData;
int? fieldOffset = data != null ? data.Offset : null;
if (fieldOffset.HasValue)
{
if (this.ContainingType.Layout.Kind != LayoutKind.Explicit)
{
Debug.Assert(boundAttributes.Any());
// error CS0636: The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)
int i = boundAttributes.IndexOfAttribute(this, AttributeDescription.FieldOffsetAttribute);
diagnostics.Add(ErrorCode.ERR_StructOffsetOnBadStruct, allAttributeSyntaxNodes[i].Name.Location);
}
}
else if (!this.IsStatic && !this.IsConst)
{
if (this.ContainingType.Layout.Kind == LayoutKind.Explicit)
{
// error CS0625: '<field>': instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute
diagnostics.Add(ErrorCode.ERR_MissingStructOffset, this.ErrorLocation, this.AttributeOwner);
}
}
base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData);
}
internal sealed override bool HasSpecialName
{
get
{
if (this.HasRuntimeSpecialName)
{
return true;
}
var data = GetDecodedWellKnownAttributeData();
return data != null && data.HasSpecialNameAttribute;
}
}
internal sealed override bool IsNotSerialized
{
get
{
var data = GetDecodedWellKnownAttributeData();
return data != null && data.HasNonSerializedAttribute;
}
}
internal sealed override MarshalPseudoCustomAttributeData MarshallingInformation
{
get
{
var data = GetDecodedWellKnownAttributeData();
return data != null ? data.MarshallingInformation : null;
}
}
internal sealed override int? TypeLayoutOffset
{
get
{
var data = GetDecodedWellKnownAttributeData();
return data != null ? data.Offset : null;
}
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
var compilation = this.DeclaringCompilation;
var type = this.TypeWithAnnotations;
if (type.Type.ContainsDynamic())
{
AddSynthesizedAttribute(ref attributes,
compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length));
}
if (type.Type.ContainsNativeInteger())
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type));
}
if (type.Type.ContainsTupleNames())
{
AddSynthesizedAttribute(ref attributes,
compilation.SynthesizeTupleNamesAttribute(type.Type));
}
if (compilation.ShouldEmitNullableAttributes(this))
{
AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, ContainingType.GetNullableContextValue(), type));
}
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/Core/Implementation/CommentSelection/ToggleBlockCommentCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommentSelection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection
{
[Export(typeof(ICommandHandler))]
[VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)]
[VisualStudio.Utilities.Name(PredefinedCommandHandlerNames.ToggleBlockComment)]
internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ToggleBlockCommentCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService,
ITextStructureNavigatorSelectorService navigatorSelectorService)
: base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService)
{
}
/// <summary>
/// Gets block comments by parsing the text for comment markers.
/// </summary>
protected override Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot,
TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken)
{
var allText = snapshot.AsText();
var commentedSpans = ArrayBuilder<TextSpan>.GetInstance();
var openIdx = 0;
while ((openIdx = allText.IndexOf(commentInfo.BlockCommentStartString, openIdx, caseSensitive: true)) >= 0)
{
// Retrieve the first closing marker located after the open index.
var closeIdx = allText.IndexOf(commentInfo.BlockCommentEndString, openIdx + commentInfo.BlockCommentStartString.Length, caseSensitive: true);
// If an open marker is found without a close marker, it's an unclosed comment.
if (closeIdx < 0)
{
closeIdx = allText.Length - commentInfo.BlockCommentEndString.Length;
}
var blockCommentSpan = new TextSpan(openIdx, closeIdx + commentInfo.BlockCommentEndString.Length - openIdx);
commentedSpans.Add(blockCommentSpan);
openIdx = closeIdx;
}
return Task.FromResult(commentedSpans.ToImmutableAndFree());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommentSelection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection
{
[Export(typeof(ICommandHandler))]
[VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)]
[VisualStudio.Utilities.Name(PredefinedCommandHandlerNames.ToggleBlockComment)]
internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ToggleBlockCommentCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService,
ITextStructureNavigatorSelectorService navigatorSelectorService)
: base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService)
{
}
/// <summary>
/// Gets block comments by parsing the text for comment markers.
/// </summary>
protected override Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot,
TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken)
{
var allText = snapshot.AsText();
var commentedSpans = ArrayBuilder<TextSpan>.GetInstance();
var openIdx = 0;
while ((openIdx = allText.IndexOf(commentInfo.BlockCommentStartString, openIdx, caseSensitive: true)) >= 0)
{
// Retrieve the first closing marker located after the open index.
var closeIdx = allText.IndexOf(commentInfo.BlockCommentEndString, openIdx + commentInfo.BlockCommentStartString.Length, caseSensitive: true);
// If an open marker is found without a close marker, it's an unclosed comment.
if (closeIdx < 0)
{
closeIdx = allText.Length - commentInfo.BlockCommentEndString.Length;
}
var blockCommentSpan = new TextSpan(openIdx, closeIdx + commentInfo.BlockCommentEndString.Length - openIdx);
commentedSpans.Add(blockCommentSpan);
openIdx = closeIdx;
}
return Task.FromResult(commentedSpans.ToImmutableAndFree());
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.OrderModifiers;
namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.OrderModifiers), Shared]
internal class CSharpOrderModifiersCodeFixProvider : AbstractOrderModifiersCodeFixProvider
{
private const string CS0267 = nameof(CS0267); // The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or 'void'
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpOrderModifiersCodeFixProvider()
: base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance)
{
}
protected override ImmutableArray<string> FixableCompilerErrorIds { get; } = ImmutableArray.Create(CS0267);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.OrderModifiers;
namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.OrderModifiers), Shared]
internal class CSharpOrderModifiersCodeFixProvider : AbstractOrderModifiersCodeFixProvider
{
private const string CS0267 = nameof(CS0267); // The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or 'void'
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpOrderModifiersCodeFixProvider()
: base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance)
{
}
protected override ImmutableArray<string> FixableCompilerErrorIds { get; } = ImmutableArray.Create(CS0267);
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/Test/EditorAdapter/TextSnapshotImplementationTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.EditorUtilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorAdapter
{
[UseExportProvider]
public class TextSnapshotImplementationTest
{
private static Tuple<ITextSnapshot, SourceText> Create(params string[] lines)
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var buffer = EditorFactory.CreateBuffer(exportProvider, lines);
var text = buffer.CurrentSnapshot.AsText();
return Tuple.Create(buffer.CurrentSnapshot, text);
}
[Fact]
public void Basic1()
{
var tuple = Create("goo", "bar");
var text = tuple.Item2;
Assert.Equal(tuple.Item1.LineCount, text.Lines.Count);
Assert.Equal(tuple.Item1.Length, text.Length);
Assert.Equal(tuple.Item1.GetText(), text.ToString());
}
[Fact]
public void GetLineFromLineNumber1()
{
var tuple = Create("goo", "bar");
var text = tuple.Item2;
var line1 = text.Lines[0];
Assert.Equal(new TextSpan(0, 3), line1.Span);
Assert.Equal(new TextSpan(0, 5), line1.SpanIncludingLineBreak);
Assert.Equal("goo", line1.ToString());
}
[Fact]
public void GetLineFromLineNumber2()
{
var tuple = Create("goo", "bar");
var text = tuple.Item2;
var line1 = text.Lines[1];
Assert.Equal(new TextSpan(5, 3), line1.Span);
Assert.Equal(new TextSpan(5, 3), line1.SpanIncludingLineBreak);
Assert.Equal("bar", line1.ToString());
}
[Fact]
public void Lines1()
{
var tuple = Create("goo", "bar");
var lines = tuple.Item2.Lines;
Assert.Equal(2, lines.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;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.EditorUtilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorAdapter
{
[UseExportProvider]
public class TextSnapshotImplementationTest
{
private static Tuple<ITextSnapshot, SourceText> Create(params string[] lines)
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var buffer = EditorFactory.CreateBuffer(exportProvider, lines);
var text = buffer.CurrentSnapshot.AsText();
return Tuple.Create(buffer.CurrentSnapshot, text);
}
[Fact]
public void Basic1()
{
var tuple = Create("goo", "bar");
var text = tuple.Item2;
Assert.Equal(tuple.Item1.LineCount, text.Lines.Count);
Assert.Equal(tuple.Item1.Length, text.Length);
Assert.Equal(tuple.Item1.GetText(), text.ToString());
}
[Fact]
public void GetLineFromLineNumber1()
{
var tuple = Create("goo", "bar");
var text = tuple.Item2;
var line1 = text.Lines[0];
Assert.Equal(new TextSpan(0, 3), line1.Span);
Assert.Equal(new TextSpan(0, 5), line1.SpanIncludingLineBreak);
Assert.Equal("goo", line1.ToString());
}
[Fact]
public void GetLineFromLineNumber2()
{
var tuple = Create("goo", "bar");
var text = tuple.Item2;
var line1 = text.Lines[1];
Assert.Equal(new TextSpan(5, 3), line1.Span);
Assert.Equal(new TextSpan(5, 3), line1.SpanIncludingLineBreak);
Assert.Equal("bar", line1.ToString());
}
[Fact]
public void Lines1()
{
var tuple = Create("goo", "bar");
var lines = tuple.Item2.Lines;
Assert.Equal(2, lines.Count);
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpCompileResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.ObjectModel;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CSharpCompileResult : CompileResult
{
private readonly MethodSymbol _method;
internal CSharpCompileResult(
byte[] assembly,
MethodSymbol method,
ReadOnlyCollection<string>? formatSpecifiers)
: base(assembly, method.ContainingType.MetadataName, method.MetadataName, formatSpecifiers)
{
Debug.Assert(method is EEMethodSymbol); // Expected but not required.
_method = method;
}
public override Guid GetCustomTypeInfo(out ReadOnlyCollection<byte>? payload)
{
payload = _method.GetCustomTypeInfoPayload();
return (payload == null) ? default : CustomTypeInfo.PayloadTypeId;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.ObjectModel;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CSharpCompileResult : CompileResult
{
private readonly MethodSymbol _method;
internal CSharpCompileResult(
byte[] assembly,
MethodSymbol method,
ReadOnlyCollection<string>? formatSpecifiers)
: base(assembly, method.ContainingType.MetadataName, method.MetadataName, formatSpecifiers)
{
Debug.Assert(method is EEMethodSymbol); // Expected but not required.
_method = method;
}
public override Guid GetCustomTypeInfo(out ReadOnlyCollection<byte>? payload)
{
payload = _method.GetCustomTypeInfoPayload();
return (payload == null) ? default : CustomTypeInfo.PayloadTypeId;
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/VisualBasicTest/SignatureHelp/GetTypeExpressionSignatureHelpProviderTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp
Public Class GetTypeExpressionSignatureHelpProviderTests
Inherits AbstractVisualBasicSignatureHelpProviderTests
Friend Overrides Function GetSignatureHelpProviderType() As Type
Return GetType(GetTypeExpressionSignatureHelpProvider)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationForGetType() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
Dim x = GetType($$
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem(
$"GetType({VBWorkspaceResources.typeName}) As System.Type",
VBWorkspaceResources.Returns_a_System_Type_object_for_the_specified_type_name,
VBWorkspaceResources.The_type_name_to_return_a_System_Type_object_for,
currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp
Public Class GetTypeExpressionSignatureHelpProviderTests
Inherits AbstractVisualBasicSignatureHelpProviderTests
Friend Overrides Function GetSignatureHelpProviderType() As Type
Return GetType(GetTypeExpressionSignatureHelpProvider)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)>
Public Async Function TestInvocationForGetType() As Task
Dim markup = <a><![CDATA[
Class C
Sub Goo()
Dim x = GetType($$
End Sub
End Class
]]></a>.Value
Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)()
expectedOrderedItems.Add(New SignatureHelpTestItem(
$"GetType({VBWorkspaceResources.typeName}) As System.Type",
VBWorkspaceResources.Returns_a_System_Type_object_for_the_specified_type_name,
VBWorkspaceResources.The_type_name_to_return_a_System_Type_object_for,
currentParameterIndex:=0))
Await TestAsync(markup, expectedOrderedItems)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Coordinates the exectution of LSP messages to ensure correct results are sent back.
/// </summary>
/// <remarks>
/// <para>
/// When a request comes in for some data the handler must be able to access a solution state that is correct
/// at the time of the request, that takes into account any text change requests that have come in previously
/// (via textDocument/didChange for example).
/// </para>
/// <para>
/// This class acheives this by distinguishing between mutating and non-mutating requests, and ensuring that
/// when a mutating request comes in, its processing blocks all subsequent requests. As each request comes in
/// it is added to a queue, and a queue item will not be retrieved while a mutating request is running. Before
/// any request is handled the solution state is created by merging workspace solution state, which could have
/// changes from non-LSP means (eg, adding a project reference), with the current "mutated" state.
/// When a non-mutating work item is retrieved from the queue, it is given the current solution state, but then
/// run in a fire-and-forget fashion.
/// </para>
/// <para>
/// Regardless of whether a request is mutating or not, or blocking or not, is an implementation detail of this class
/// and any consumers observing the results of the task returned from <see cref="ExecuteAsync{TRequestType, TResponseType}(bool, bool, IRequestHandler{TRequestType, TResponseType}, TRequestType, ClientCapabilities, string?, string, CancellationToken)"/>
/// will see the results of the handling of the request, whenever it occurred.
/// </para>
/// <para>
/// Exceptions in the handling of non-mutating requests are sent back to callers. Exceptions in the processing of
/// the queue will close the LSP connection so that the client can reconnect. Exceptions in the handling of mutating
/// requests will also close the LSP connection, as at that point the mutated solution is in an unknown state.
/// </para>
/// <para>
/// After shutdown is called, or an error causes the closing of the connection, the queue will not accept any
/// more messages, and a new queue will need to be created.
/// </para>
/// </remarks>
internal partial class RequestExecutionQueue
{
private readonly string _serverName;
private readonly AsyncQueue<QueueItem> _queue;
private readonly CancellationTokenSource _cancelSource;
private readonly DocumentChangeTracker _documentChangeTracker;
private readonly RequestTelemetryLogger _requestTelemetryLogger;
// This dictionary is used to cache our forked LSP solution so we don't have to
// recompute it for each request. We don't need to worry about threading because they are only
// used when preparing to handle a request, which happens in a single thread in the ProcessQueueAsync
// method.
private readonly Dictionary<Workspace, (Solution workspaceSolution, Solution lspSolution)> _lspSolutionCache = new();
private readonly ILspLogger _logger;
private readonly ILspWorkspaceRegistrationService _workspaceRegistrationService;
public CancellationToken CancellationToken => _cancelSource.Token;
/// <summary>
/// Raised when the execution queue has failed, or the solution state its tracking is in an unknown state
/// and so the only course of action is to shutdown the server so that the client re-connects and we can
/// start over again.
/// </summary>
/// <remarks>
/// Once this event has been fired all currently active and pending work items in the queue will be cancelled.
/// </remarks>
public event EventHandler<RequestShutdownEventArgs>? RequestServerShutdown;
public RequestExecutionQueue(
ILspLogger logger,
ILspWorkspaceRegistrationService workspaceRegistrationService,
string serverName,
string serverTypeName)
{
_logger = logger;
_workspaceRegistrationService = workspaceRegistrationService;
_serverName = serverName;
_queue = new AsyncQueue<QueueItem>();
_cancelSource = new CancellationTokenSource();
_documentChangeTracker = new DocumentChangeTracker();
// Pass the language client instance type name to the telemetry logger to ensure we can
// differentiate between the different C# LSP servers that have the same client name.
// We also don't use the language client's name property as it is a localized user facing string
// which is difficult to write telemetry queries for.
_requestTelemetryLogger = new RequestTelemetryLogger(serverTypeName);
// Start the queue processing
_ = ProcessQueueAsync();
}
/// <summary>
/// Shuts down the queue, stops accepting new messages, and cancels any in-progress or queued tasks. Calling
/// this multiple times won't cause any issues.
/// </summary>
public void Shutdown()
{
_cancelSource.Cancel();
DrainQueue();
_requestTelemetryLogger.Dispose();
}
/// <summary>
/// Queues a request to be handled by the specified handler, with mutating requests blocking subsequent requests
/// from starting until the mutation is complete.
/// </summary>
/// <param name="mutatesSolutionState">Whether or not handling this method results in changes to the current solution state.
/// Mutating requests will block all subsequent requests from starting until after they have
/// completed and mutations have been applied.</param>
/// <param name="requiresLSPSolution">Whether or not to build a solution that represents the LSP view of the world. If this
/// is set to false, the default workspace's current solution will be used.</param>
/// <param name="handler">The handler that will handle the request.</param>
/// <param name="request">The request to handle.</param>
/// <param name="clientCapabilities">The client capabilities.</param>
/// <param name="clientName">The client name.</param>
/// <param name="methodName">The name of the LSP method.</param>
/// <param name="requestCancellationToken">A cancellation token that will cancel the handing of this request.
/// The request could also be cancelled by the queue shutting down.</param>
/// <returns>A task that can be awaited to observe the results of the handing of this request.</returns>
public Task<TResponseType> ExecuteAsync<TRequestType, TResponseType>(
bool mutatesSolutionState,
bool requiresLSPSolution,
IRequestHandler<TRequestType, TResponseType> handler,
TRequestType request,
ClientCapabilities clientCapabilities,
string? clientName,
string methodName,
CancellationToken requestCancellationToken) where TRequestType : class
{
// Create a task completion source that will represent the processing of this request to the caller
var completion = new TaskCompletionSource<TResponseType>();
// Note: If the queue is not accepting any more items then TryEnqueue below will fail.
var textDocument = handler.GetTextDocumentIdentifier(request);
var item = new QueueItem(
mutatesSolutionState,
requiresLSPSolution,
clientCapabilities,
clientName,
methodName,
textDocument,
Trace.CorrelationManager.ActivityId,
_logger,
_requestTelemetryLogger,
callbackAsync: async (context, cancellationToken) =>
{
// Check if cancellation was requested while this was waiting in the queue
if (cancellationToken.IsCancellationRequested)
{
completion.SetCanceled();
return;
}
try
{
var result = await handler.HandleRequestAsync(request, context, cancellationToken).ConfigureAwait(false);
completion.SetResult(result);
}
catch (OperationCanceledException ex)
{
completion.TrySetCanceled(ex.CancellationToken);
}
catch (Exception exception)
{
// Pass the exception to the task completion source, so the caller of the ExecuteAsync method can react
completion.SetException(exception);
// Also allow the exception to flow back to the request queue to handle as appropriate
throw new InvalidOperationException($"Error handling '{methodName}' request: {exception.Message}", exception);
}
}, requestCancellationToken);
var didEnqueue = _queue.TryEnqueue(item);
// If the queue has been shut down the enqueue will fail, so we just fault the task immediately.
// The queue itself is threadsafe (_queue.TryEnqueue and _queue.Complete use the same lock).
if (!didEnqueue)
{
completion.SetException(new InvalidOperationException($"{_serverName} was requested to shut down."));
}
return completion.Task;
}
private async Task ProcessQueueAsync()
{
try
{
while (!_cancelSource.IsCancellationRequested)
{
var work = await _queue.DequeueAsync(_cancelSource.Token).ConfigureAwait(false);
// Record when the work item was been de-queued and the request context preparation started.
work.Metrics.RecordExecutionStart();
// Restore our activity id so that logging/tracking works across asynchronous calls.
Trace.CorrelationManager.ActivityId = work.ActivityId;
var context = CreateRequestContext(work, out var workspace);
if (work.MutatesSolutionState)
{
// Mutating requests block other requests from starting to ensure an up to date snapshot is used.
await ExecuteCallbackAsync(work, context, _cancelSource.Token).ConfigureAwait(false);
// Now that we've mutated our solution, clear out our saved state to ensure it gets recalculated
_lspSolutionCache.Remove(workspace);
}
else
{
// Non mutating are fire-and-forget because they are by definition readonly. Any errors
// will be sent back to the client but we can still capture errors in queue processing
// via NFW, though these errors don't put us into a bad state as far as the rest of the queue goes.
_ = ExecuteCallbackAsync(work, context, _cancelSource.Token).ReportNonFatalErrorAsync();
}
}
}
catch (OperationCanceledException e) when (e.CancellationToken == _cancelSource.Token)
{
// If cancellation occurs as a result of our token, then it was either because we cancelled it in the Shutdown
// method, if it happened during a mutating request, or because the queue was completed in the Shutdown method
// if it happened while waiting to dequeue the next item. Either way, we're already shutting down so we don't
// want to log it.
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
_logger.TraceException(e);
OnRequestServerShutdown($"Error occurred processing queue in {_serverName}: {e.Message}.");
}
}
private static async Task ExecuteCallbackAsync(QueueItem work, RequestContext context, CancellationToken queueCancellationToken)
{
// Create a combined cancellation token to cancel any requests in progress when this shuts down
using var combinedTokenSource = queueCancellationToken.CombineWith(work.CancellationToken);
await work.CallbackAsync(context, combinedTokenSource.Token).ConfigureAwait(false);
}
private void OnRequestServerShutdown(string message)
{
RequestServerShutdown?.Invoke(this, new RequestShutdownEventArgs(message));
Shutdown();
}
/// <summary>
/// Cancels all requests in the queue and stops the queue from accepting any more requests. After this method
/// is called this queue is essentially useless.
/// </summary>
private void DrainQueue()
{
// Tell the queue not to accept any more items
_queue.Complete();
// Spin through the queue and pass in our cancelled token, so that the waiting tasks are cancelled.
// NOTE: This only really works because the first thing that CallbackAsync does is check for cancellation
// but generics make it annoying to store the TaskCompletionSource<TResult> on the QueueItem so this
// is the best we can do for now. Ideally we would manipulate the TaskCompletionSource directly here
// and just call SetCanceled
while (_queue.TryDequeue(out var item))
{
_ = item.CallbackAsync(default, new CancellationToken(true));
}
}
private RequestContext CreateRequestContext(QueueItem queueItem, out Workspace workspace)
{
var trackerToUse = queueItem.MutatesSolutionState
? (IDocumentChangeTracker)_documentChangeTracker
: new NonMutatingDocumentChangeTracker(_documentChangeTracker);
return RequestContext.Create(
queueItem.RequiresLSPSolution,
queueItem.TextDocument,
queueItem.ClientName,
_logger,
_requestTelemetryLogger,
queueItem.ClientCapabilities,
_workspaceRegistrationService,
_lspSolutionCache,
trackerToUse,
out 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.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Coordinates the exectution of LSP messages to ensure correct results are sent back.
/// </summary>
/// <remarks>
/// <para>
/// When a request comes in for some data the handler must be able to access a solution state that is correct
/// at the time of the request, that takes into account any text change requests that have come in previously
/// (via textDocument/didChange for example).
/// </para>
/// <para>
/// This class acheives this by distinguishing between mutating and non-mutating requests, and ensuring that
/// when a mutating request comes in, its processing blocks all subsequent requests. As each request comes in
/// it is added to a queue, and a queue item will not be retrieved while a mutating request is running. Before
/// any request is handled the solution state is created by merging workspace solution state, which could have
/// changes from non-LSP means (eg, adding a project reference), with the current "mutated" state.
/// When a non-mutating work item is retrieved from the queue, it is given the current solution state, but then
/// run in a fire-and-forget fashion.
/// </para>
/// <para>
/// Regardless of whether a request is mutating or not, or blocking or not, is an implementation detail of this class
/// and any consumers observing the results of the task returned from <see cref="ExecuteAsync{TRequestType, TResponseType}(bool, bool, IRequestHandler{TRequestType, TResponseType}, TRequestType, ClientCapabilities, string?, string, CancellationToken)"/>
/// will see the results of the handling of the request, whenever it occurred.
/// </para>
/// <para>
/// Exceptions in the handling of non-mutating requests are sent back to callers. Exceptions in the processing of
/// the queue will close the LSP connection so that the client can reconnect. Exceptions in the handling of mutating
/// requests will also close the LSP connection, as at that point the mutated solution is in an unknown state.
/// </para>
/// <para>
/// After shutdown is called, or an error causes the closing of the connection, the queue will not accept any
/// more messages, and a new queue will need to be created.
/// </para>
/// </remarks>
internal partial class RequestExecutionQueue
{
private readonly string _serverName;
private readonly AsyncQueue<QueueItem> _queue;
private readonly CancellationTokenSource _cancelSource;
private readonly DocumentChangeTracker _documentChangeTracker;
private readonly RequestTelemetryLogger _requestTelemetryLogger;
// This dictionary is used to cache our forked LSP solution so we don't have to
// recompute it for each request. We don't need to worry about threading because they are only
// used when preparing to handle a request, which happens in a single thread in the ProcessQueueAsync
// method.
private readonly Dictionary<Workspace, (Solution workspaceSolution, Solution lspSolution)> _lspSolutionCache = new();
private readonly ILspLogger _logger;
private readonly ILspWorkspaceRegistrationService _workspaceRegistrationService;
public CancellationToken CancellationToken => _cancelSource.Token;
/// <summary>
/// Raised when the execution queue has failed, or the solution state its tracking is in an unknown state
/// and so the only course of action is to shutdown the server so that the client re-connects and we can
/// start over again.
/// </summary>
/// <remarks>
/// Once this event has been fired all currently active and pending work items in the queue will be cancelled.
/// </remarks>
public event EventHandler<RequestShutdownEventArgs>? RequestServerShutdown;
public RequestExecutionQueue(
ILspLogger logger,
ILspWorkspaceRegistrationService workspaceRegistrationService,
string serverName,
string serverTypeName)
{
_logger = logger;
_workspaceRegistrationService = workspaceRegistrationService;
_serverName = serverName;
_queue = new AsyncQueue<QueueItem>();
_cancelSource = new CancellationTokenSource();
_documentChangeTracker = new DocumentChangeTracker();
// Pass the language client instance type name to the telemetry logger to ensure we can
// differentiate between the different C# LSP servers that have the same client name.
// We also don't use the language client's name property as it is a localized user facing string
// which is difficult to write telemetry queries for.
_requestTelemetryLogger = new RequestTelemetryLogger(serverTypeName);
// Start the queue processing
_ = ProcessQueueAsync();
}
/// <summary>
/// Shuts down the queue, stops accepting new messages, and cancels any in-progress or queued tasks. Calling
/// this multiple times won't cause any issues.
/// </summary>
public void Shutdown()
{
_cancelSource.Cancel();
DrainQueue();
_requestTelemetryLogger.Dispose();
}
/// <summary>
/// Queues a request to be handled by the specified handler, with mutating requests blocking subsequent requests
/// from starting until the mutation is complete.
/// </summary>
/// <param name="mutatesSolutionState">Whether or not handling this method results in changes to the current solution state.
/// Mutating requests will block all subsequent requests from starting until after they have
/// completed and mutations have been applied.</param>
/// <param name="requiresLSPSolution">Whether or not to build a solution that represents the LSP view of the world. If this
/// is set to false, the default workspace's current solution will be used.</param>
/// <param name="handler">The handler that will handle the request.</param>
/// <param name="request">The request to handle.</param>
/// <param name="clientCapabilities">The client capabilities.</param>
/// <param name="clientName">The client name.</param>
/// <param name="methodName">The name of the LSP method.</param>
/// <param name="requestCancellationToken">A cancellation token that will cancel the handing of this request.
/// The request could also be cancelled by the queue shutting down.</param>
/// <returns>A task that can be awaited to observe the results of the handing of this request.</returns>
public Task<TResponseType> ExecuteAsync<TRequestType, TResponseType>(
bool mutatesSolutionState,
bool requiresLSPSolution,
IRequestHandler<TRequestType, TResponseType> handler,
TRequestType request,
ClientCapabilities clientCapabilities,
string? clientName,
string methodName,
CancellationToken requestCancellationToken) where TRequestType : class
{
// Create a task completion source that will represent the processing of this request to the caller
var completion = new TaskCompletionSource<TResponseType>();
// Note: If the queue is not accepting any more items then TryEnqueue below will fail.
var textDocument = handler.GetTextDocumentIdentifier(request);
var item = new QueueItem(
mutatesSolutionState,
requiresLSPSolution,
clientCapabilities,
clientName,
methodName,
textDocument,
Trace.CorrelationManager.ActivityId,
_logger,
_requestTelemetryLogger,
callbackAsync: async (context, cancellationToken) =>
{
// Check if cancellation was requested while this was waiting in the queue
if (cancellationToken.IsCancellationRequested)
{
completion.SetCanceled();
return;
}
try
{
var result = await handler.HandleRequestAsync(request, context, cancellationToken).ConfigureAwait(false);
completion.SetResult(result);
}
catch (OperationCanceledException ex)
{
completion.TrySetCanceled(ex.CancellationToken);
}
catch (Exception exception)
{
// Pass the exception to the task completion source, so the caller of the ExecuteAsync method can react
completion.SetException(exception);
// Also allow the exception to flow back to the request queue to handle as appropriate
throw new InvalidOperationException($"Error handling '{methodName}' request: {exception.Message}", exception);
}
}, requestCancellationToken);
var didEnqueue = _queue.TryEnqueue(item);
// If the queue has been shut down the enqueue will fail, so we just fault the task immediately.
// The queue itself is threadsafe (_queue.TryEnqueue and _queue.Complete use the same lock).
if (!didEnqueue)
{
completion.SetException(new InvalidOperationException($"{_serverName} was requested to shut down."));
}
return completion.Task;
}
private async Task ProcessQueueAsync()
{
try
{
while (!_cancelSource.IsCancellationRequested)
{
var work = await _queue.DequeueAsync(_cancelSource.Token).ConfigureAwait(false);
// Record when the work item was been de-queued and the request context preparation started.
work.Metrics.RecordExecutionStart();
// Restore our activity id so that logging/tracking works across asynchronous calls.
Trace.CorrelationManager.ActivityId = work.ActivityId;
var context = CreateRequestContext(work, out var workspace);
if (work.MutatesSolutionState)
{
// Mutating requests block other requests from starting to ensure an up to date snapshot is used.
await ExecuteCallbackAsync(work, context, _cancelSource.Token).ConfigureAwait(false);
// Now that we've mutated our solution, clear out our saved state to ensure it gets recalculated
_lspSolutionCache.Remove(workspace);
}
else
{
// Non mutating are fire-and-forget because they are by definition readonly. Any errors
// will be sent back to the client but we can still capture errors in queue processing
// via NFW, though these errors don't put us into a bad state as far as the rest of the queue goes.
_ = ExecuteCallbackAsync(work, context, _cancelSource.Token).ReportNonFatalErrorAsync();
}
}
}
catch (OperationCanceledException e) when (e.CancellationToken == _cancelSource.Token)
{
// If cancellation occurs as a result of our token, then it was either because we cancelled it in the Shutdown
// method, if it happened during a mutating request, or because the queue was completed in the Shutdown method
// if it happened while waiting to dequeue the next item. Either way, we're already shutting down so we don't
// want to log it.
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
_logger.TraceException(e);
OnRequestServerShutdown($"Error occurred processing queue in {_serverName}: {e.Message}.");
}
}
private static async Task ExecuteCallbackAsync(QueueItem work, RequestContext context, CancellationToken queueCancellationToken)
{
// Create a combined cancellation token to cancel any requests in progress when this shuts down
using var combinedTokenSource = queueCancellationToken.CombineWith(work.CancellationToken);
await work.CallbackAsync(context, combinedTokenSource.Token).ConfigureAwait(false);
}
private void OnRequestServerShutdown(string message)
{
RequestServerShutdown?.Invoke(this, new RequestShutdownEventArgs(message));
Shutdown();
}
/// <summary>
/// Cancels all requests in the queue and stops the queue from accepting any more requests. After this method
/// is called this queue is essentially useless.
/// </summary>
private void DrainQueue()
{
// Tell the queue not to accept any more items
_queue.Complete();
// Spin through the queue and pass in our cancelled token, so that the waiting tasks are cancelled.
// NOTE: This only really works because the first thing that CallbackAsync does is check for cancellation
// but generics make it annoying to store the TaskCompletionSource<TResult> on the QueueItem so this
// is the best we can do for now. Ideally we would manipulate the TaskCompletionSource directly here
// and just call SetCanceled
while (_queue.TryDequeue(out var item))
{
_ = item.CallbackAsync(default, new CancellationToken(true));
}
}
private RequestContext CreateRequestContext(QueueItem queueItem, out Workspace workspace)
{
var trackerToUse = queueItem.MutatesSolutionState
? (IDocumentChangeTracker)_documentChangeTracker
: new NonMutatingDocumentChangeTracker(_documentChangeTracker);
return RequestContext.Create(
queueItem.RequiresLSPSolution,
queueItem.TextDocument,
queueItem.ClientName,
_logger,
_requestTelemetryLogger,
queueItem.ClientCapabilities,
_workspaceRegistrationService,
_lspSolutionCache,
trackerToUse,
out workspace);
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/VisualStudio/Core/Def/Implementation/CommandBindings.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Editor.Commanding;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.ValueTracking;
namespace Microsoft.VisualStudio.Editor.Implementation
{
internal sealed class CommandBindings
{
[Export]
[CommandBinding(Guids.RoslynGroupIdString, ID.RoslynCommands.GoToImplementation, typeof(GoToImplementationCommandArgs))]
internal CommandBindingDefinition gotoImplementationCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.OrganizeSortUsings, typeof(SortImportsCommandArgs))]
internal CommandBindingDefinition organizeSortCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.OrganizeRemoveAndSort, typeof(SortAndRemoveUnnecessaryImportsCommandArgs))]
internal CommandBindingDefinition organizeRemoveAndSortCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.ContextOrganizeRemoveAndSort, typeof(SortAndRemoveUnnecessaryImportsCommandArgs))]
internal CommandBindingDefinition contextOrganizeRemoveAndSortCommandBinding;
[Export]
[CommandBinding(Guids.RoslynGroupIdString, ID.RoslynCommands.GoToValueTrackingWindow, typeof(ValueTrackingEditorCommandArgs))]
internal CommandBindingDefinition gotoDataFlowToolCommandBinding;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Editor.Commanding;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.ValueTracking;
namespace Microsoft.VisualStudio.Editor.Implementation
{
internal sealed class CommandBindings
{
[Export]
[CommandBinding(Guids.RoslynGroupIdString, ID.RoslynCommands.GoToImplementation, typeof(GoToImplementationCommandArgs))]
internal CommandBindingDefinition gotoImplementationCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.OrganizeSortUsings, typeof(SortImportsCommandArgs))]
internal CommandBindingDefinition organizeSortCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.OrganizeRemoveAndSort, typeof(SortAndRemoveUnnecessaryImportsCommandArgs))]
internal CommandBindingDefinition organizeRemoveAndSortCommandBinding;
[Export]
[CommandBinding(Guids.CSharpGroupIdString, ID.CSharpCommands.ContextOrganizeRemoveAndSort, typeof(SortAndRemoveUnnecessaryImportsCommandArgs))]
internal CommandBindingDefinition contextOrganizeRemoveAndSortCommandBinding;
[Export]
[CommandBinding(Guids.RoslynGroupIdString, ID.RoslynCommands.GoToValueTrackingWindow, typeof(ValueTrackingEditorCommandArgs))]
internal CommandBindingDefinition gotoDataFlowToolCommandBinding;
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/CSharp/Test/Syntax/Parsing/AsyncParsingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using System;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AsyncParsingTests : ParsingTests
{
public AsyncParsingTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: (options ?? TestOptions.Regular).WithLanguageVersion(LanguageVersion.CSharp5));
}
protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options = null)
{
return SyntaxFactory.ParseExpression(text, options: (options ?? TestOptions.Regular).WithLanguageVersion(LanguageVersion.CSharp5));
}
private void TestVersions(Action<CSharpParseOptions> test)
{
foreach (LanguageVersion version in Enum.GetValues(typeof(LanguageVersion)))
{
test(new CSharpParseOptions(languageVersion: version));
}
}
[Fact]
public void SimpleAsyncMethod()
{
UsingTree(@"
class C
{
async void M() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodCalledAsync()
{
UsingTree(@"
class C
{
void async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodReturningAsync()
{
UsingTree(@"
class C
{
async M() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsync()
{
UsingTree(@"
class C
{
async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(13090, "https://github.com/dotnet/roslyn/issues/13090")]
[Fact]
public void MethodAsyncVarAsync()
{
UsingTree(
@"class C
{
static async void M(object async)
{
async.F();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
N(SyntaxKind.VoidKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
N(SyntaxKind.ObjectKeyword);
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void IncompleteAsync()
{
UsingTree(@"
class C
{
async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void IncompleteAsyncAsync()
{
UsingTree(@"
class C
{
async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsync1()
{
UsingTree(@"
class C
{
async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsync2()
{
UsingTree(@"
class C
{
async async = 1;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void IncompleteAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void IncompleteAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember01()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
async Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember02()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
async Tasks.Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember03()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
static async Tasks.Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember04()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async operator+
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken); // async
}
N(SyntaxKind.OperatorKeyword);
N(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember05()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async Task<T>
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember06()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async Task<T> f
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void PropertyAsyncAsync()
{
UsingTree(@"
class C
{
async async { get; set; }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.SetAccessorDeclaration);
{
N(SyntaxKind.SetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void PropertyAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async { get; set; }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.SetAccessorDeclaration);
{
N(SyntaxKind.SetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsync()
{
UsingTree(@"
class C
{
event async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsyncAsync1()
{
UsingTree(@"
class C
{
event async async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsyncAsync2()
{
UsingTree(@"
class C
{
async event async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void AsyncModifierOnDelegateDeclaration()
{
UsingTree(@"
class C
{
public async delegate void Goo();
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.DelegateDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void NonAsyncLambda()
{
TestVersions(options =>
{
UsingNode("async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncSimpleLambda()
{
TestVersions(options =>
{
UsingNode("async async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncAsyncAsyncAsyncSimpleLambda()
{
TestVersions(options =>
{
UsingNode("async async => async async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
}
});
}
[Fact]
public void NonAsyncParenthesizedLambda()
{
TestVersions(options =>
{
UsingNode("(async) => async", options);
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncParenthesizedLambda()
{
TestVersions(options =>
{
UsingNode("async (async) => async", options);
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncSimpleDelegate()
{
TestVersions(options =>
{
UsingNode("async delegate { }", options);
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
});
}
[Fact]
public void AsyncParenthesizedDelegate()
{
TestVersions(options =>
{
UsingNode("async delegate (int x) { }", options);
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
});
}
// Comment directly from CParser::IsAsyncMethod.
// ... 'async' [partial] <typedecl> ...
// ... 'async' [partial] <event> ...
// ... 'async' [partial] <implicit> <operator> ...
// ... 'async' [partial] <explicit> <operator> ...
// ... 'async' [partial] <typename> <operator> ...
// ... 'async' [partial] <typename> <membername> ...
// DEVNOTE: Although we parse async user defined conversions, operators, etc. here,
// anything other than async methods are detected as erroneous later, during the define phase
[Fact]
public void AsyncInterface()
{
// ... 'async' <typedecl> ...
UsingTree(@"
class C
{
async interface
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.InterfaceKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialClass()
{
// ... 'async' 'partial' <typedecl> ...
UsingTree(@"
class C
{
async partial class
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PartialKeyword);
N(SyntaxKind.ClassKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncEvent()
{
// ... 'async' <event> ...
UsingTree(@"
class C
{
async event
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.EventKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialEvent()
{
// ... 'async' 'partial' <event> ...
UsingTree(@"
class C
{
async partial event
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
}
N(SyntaxKind.EventDeclaration);
{
N(SyntaxKind.EventKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncImplicitOperator()
{
// ... 'async' <implicit> <operator> ...
UsingTree(@"
class C
{
async implicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ConversionOperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ImplicitKeyword);
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialImplicitOperator()
{
// ... 'async' 'partial' <implicit> <operator> ...
UsingTree(@"
class C
{
async partial implicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
M(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncExplicitOperator()
{
// ... 'async' <explicit> <operator> ...
UsingTree(@"
class C
{
async explicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ConversionOperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ExplicitKeyword);
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialExplicitOperator()
{
// ... 'async' 'partial' <explicit> <operator> ...
UsingTree(@"
class C
{
async partial explicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
M(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeOperator()
{
// ... 'async' <typename> <operator> ...
UsingTree(@"
class C
{
async C operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialTypeOperator()
{
// ... 'async' 'partial' <typename> <operator> ...
UsingTree(@"
class C
{
async partial int operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
}
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncField()
{
// ... 'async' <typename> <membername> ...
UsingTree(@"
class C
{
async C C
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "C");
}
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialIndexer()
{
// ... 'async' 'partial' <typename> <membername> ...
UsingTree(@"
class C
{
async partial C this
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PartialKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.ThisKeyword);
M(SyntaxKind.BracketedParameterList);
{
M(SyntaxKind.OpenBracketToken);
M(SyntaxKind.CloseBracketToken);
}
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeEndOfFile()
{
UsingTree("class C { async T");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeCloseCurly()
{
UsingTree("class C { async T }");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypePredefinedType()
{
UsingTree(
@"class C {
async T
int");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeModifier()
{
UsingTree(
@"class C {
async T
public");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PublicKeyword);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeFollowedByTypeDecl()
{
UsingTree(
@"class C {
async T
class");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeFollowedByNamespaceDecl()
{
UsingTree(
@"class C {
async T
namespace");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.NamespaceDeclaration);
{
N(SyntaxKind.NamespaceKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(18621, "https://github.com/dotnet/roslyn/issues/18621")]
public void AsyncGenericType()
{
UsingTree(
@"class Program
{
public async Task<IReadOnlyCollection<ProjectConfiguration>>
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "Task");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IReadOnlyCollection");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectConfiguration");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property_ExpressionBody()
{
UsingTree("class async { async async => null; }").GetDiagnostics().Verify(
// (1,27): error CS8026: Feature 'expression-bodied property' is not available in C# 5. Please use language version 6 or greater.
// class async { async async => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied property", "6").WithLocation(1, 27)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property()
{
UsingTree("class async { async async { get; } }").GetDiagnostics().Verify();
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Indexer_ExpressionBody_ErrorCase()
{
UsingTree("interface async { async this[async i] => null; }").GetDiagnostics().Verify(
// (1,39): error CS8026: Feature 'expression-bodied indexer' is not available in C# 5. Please use language version 6 or greater.
// interface async { async this[async i] => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied indexer", "6").WithLocation(1, 39)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.InterfaceKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ThisKeyword);
N(SyntaxKind.BracketedParameterList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Indexer()
{
UsingTree("interface async { async this[async i] { get; } }").GetDiagnostics().Verify();
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.InterfaceKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ThisKeyword);
N(SyntaxKind.BracketedParameterList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property_ExplicitInterface()
{
UsingTree("class async : async { async async.async => null; }").GetDiagnostics().Verify(
// (1,41): error CS8026: Feature 'expression-bodied property' is not available in C# 5. Please use language version 6 or greater.
// class async : async { async async.async => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied property", "6").WithLocation(1, 41)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.BaseList);
{
N(SyntaxKind.ColonToken);
N(SyntaxKind.SimpleBaseType);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ExplicitInterfaceSpecifier);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.DotToken);
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using System;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AsyncParsingTests : ParsingTests
{
public AsyncParsingTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: (options ?? TestOptions.Regular).WithLanguageVersion(LanguageVersion.CSharp5));
}
protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options = null)
{
return SyntaxFactory.ParseExpression(text, options: (options ?? TestOptions.Regular).WithLanguageVersion(LanguageVersion.CSharp5));
}
private void TestVersions(Action<CSharpParseOptions> test)
{
foreach (LanguageVersion version in Enum.GetValues(typeof(LanguageVersion)))
{
test(new CSharpParseOptions(languageVersion: version));
}
}
[Fact]
public void SimpleAsyncMethod()
{
UsingTree(@"
class C
{
async void M() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodCalledAsync()
{
UsingTree(@"
class C
{
void async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodReturningAsync()
{
UsingTree(@"
class C
{
async M() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsync()
{
UsingTree(@"
class C
{
async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(13090, "https://github.com/dotnet/roslyn/issues/13090")]
[Fact]
public void MethodAsyncVarAsync()
{
UsingTree(
@"class C
{
static async void M(object async)
{
async.F();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
N(SyntaxKind.VoidKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
N(SyntaxKind.ObjectKeyword);
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void IncompleteAsync()
{
UsingTree(@"
class C
{
async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void IncompleteAsyncAsync()
{
UsingTree(@"
class C
{
async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsync1()
{
UsingTree(@"
class C
{
async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsync2()
{
UsingTree(@"
class C
{
async async = 1;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void IncompleteAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void IncompleteAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember01()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
async Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember02()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
async Tasks.Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember03()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
static async Tasks.Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember04()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async operator+
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken); // async
}
N(SyntaxKind.OperatorKeyword);
N(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember05()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async Task<T>
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember06()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async Task<T> f
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void PropertyAsyncAsync()
{
UsingTree(@"
class C
{
async async { get; set; }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.SetAccessorDeclaration);
{
N(SyntaxKind.SetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void PropertyAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async { get; set; }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.SetAccessorDeclaration);
{
N(SyntaxKind.SetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsync()
{
UsingTree(@"
class C
{
event async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsyncAsync1()
{
UsingTree(@"
class C
{
event async async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsyncAsync2()
{
UsingTree(@"
class C
{
async event async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void AsyncModifierOnDelegateDeclaration()
{
UsingTree(@"
class C
{
public async delegate void Goo();
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.DelegateDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void NonAsyncLambda()
{
TestVersions(options =>
{
UsingNode("async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncSimpleLambda()
{
TestVersions(options =>
{
UsingNode("async async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncAsyncAsyncAsyncSimpleLambda()
{
TestVersions(options =>
{
UsingNode("async async => async async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
}
});
}
[Fact]
public void NonAsyncParenthesizedLambda()
{
TestVersions(options =>
{
UsingNode("(async) => async", options);
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncParenthesizedLambda()
{
TestVersions(options =>
{
UsingNode("async (async) => async", options);
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncSimpleDelegate()
{
TestVersions(options =>
{
UsingNode("async delegate { }", options);
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
});
}
[Fact]
public void AsyncParenthesizedDelegate()
{
TestVersions(options =>
{
UsingNode("async delegate (int x) { }", options);
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
});
}
// Comment directly from CParser::IsAsyncMethod.
// ... 'async' [partial] <typedecl> ...
// ... 'async' [partial] <event> ...
// ... 'async' [partial] <implicit> <operator> ...
// ... 'async' [partial] <explicit> <operator> ...
// ... 'async' [partial] <typename> <operator> ...
// ... 'async' [partial] <typename> <membername> ...
// DEVNOTE: Although we parse async user defined conversions, operators, etc. here,
// anything other than async methods are detected as erroneous later, during the define phase
[Fact]
public void AsyncInterface()
{
// ... 'async' <typedecl> ...
UsingTree(@"
class C
{
async interface
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.InterfaceKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialClass()
{
// ... 'async' 'partial' <typedecl> ...
UsingTree(@"
class C
{
async partial class
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PartialKeyword);
N(SyntaxKind.ClassKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncEvent()
{
// ... 'async' <event> ...
UsingTree(@"
class C
{
async event
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.EventKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialEvent()
{
// ... 'async' 'partial' <event> ...
UsingTree(@"
class C
{
async partial event
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
}
N(SyntaxKind.EventDeclaration);
{
N(SyntaxKind.EventKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncImplicitOperator()
{
// ... 'async' <implicit> <operator> ...
UsingTree(@"
class C
{
async implicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ConversionOperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ImplicitKeyword);
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialImplicitOperator()
{
// ... 'async' 'partial' <implicit> <operator> ...
UsingTree(@"
class C
{
async partial implicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
M(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncExplicitOperator()
{
// ... 'async' <explicit> <operator> ...
UsingTree(@"
class C
{
async explicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ConversionOperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ExplicitKeyword);
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialExplicitOperator()
{
// ... 'async' 'partial' <explicit> <operator> ...
UsingTree(@"
class C
{
async partial explicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
M(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeOperator()
{
// ... 'async' <typename> <operator> ...
UsingTree(@"
class C
{
async C operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialTypeOperator()
{
// ... 'async' 'partial' <typename> <operator> ...
UsingTree(@"
class C
{
async partial int operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
}
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncField()
{
// ... 'async' <typename> <membername> ...
UsingTree(@"
class C
{
async C C
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "C");
}
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialIndexer()
{
// ... 'async' 'partial' <typename> <membername> ...
UsingTree(@"
class C
{
async partial C this
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PartialKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.ThisKeyword);
M(SyntaxKind.BracketedParameterList);
{
M(SyntaxKind.OpenBracketToken);
M(SyntaxKind.CloseBracketToken);
}
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeEndOfFile()
{
UsingTree("class C { async T");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeCloseCurly()
{
UsingTree("class C { async T }");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypePredefinedType()
{
UsingTree(
@"class C {
async T
int");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeModifier()
{
UsingTree(
@"class C {
async T
public");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PublicKeyword);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeFollowedByTypeDecl()
{
UsingTree(
@"class C {
async T
class");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeFollowedByNamespaceDecl()
{
UsingTree(
@"class C {
async T
namespace");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.NamespaceDeclaration);
{
N(SyntaxKind.NamespaceKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(18621, "https://github.com/dotnet/roslyn/issues/18621")]
public void AsyncGenericType()
{
UsingTree(
@"class Program
{
public async Task<IReadOnlyCollection<ProjectConfiguration>>
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "Task");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IReadOnlyCollection");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectConfiguration");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property_ExpressionBody()
{
UsingTree("class async { async async => null; }").GetDiagnostics().Verify(
// (1,27): error CS8026: Feature 'expression-bodied property' is not available in C# 5. Please use language version 6 or greater.
// class async { async async => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied property", "6").WithLocation(1, 27)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property()
{
UsingTree("class async { async async { get; } }").GetDiagnostics().Verify();
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Indexer_ExpressionBody_ErrorCase()
{
UsingTree("interface async { async this[async i] => null; }").GetDiagnostics().Verify(
// (1,39): error CS8026: Feature 'expression-bodied indexer' is not available in C# 5. Please use language version 6 or greater.
// interface async { async this[async i] => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied indexer", "6").WithLocation(1, 39)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.InterfaceKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ThisKeyword);
N(SyntaxKind.BracketedParameterList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Indexer()
{
UsingTree("interface async { async this[async i] { get; } }").GetDiagnostics().Verify();
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.InterfaceKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ThisKeyword);
N(SyntaxKind.BracketedParameterList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property_ExplicitInterface()
{
UsingTree("class async : async { async async.async => null; }").GetDiagnostics().Verify(
// (1,41): error CS8026: Feature 'expression-bodied property' is not available in C# 5. Please use language version 6 or greater.
// class async : async { async async.async => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied property", "6").WithLocation(1, 41)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.BaseList);
{
N(SyntaxKind.ColonToken);
N(SyntaxKind.SimpleBaseType);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ExplicitInterfaceSpecifier);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.DotToken);
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Workspaces/Core/Portable/Workspace/Host/Mef/ServiceLayer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Host.Mef
{
/// <summary>
/// The layer of an exported service.
///
/// If there are multiple definitions of a service, the <see cref="ServiceLayer"/> is used to determine which is used.
/// </summary>
public static class ServiceLayer
{
/// <summary>
/// Service layer that overrides <see cref="Editor"/>, <see cref="Desktop"/> and <see cref="Default"/>.
/// </summary>
internal const string Test = nameof(Test);
/// <summary>
/// Service layer that overrides <see cref="Editor"/>, <see cref="Desktop"/> and <see cref="Default"/>.
/// </summary>
public const string Host = nameof(Host);
/// <summary>
/// Service layer that overrides <see cref="Desktop" /> and <see cref="Default"/>.
/// </summary>
public const string Editor = nameof(Editor);
/// <summary>
/// Service layer that overrides <see cref="Default"/>.
/// </summary>
public const string Desktop = nameof(Desktop);
/// <summary>
/// The base service layer.
/// </summary>
public const string Default = nameof(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
namespace Microsoft.CodeAnalysis.Host.Mef
{
/// <summary>
/// The layer of an exported service.
///
/// If there are multiple definitions of a service, the <see cref="ServiceLayer"/> is used to determine which is used.
/// </summary>
public static class ServiceLayer
{
/// <summary>
/// Service layer that overrides <see cref="Editor"/>, <see cref="Desktop"/> and <see cref="Default"/>.
/// </summary>
internal const string Test = nameof(Test);
/// <summary>
/// Service layer that overrides <see cref="Editor"/>, <see cref="Desktop"/> and <see cref="Default"/>.
/// </summary>
public const string Host = nameof(Host);
/// <summary>
/// Service layer that overrides <see cref="Desktop" /> and <see cref="Default"/>.
/// </summary>
public const string Editor = nameof(Editor);
/// <summary>
/// Service layer that overrides <see cref="Default"/>.
/// </summary>
public const string Desktop = nameof(Desktop);
/// <summary>
/// The base service layer.
/// </summary>
public const string Default = nameof(Default);
}
}
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.TriviaProcessor.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.ExtractMethod
Partial Public Class ExtractMethodTests
<[UseExportProvider]>
Public Class TriviaProcessor
<WorkItem(539281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539281")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function TestCommentBeforeCode() As Threading.Tasks.Task
Dim code = <text>Class C
Sub M()
[|'comment
Console.Write(10)|]
End Sub
End Class</text>
Dim expected = <text>Class C
Sub M()
NewMethod()
End Sub
Private Shared Sub NewMethod()
'comment
Console.Write(10)
End Sub
End Class</text>
Await TestExtractMethodAsync(code, expected)
End Function
<WorkItem(545173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545173")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function LineContinuation() As Threading.Tasks.Task
Dim code = <text>Module Program
Sub Main
Dim x = [|1. _
ToString|]
End Sub
End Module</text>
Dim expected = <text>Module Program
Sub Main
Dim x = GetX()
End Sub
Private Function GetX() As String
Return 1. _
ToString
End Function
End Module</text>
Await TestExtractMethodAsync(code, expected)
End Function
<WorkItem(544568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544568")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function LineContinuation2() As Threading.Tasks.Task
Dim code = <text>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim x1 = Function(num _
As _
Integer
)
Return [|num _
+
1|]
End Function
End Sub
End Module</text>
Dim expected = <text>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim x1 = Function(num _
As _
Integer
)
Return NewMethod(num)
End Function
End Sub
Private Function NewMethod(num As Integer) As Integer
Return num _
+
1
End Function
End Module</text>
Await TestExtractMethodAsync(code, expected)
End Function
<WorkItem(529797, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529797")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function ImplicitLineContinuation() As Threading.Tasks.Task
Dim code = <text>Imports System.Linq
Module A
Sub Main()
Dim q = [|From x In "" Distinct|] ' Extract Method
.ToString()
End Sub
End Module</text>
Dim expected = <text>Imports System.Linq
Module A
Sub Main()
Dim q = NewMethod() ' Extract Method
.ToString()
End Sub
Private Function NewMethod() As System.Collections.Generic.IEnumerable(Of Char)
Return From x In "" Distinct
End Function
End Module</text>
Await TestExtractMethodAsync(code, expected)
End Function
<WorkItem(529797, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529797")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function ImplicitLineContinuation2() As Threading.Tasks.Task
Dim code = <text>Imports System.Linq
Module A
Sub Main()
Dim q = [|From x In "" Distinct|]
.ToString()
End Sub
End Module</text>
Dim expected = <text>Imports System.Linq
Module A
Sub Main()
Dim q = NewMethod()
.ToString()
End Sub
Private Function NewMethod() As System.Collections.Generic.IEnumerable(Of Char)
Return From x In "" Distinct
End Function
End Module</text>
Await TestExtractMethodAsync(code, expected)
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ExtractMethod
Partial Public Class ExtractMethodTests
<[UseExportProvider]>
Public Class TriviaProcessor
<WorkItem(539281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539281")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function TestCommentBeforeCode() As Threading.Tasks.Task
Dim code = <text>Class C
Sub M()
[|'comment
Console.Write(10)|]
End Sub
End Class</text>
Dim expected = <text>Class C
Sub M()
NewMethod()
End Sub
Private Shared Sub NewMethod()
'comment
Console.Write(10)
End Sub
End Class</text>
Await TestExtractMethodAsync(code, expected)
End Function
<WorkItem(545173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545173")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function LineContinuation() As Threading.Tasks.Task
Dim code = <text>Module Program
Sub Main
Dim x = [|1. _
ToString|]
End Sub
End Module</text>
Dim expected = <text>Module Program
Sub Main
Dim x = GetX()
End Sub
Private Function GetX() As String
Return 1. _
ToString
End Function
End Module</text>
Await TestExtractMethodAsync(code, expected)
End Function
<WorkItem(544568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544568")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function LineContinuation2() As Threading.Tasks.Task
Dim code = <text>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim x1 = Function(num _
As _
Integer
)
Return [|num _
+
1|]
End Function
End Sub
End Module</text>
Dim expected = <text>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim x1 = Function(num _
As _
Integer
)
Return NewMethod(num)
End Function
End Sub
Private Function NewMethod(num As Integer) As Integer
Return num _
+
1
End Function
End Module</text>
Await TestExtractMethodAsync(code, expected)
End Function
<WorkItem(529797, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529797")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function ImplicitLineContinuation() As Threading.Tasks.Task
Dim code = <text>Imports System.Linq
Module A
Sub Main()
Dim q = [|From x In "" Distinct|] ' Extract Method
.ToString()
End Sub
End Module</text>
Dim expected = <text>Imports System.Linq
Module A
Sub Main()
Dim q = NewMethod() ' Extract Method
.ToString()
End Sub
Private Function NewMethod() As System.Collections.Generic.IEnumerable(Of Char)
Return From x In "" Distinct
End Function
End Module</text>
Await TestExtractMethodAsync(code, expected)
End Function
<WorkItem(529797, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529797")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function ImplicitLineContinuation2() As Threading.Tasks.Task
Dim code = <text>Imports System.Linq
Module A
Sub Main()
Dim q = [|From x In "" Distinct|]
.ToString()
End Sub
End Module</text>
Dim expected = <text>Imports System.Linq
Module A
Sub Main()
Dim q = NewMethod()
.ToString()
End Sub
Private Function NewMethod() As System.Collections.Generic.IEnumerable(Of Char)
Return From x In "" Distinct
End Function
End Module</text>
Await TestExtractMethodAsync(code, expected)
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,463 | Use new document formatting service when generating types | This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | davidwengier | 2021-08-06T13:03:56Z | 2021-08-10T00:51:49Z | f73f716facc82b8bddaca1d09a9131ea8e58cc2a | 06495a2bf3813e13cff59d2cdf30c24c99966d8e | Use new document formatting service when generating types. This builds on https://github.com/dotnet/roslyn/pull/55432 so only review from [`6342b87` (#55463)](https://github.com/dotnet/roslyn/pull/55463/commits/6342b8783a19633a80127448400d978d4913209d) onwards. Will rebase etc. when that is merged.
This makes Generate Type use the new document formatting service, which realistically means Generate Type now supports file header templates from .editorconfig, and using directive placement options. | ./src/Compilers/CSharp/Test/Semantic/Semantics/OutVarTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using static Roslyn.Test.Utilities.TestMetadata;
using ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.OutVar)]
public class OutVarTests : CompilingTestBase
{
[Fact]
public void OldVersion()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,29): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
[WorkItem(12182, "https://github.com/dotnet/roslyn/issues/12182")]
[WorkItem(16348, "https://github.com/dotnet/roslyn/issues/16348")]
public void DiagnosticsDifferenceBetweenLanguageVersions_01()
{
var text = @"
public class Cls
{
public static void Test1()
{
Test(out int x1);
}
public static void Test2()
{
var x = new Cls(out int x2);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,22): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// Test(out int x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 22),
// (11,33): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x2").WithArguments("out variable declaration", "7.0").WithLocation(11, 33),
// (6,9): error CS0103: The name 'Test' does not exist in the current context
// Test(out int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9),
// (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21),
// (11,29): error CS0165: Use of unassigned local variable 'x2'
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = GetOutVarDeclaration(tree, "x2");
//VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348
VerifyModelForOutVarWithoutDataFlow(model, x2Decl);
compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0103: The name 'Test' does not exist in the current context
// Test(out int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9),
// (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21),
// (11,29): error CS0165: Use of unassigned local variable 'x2'
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29)
);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
x2Decl = GetOutVarDeclaration(tree, "x2");
//VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348
VerifyModelForOutVarWithoutDataFlow(model, x2Decl);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var (x1, x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19),
// (6,24): error CS0103: The name 'x1' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24),
// (6,28): error CS0103: The name 'x2' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28),
// (6,19): error CS0103: The name 'var' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19),
// (7,34): error CS0103: The name 'x1' does not exist in the current context
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34),
// (8,34): error CS0103: The name 'x2' does not exist in the current context
// System.Console.WriteLine(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (var x1, var x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(6, 20),
// (6,28): error CS8185: A declaration is not allowed in this context.
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, var x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (int x1, long x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20),
// (6,28): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, long x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19),
// (6,20): error CS0165: Use of unassigned local variable 'x1'
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20),
// (6,28): error CS0165: Use of unassigned local variable 'x2'
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 28)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (int x1, (long x2, byte x3)));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20),
// (6,29): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 29),
// (6,38): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "byte x3").WithLocation(6, 38),
// (6,28): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(long x2, byte x3)").WithArguments("System.ValueTuple`2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, (long x2, byte x3))").WithArguments("System.ValueTuple`2").WithLocation(6, 19),
// (6,20): error CS0165: Use of unassigned local variable 'x1'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20),
// (6,29): error CS0165: Use of unassigned local variable 'x2'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 29),
// (6,38): error CS0165: Use of unassigned local variable 'x3'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "byte x3").WithArguments("x3").WithLocation(6, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeclarationVarWithoutDataFlow(model, x3Decl, x3Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_05()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out var (x1, (x2, x3)));
System.Console.WriteLine(F1);
}
static ref int var(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (x2, x3)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2, x3))").WithLocation(11, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_06()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
Test1(out var (x1));
System.Console.WriteLine(F1);
}
static ref int var(object x)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1)").WithLocation(8, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_07()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (x1, x2: x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2: x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2: x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_08()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (ref x1, x2));
System.Console.WriteLine(F1);
}
static ref int var(ref object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (ref x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (ref x1, x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_09()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (x1, (x2)));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (x2)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2))").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_10()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var ((x1), x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var ((x1), x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var ((x1), x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_11()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var (x1, x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19),
// (6,24): error CS0103: The name 'x1' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24),
// (6,28): error CS0103: The name 'x2' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28),
// (6,19): error CS0103: The name 'var' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19),
// (7,34): error CS0103: The name 'x1' does not exist in the current context
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34),
// (8,34): error CS0103: The name 'x2' does not exist in the current context
// System.Console.WriteLine(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_12()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out M1 (x1, x2));
System.Console.WriteLine(F1);
}
static ref int M1(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_13()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(ref var (x1, x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(ref int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(ref var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_14()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(var (x1, x2));
System.Console.WriteLine(F1);
}
static int var(object x1, object x2)
{
F1 = 123;
return 124;
}
static object Test1(int x)
{
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput:
@"124
123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_15()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out M1 (x1, (x2, x3)));
System.Console.WriteLine(F1);
}
static ref int M1(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_16()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out var (x1, (a: x2, b: x3)));
System.Console.WriteLine(F1);
}
static ref int var(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (a: x2, b: x3)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (a: x2, b: x3))").WithLocation(11, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name)
{
return GetReferences(tree, name).Single();
}
private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count)
{
var nameRef = GetReferences(tree, name).ToArray();
Assert.Equal(count, nameRef.Length);
return nameRef;
}
internal static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name);
}
private static IEnumerable<DeclarationExpressionSyntax> GetDeclarations(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == name);
}
private static DeclarationExpressionSyntax GetDeclaration(SyntaxTree tree, string name)
{
return GetDeclarations(tree, name).Single();
}
internal static DeclarationExpressionSyntax GetOutVarDeclaration(SyntaxTree tree, string name)
{
return GetOutVarDeclarations(tree, name).Single();
}
private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.IsOutVarDeclaration() && p.Identifier().ValueText == name);
}
private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>();
}
private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken);
}
private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.IsOutVarDeclaration());
}
[Fact]
public void Simple_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1);
int x2;
Test3(out x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
static void Test3(out int y)
{
y = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVarWithoutDataFlow(model, decl, isShadowed: false, references: references);
}
private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isShadowed, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: isShadowed, verifyDataFlow: false, references: references);
}
private static void VerifyModelForDeclarationVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: false, expectedLocalKind: LocalDeclarationKind.DeclarationExpressionVariable, references: references);
}
internal static void VerifyModelForOutVar(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: references);
}
private static void VerifyModelForOutVarInNotExecutableCode(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: references);
}
private static void VerifyModelForOutVarInNotExecutableCode(
SemanticModel model,
DeclarationExpressionSyntax decl,
IdentifierNameSyntax reference)
{
VerifyModelForOutVar(
model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false,
verifyDataFlow: true, references: reference);
}
private static void VerifyModelForOutVar(
SemanticModel model,
DeclarationExpressionSyntax decl,
bool isDelegateCreation,
bool isExecutableCode,
bool isShadowed,
bool verifyDataFlow = true,
LocalDeclarationKind expectedLocalKind = LocalDeclarationKind.OutVariable,
params IdentifierNameSyntax[] references)
{
var variableDeclaratorSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDeclaratorSyntax);
Assert.NotNull(symbol);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(variableDeclaratorSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(expectedLocalKind, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
Assert.False(((ILocalSymbol)symbol).IsFixed);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax));
var other = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single();
if (isShadowed)
{
Assert.NotEqual(symbol, other);
}
else
{
Assert.Same(symbol, other);
}
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText));
var local = (ILocalSymbol)symbol;
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: local.Type);
foreach (var reference in references)
{
Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
}
if (verifyDataFlow)
{
VerifyDataFlow(model, decl, isDelegateCreation, isExecutableCode, references, symbol);
}
}
private static void AssertInfoForDeclarationExpressionSyntax(
SemanticModel model,
DeclarationExpressionSyntax decl,
ISymbol expectedSymbol = null,
ITypeSymbol expectedType = null
)
{
var symbolInfo = model.GetSymbolInfo(decl);
Assert.Equal(expectedSymbol, symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(symbolInfo, ((CSharpSemanticModel)model).GetSymbolInfo(decl));
var typeInfo = model.GetTypeInfo(decl);
Assert.Equal(expectedType, typeInfo.Type);
// skip cases where operation is not supported
AssertTypeFromOperation(model, expectedType, decl);
// Note: the following assertion is not, in general, correct for declaration expressions,
// even though this helper is used to handle declaration expressions.
// However, the tests that use this helper have been carefully crafted to avoid
// triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463
Assert.Equal(expectedType, typeInfo.ConvertedType);
Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(decl));
// Note: the following assertion is not, in general, correct for declaration expressions,
// even though this helper is used to handle declaration expressions.
// However, the tests that use this helper have been carefully crafted to avoid
// triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463
Assert.True(model.GetConversion(decl).IsIdentity);
var typeSyntax = decl.Type;
Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax));
Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax));
ITypeSymbol expected = expectedSymbol?.GetTypeOrReturnType();
if (expected?.IsErrorType() != false)
{
Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol);
}
else
{
Assert.Equal(expected, model.GetSymbolInfo(typeSyntax).Symbol);
}
typeInfo = model.GetTypeInfo(typeSyntax);
Assert.Equal(expected, typeInfo.Type);
Assert.Equal(expected, typeInfo.ConvertedType);
Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(typeSyntax));
Assert.True(model.GetConversion(typeSyntax).IsIdentity);
var conversion = model.ClassifyConversion(decl, model.Compilation.ObjectType, false);
Assert.False(conversion.Exists);
Assert.Equal(conversion, model.ClassifyConversion(decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true));
Assert.Null(model.GetDeclaredSymbol(decl));
}
private static void AssertTypeFromOperation(SemanticModel model, ITypeSymbol expectedType, DeclarationExpressionSyntax decl)
{
// see https://github.com/dotnet/roslyn/issues/23006 and https://github.com/dotnet/roslyn/issues/23007 for more detail
// unlike GetSymbolInfo or GetTypeInfo, GetOperation doesn't use SemanticModel's recovery mode.
// what that means is that GetOperation might return null for ones GetSymbol/GetTypeInfo do return info from
// error recovery mode
var typeofExpression = decl.Ancestors().OfType<TypeOfExpressionSyntax>().FirstOrDefault();
if (typeofExpression?.Type?.FullSpan.Contains(decl.Span) == true)
{
// invalid syntax case where operation is not supported
return;
}
Assert.Equal(expectedType, model.GetOperation(decl)?.Type);
}
private static void VerifyDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, IdentifierNameSyntax[] references, ISymbol symbol)
{
var dataFlowParent = decl.Parent.Parent.Parent as ExpressionSyntax;
if (dataFlowParent == null)
{
if (isExecutableCode || !(decl.Parent.Parent.Parent is VariableDeclaratorSyntax))
{
Assert.IsAssignableFrom<ConstructorInitializerSyntax>(decl.Parent.Parent.Parent);
}
return;
}
if (model.IsSpeculativeSemanticModel)
{
Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent));
return;
}
var dataFlow = model.AnalyzeDataFlow(dataFlowParent);
if (isExecutableCode)
{
Assert.True(dataFlow.Succeeded);
Assert.True(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance));
if (!isDelegateCreation)
{
Assert.True(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.True(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance));
var flowsIn = FlowsIn(dataFlowParent, decl, references);
Assert.Equal(flowsIn,
dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(flowsIn,
dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(FlowsOut(dataFlowParent, decl, references),
dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(ReadOutside(dataFlowParent, references),
dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(WrittenOutside(dataFlowParent, references),
dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
}
}
}
private static void VerifyModelForOutVarDuplicateInSameScope(SemanticModel model, DeclarationExpressionSyntax decl)
{
var variableDesignationSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDesignationSyntax);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(LocalDeclarationKind.OutVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax));
Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single());
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText));
var local = (ILocalSymbol)symbol;
AssertInfoForDeclarationExpressionSyntax(model, decl, local, local.Type);
}
private static void VerifyNotInScope(SemanticModel model, IdentifierNameSyntax reference)
{
Assert.Null(model.GetSymbolInfo(reference).Symbol);
Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
Assert.False(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
private static void VerifyNotAnOutField(SemanticModel model, IdentifierNameSyntax reference)
{
var symbol = model.GetSymbolInfo(reference).Symbol;
Assert.NotEqual(SymbolKind.Field, symbol.Kind);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
internal static void VerifyNotAnOutLocal(SemanticModel model, IdentifierNameSyntax reference)
{
var symbol = model.GetSymbolInfo(reference).Symbol;
if (symbol.Kind == SymbolKind.Local)
{
var local = symbol.GetSymbol<SourceLocalSymbol>();
var parent = local.IdentifierToken.Parent;
Assert.Empty(parent.Ancestors().OfType<DeclarationExpressionSyntax>().Where(e => e.IsOutVarDeclaration()));
if (parent.Kind() == SyntaxKind.VariableDeclarator)
{
var parent1 = ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)parent).Parent).Parent;
switch (parent1.Kind())
{
case SyntaxKind.FixedStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.UsingStatement:
break;
default:
Assert.Equal(SyntaxKind.LocalDeclarationStatement, parent1.Kind());
break;
}
}
}
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
private static SingleVariableDesignationSyntax GetVariableDesignation(DeclarationExpressionSyntax decl)
{
return (SingleVariableDesignationSyntax)decl.Designation;
}
private static bool FlowsIn(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (dataFlowParent.Span.Contains(reference.Span) && reference.SpanStart > decl.SpanStart)
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool IsRead(IdentifierNameSyntax reference)
{
switch (reference.Parent.Kind())
{
case SyntaxKind.Argument:
if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword)
{
return true;
}
break;
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
if (((AssignmentExpressionSyntax)reference.Parent).Left != reference)
{
return true;
}
break;
default:
return true;
}
return false;
}
private static bool ReadOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span))
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool FlowsOut(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references)
{
ForStatementSyntax forStatement;
if ((forStatement = decl.Ancestors().OfType<ForStatementSyntax>().FirstOrDefault()) != null &&
forStatement.Incrementors.Span.Contains(decl.Position) &&
forStatement.Statement.DescendantNodes().OfType<ForStatementSyntax>().Any(f => f.Condition == null))
{
return false;
}
var containingStatement = decl.Ancestors().OfType<StatementSyntax>().FirstOrDefault();
var containingReturnOrThrow = containingStatement as ReturnStatementSyntax ?? (StatementSyntax)(containingStatement as ThrowStatementSyntax);
MethodDeclarationSyntax methodDeclParent;
if (containingReturnOrThrow != null && decl.Identifier().ValueText == "x1" &&
((methodDeclParent = containingReturnOrThrow.Parent.Parent as MethodDeclarationSyntax) == null ||
methodDeclParent.Body.Statements.First() != containingReturnOrThrow))
{
return false;
}
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span) &&
(containingReturnOrThrow == null || containingReturnOrThrow.Span.Contains(reference.SpanStart)) &&
(reference.SpanStart > decl.SpanStart ||
(containingReturnOrThrow == null &&
reference.Ancestors().OfType<DoStatementSyntax>().Join(
decl.Ancestors().OfType<DoStatementSyntax>(), d => d, d => d, (d1, d2) => true).Any())))
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool WrittenOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span))
{
if (IsWrite(reference))
{
return true;
}
}
}
return false;
}
private static bool IsWrite(IdentifierNameSyntax reference)
{
switch (reference.Parent.Kind())
{
case SyntaxKind.Argument:
if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.None)
{
return true;
}
break;
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
if (((AssignmentExpressionSyntax)reference.Parent).Left == reference)
{
return true;
}
break;
case SyntaxKind.PreIncrementExpression:
case SyntaxKind.PostIncrementExpression:
case SyntaxKind.PreDecrementExpression:
case SyntaxKind.PostDecrementExpression:
return true;
default:
return false;
}
return false;
}
[Fact]
public void Simple_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.Int32 x1), x1);
int x2 = 0;
Test3(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
static void Test3(int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
[Fact]
public void Simple_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out (int, int) x1), x1);
}
static object Test1(out (int, int) x)
{
x = (123, 124);
return null;
}
static void Test2(object x, (int, int) y)
{
System.Console.WriteLine(y);
}
}
namespace System
{
// struct with two values
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
public override string ToString()
{
return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}';
}
}
}
" + TestResources.NetFX.ValueTuple.tupleattributes_cs;
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"{123, 124}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.Collections.Generic.IEnumerable<System.Int32> x1), x1);
}
static object Test1(out System.Collections.Generic.IEnumerable<System.Int32> x)
{
x = new System.Collections.Generic.List<System.Int32>();
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"System.Collections.Generic.List`1[System.Int32]").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1, out x1), x1);
}
static object Test1(out int x, out int y)
{
x = 123;
y = 124;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1, x1 = 124), x1);
}
static object Test1(out int x, int y)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_07()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1, x1 = 124);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y, int z)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), ref x1);
int x2 = 0;
Test3(ref x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, ref int y)
{
System.Console.WriteLine(y);
}
static void Test3(ref int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
[Fact]
public void Simple_09()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), out x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, out int y)
{
y = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_10()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out dynamic x1), x1);
}
static object Test1(out dynamic x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
references: new MetadataReference[] { CSharpRef },
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_11()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int[] x1), x1);
}
static object Test1(out int[] x)
{
x = new [] {123};
return null;
}
static void Test2(object x, int[] y)
{
System.Console.WriteLine(y[0]);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_01()
{
var text = @"
public class Cls
{
public static void Main()
{
int x1 = 0;
Test1(out int x1);
Test2(Test1(out int x2),
out int x2);
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(object y, out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,23): error CS0128: A local variable named 'x1' is already defined in this scope
// Test1(out int x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 23),
// (9,29): error CS0128: A local variable named 'x2' is already defined in this scope
// out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(9, 29),
// (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used
// int x1 = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13)
);
}
[Fact]
public void Scope_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(x1,
Test1(out int x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(object y, object x)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,15): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 15)
);
}
[Fact]
public void Scope_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(out x1,
Test1(out int x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(out int y, object x)
{
y = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(out x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19)
);
}
[Fact]
public void Scope_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out int x1);
System.Console.WriteLine(x1);
}
static object Test1(out int x)
{
x = 1;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(out x1,
Test1(out var x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(out int y, object x)
{
y = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(out x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19)
);
}
[Fact]
public void Scope_Attribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(p = TakeOutParam(out int x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out int x4))]
[Test(p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out int x6) && x6 > 0,
p2 = TakeOutParam(out int x6) && x6 > 0)]
[Test(p = TakeOutParam(out int x7) && x7 > 0)]
[Test(p = x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out int x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 15),
// (9,15): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15),
// (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40),
// (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithLocation(10, 15),
// (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37),
// (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p1 = TakeOutParam(out int x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 16),
// (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 16),
// (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out int x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 15),
// (16,15): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(TakeOutParam(out int x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out int x4))]
[Test(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(TakeOutParam(out int x6) && x6 > 0,
TakeOutParam(out int x6) && x6 > 0)]
[Test(TakeOutParam(out int x7) && x7 > 0)]
[Test(x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 11),
// (9,11): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11),
// (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36),
// (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithLocation(10, 11),
// (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32),
// (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 11),
// (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 11),
// (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 11),
// (16,11): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(p = TakeOutParam(out var x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out var x4))]
[Test(p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out var x6) && x6 > 0,
p2 = TakeOutParam(out var x6) && x6 > 0)]
[Test(p = TakeOutParam(out var x7) && x7 > 0)]
[Test(p = x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out var x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 15),
// (9,15): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15),
// (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40),
// (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithLocation(10, 15),
// (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37),
// (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p1 = TakeOutParam(out var x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 16),
// (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 16),
// (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out var x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 15),
// (16,15): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(TakeOutParam(out var x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out var x4))]
[Test(TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(TakeOutParam(out var x6) && x6 > 0,
TakeOutParam(out var x6) && x6 > 0)]
[Test(TakeOutParam(out var x7) && x7 > 0)]
[Test(x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 11),
// (9,11): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11),
// (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36),
// (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithLocation(10, 11),
// (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32),
// (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 11),
// (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 11),
// (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 11),
// (16,11): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void AttributeArgument_01()
{
var source =
@"
public class X
{
[Test(out var x3)]
[Test(out int x4)]
[Test(p: out var x5)]
[Test(p: out int x6)]
public static void Main()
{
}
}
class Test : System.Attribute
{
public Test(out int p) { p = 100; }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
compilation.VerifyDiagnostics(
// (4,11): error CS1041: Identifier expected; 'out' is a keyword
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(4, 11),
// (4,19): error CS1003: Syntax error, ',' expected
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(4, 19),
// (5,11): error CS1041: Identifier expected; 'out' is a keyword
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(5, 11),
// (5,15): error CS1525: Invalid expression term 'int'
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(5, 15),
// (5,19): error CS1003: Syntax error, ',' expected
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x4").WithArguments(",", "").WithLocation(5, 19),
// (6,14): error CS1525: Invalid expression term 'out'
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 14),
// (6,14): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 14),
// (6,18): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "var").WithArguments(",", "").WithLocation(6, 18),
// (6,22): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x5").WithArguments(",", "").WithLocation(6, 22),
// (7,14): error CS1525: Invalid expression term 'out'
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(7, 14),
// (7,14): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(7, 14),
// (7,18): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(",", "int").WithLocation(7, 18),
// (7,18): error CS1525: Invalid expression term 'int'
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18),
// (7,22): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x6").WithArguments(",", "").WithLocation(7, 22),
// (4,15): error CS0103: The name 'var' does not exist in the current context
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 15),
// (4,19): error CS0103: The name 'x3' does not exist in the current context
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(4, 19),
// (4,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out var x3)").WithArguments("Test", "2").WithLocation(4, 6),
// (5,19): error CS0103: The name 'x4' does not exist in the current context
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(5, 19),
// (5,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out int x4)").WithArguments("Test", "2").WithLocation(5, 6),
// (6,18): error CS0103: The name 'var' does not exist in the current context
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 18),
// (6,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "var").WithArguments("7.2").WithLocation(6, 18),
// (6,22): error CS0103: The name 'x5' does not exist in the current context
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(6, 22),
// (6,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out var x5)").WithArguments("Test", "3").WithLocation(6, 6),
// (7,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "int").WithArguments("7.2").WithLocation(7, 18),
// (7,22): error CS0103: The name 'x6' does not exist in the current context
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(7, 22),
// (7,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out int x6)").WithArguments("Test", "3").WithLocation(7, 6)
);
var tree = compilation.SyntaxTrees.Single();
Assert.False(GetOutVarDeclarations(tree, "x3").Any());
Assert.False(GetOutVarDeclarations(tree, "x4").Any());
Assert.False(GetOutVarDeclarations(tree, "x5").Any());
Assert.False(GetOutVarDeclarations(tree, "x6").Any());
}
[Fact]
public void Scope_Catch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
try {}
catch when (TakeOutParam(out var x1) && x1 > 0)
{
Dummy(x1);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out var x4) && x4 > 0)
{
Dummy(x4);
}
}
void Test6()
{
try {}
catch when (x6 && TakeOutParam(out var x6))
{
Dummy(x6);
}
}
void Test7()
{
try {}
catch when (TakeOutParam(out var x7) && x7 > 0)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
try {}
catch when (TakeOutParam(out var x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
}
void Test9()
{
try {}
catch when (TakeOutParam(out var x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
}
void Test10()
{
try {}
catch when (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// try {}
// catch when (TakeOutParam(y11, out var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test14()
{
try {}
catch when (Dummy(TakeOutParam(out var x14),
TakeOutParam(out var x14), // 2
x14))
{
Dummy(x14);
}
}
void Test15()
{
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out var x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42),
// (34,21): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21),
// (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17),
// (58,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34),
// (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46),
// (78,34): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34),
// (99,48): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48),
// (110,48): error CS0128: A local variable named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Scope_Catch_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
try {}
catch when (TakeOutParam(out int x1) && x1 > 0)
{
Dummy(x1);
}
}
void Test4()
{
int x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out int x4) && x4 > 0)
{
Dummy(x4);
}
}
void Test6()
{
try {}
catch when (x6 && TakeOutParam(out int x6))
{
Dummy(x6);
}
}
void Test7()
{
try {}
catch when (TakeOutParam(out int x7) && x7 > 0)
{
int x7 = 12;
Dummy(x7);
}
}
void Test8()
{
try {}
catch when (TakeOutParam(out int x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
}
void Test9()
{
try {}
catch when (TakeOutParam(out int x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out int x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
}
void Test10()
{
try {}
catch when (TakeOutParam(y10, out int x10))
{
int y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// try {}
// catch when (TakeOutParam(y11, out int x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test14()
{
try {}
catch when (Dummy(TakeOutParam(out int x14),
TakeOutParam(out int x14), // 2
x14))
{
Dummy(x14);
}
}
void Test15()
{
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out int x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out int x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42),
// (34,21): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out int x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21),
// (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17),
// (58,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34),
// (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out int x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46),
// (78,34): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out int x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34),
// (99,48): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(out int x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48),
// (110,48): error CS0128: A local variable named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out int x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Catch_01()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Catch_01_ExplicitType()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out System.Exception x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
}
[Fact]
public void Catch_02()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
System.Console.WriteLine(x1.GetType());
};
System.Console.WriteLine(x1.GetType());
d();
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.InvalidOperationException");
}
[Fact]
public void Catch_03()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
e = new System.NullReferenceException();
System.Console.WriteLine(x1.GetType());
};
System.Console.WriteLine(x1.GetType());
d();
System.Console.WriteLine(e.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.InvalidOperationException
System.NullReferenceException");
}
[Fact]
public void Catch_04()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
e = new System.NullReferenceException();
};
System.Console.WriteLine(x1.GetType());
d();
System.Console.WriteLine(e.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.NullReferenceException");
}
[Fact]
public void Scope_ConstructorInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
X(byte x)
: this(TakeOutParam(3, out int x3) && x3 > 0)
{}
X(sbyte x)
: this(x4 && TakeOutParam(4, out int x4))
{}
X(short x)
: this(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
X(ushort x)
: this(TakeOutParam(6, out int x6) && x6 > 0,
TakeOutParam(6, out int x6) && x6 > 0) // 2
{}
X(int x)
: this(TakeOutParam(7, out int x7) && x7 > 0)
{}
X(uint x)
: this(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
X(params object[] x) {}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : this(x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,41): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41),
// (24,40): error CS0128: A local variable named 'x6' is already defined in this scope
// TakeOutParam(6, out int x6) && x6 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : this(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_ConstructorInitializers_02()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x)
: base(TakeOutParam(3, out int x3) && x3 > 0)
{}
X(sbyte x)
: base(x4 && TakeOutParam(4, out int x4))
{}
X(short x)
: base(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
X(ushort x)
: base(TakeOutParam(6, out int x6) && x6 > 0,
TakeOutParam(6, out int x6) && x6 > 0) // 2
{}
X(int x)
: base(TakeOutParam(7, out int x7) && x7 > 0)
{}
X(uint x)
: base(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
public class Y
{
public Y(params object[] x) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : base(x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,41): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41),
// (24,40): error CS0128: A local variable named 'x6' is already defined in this scope
// TakeOutParam(6, out int x6) && x6 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : base(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_ConstructorInitializers_03()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(12);
}
}
class D
{
public D(int o) : this(TakeOutParam(o, out int x1) && x1 >= 5)
{
Console.WriteLine(x1);
}
public D(bool b) { Console.WriteLine(b); }
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"False
1
True
10
True
12
").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_04()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(12);
}
}
class D : C
{
public D(int o) : base(TakeOutParam(o, out int x1) && x1 >= 5)
{
Console.WriteLine(x1);
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
class C
{
public C(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"False
1
True
10
True
12
").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_05()
{
var source =
@"using System;
class D
{
public D(int o) : this(SpeculateHere)
{
}
public D(bool b) { Console.WriteLine(b); }
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)");
var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, arguments);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model);
Assert.True(success);
Assert.NotNull(model);
tree = initializer.SyntaxTree;
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_06()
{
var source =
@"using System;
class D : C
{
public D(int o) : base(SpeculateHere)
{
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
class C
{
public C(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)");
var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, arguments);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model);
Assert.True(success);
Assert.NotNull(model);
tree = initializer.SyntaxTree;
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var initializerOperation = model.GetOperation(initializer);
Assert.Null(initializerOperation.Parent.Parent.Parent);
VerifyOperationTree(compilation, initializerOperation.Parent.Parent, @"
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)')
Expression:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(TakeOutPar ... && x1 >= 5)')
Children(1):
IInvocationOperation ( C..ctor(System.Boolean b)) (OperationKind.Invocation, Type: System.Void) (Syntax: ':base(TakeO ... && x1 >= 5)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'TakeOutPara ... && x1 >= 5')
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... && x1 >= 5')
Left:
IInvocationOperation (System.Boolean D.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'o')
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'o')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x1 >= 5')
Left:
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
public void Scope_ConstructorInitializers_07()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x3)
: base(TakeOutParam(3, out var x3))
{}
X(sbyte x)
: base(TakeOutParam(4, out var x4))
{
int x4 = 1;
System.Console.WriteLine(x4);
}
X(ushort x)
: base(TakeOutParam(51, out var x5))
=> Dummy(TakeOutParam(52, out var x5), x5);
X(short x)
: base(out int x6, x6)
{}
X(uint x)
: base(out var x7, x7)
{}
X(int x)
: base(TakeOutParam(out int x8, x8))
{}
X(ulong x)
: base(TakeOutParam(out var x9, x9))
{}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(out int x, int y)
{
x = 123;
return true;
}
}
public class Y
{
public Y(params object[] x) {}
public Y(out int x, int y) { x = y; }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// : base(TakeOutParam(3, out var x3))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(9, 40),
// (15,13): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x4 = 1;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 13),
// (21,39): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// => Dummy(TakeOutParam(52, out var x5), x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 39),
// (24,28): error CS0165: Use of unassigned local variable 'x6'
// : base(out int x6, x6)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x6").WithArguments("x6").WithLocation(24, 28),
// (28,28): error CS8196: Reference to an implicitly-typed out variable 'x7' is not permitted in the same argument list.
// : base(out var x7, x7)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x7").WithArguments("x7").WithLocation(28, 28),
// (28,20): error CS1615: Argument 1 may not be passed with the 'out' keyword
// : base(out var x7, x7)
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x7").WithArguments("1", "out").WithLocation(28, 20),
// (32,41): error CS0165: Use of unassigned local variable 'x8'
// : base(TakeOutParam(out int x8, x8))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(32, 41),
// (36,41): error CS8196: Reference to an implicitly-typed out variable 'x9' is not permitted in the same argument list.
// : base(TakeOutParam(out var x9, x9))
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x9").WithArguments("x9").WithLocation(36, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").Single();
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVarWithoutDataFlow(model, x9Decl, x9Ref);
}
[Fact]
public void Scope_Do_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
do
{
Dummy(x1);
}
while (TakeOutParam(true, out var x1) && x1);
}
void Test2()
{
do
Dummy(x2);
while (TakeOutParam(true, out var x2) && x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
do
Dummy(x4);
while (TakeOutParam(true, out var x4) && x4);
}
void Test6()
{
do
Dummy(x6);
while (x6 && TakeOutParam(true, out var x6));
}
void Test7()
{
do
{
var x7 = 12;
Dummy(x7);
}
while (TakeOutParam(true, out var x7) && x7);
}
void Test8()
{
do
Dummy(x8);
while (TakeOutParam(true, out var x8) && x8);
System.Console.WriteLine(x8);
}
void Test9()
{
do
{
Dummy(x9);
do
Dummy(x9);
while (TakeOutParam(true, out var x9) && x9); // 2
}
while (TakeOutParam(true, out var x9) && x9);
}
void Test10()
{
do
{
var y10 = 12;
Dummy(y10);
}
while (TakeOutParam(y10, out var x10));
}
//void Test11()
//{
// do
// {
// let y11 = 12;
// Dummy(y11);
// }
// while (TakeOutParam(y11, out var x11));
//}
void Test12()
{
do
var y12 = 12;
while (TakeOutParam(y12, out var x12));
}
//void Test13()
//{
// do
// let y13 = 12;
// while (TakeOutParam(y13, out var x13));
//}
void Test14()
{
do
{
Dummy(x14);
}
while (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14));
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (97,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(97, 13),
// (14,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(14, 19),
// (22,19): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(22, 19),
// (33,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x4) && x4);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(33, 43),
// (32,19): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy(x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(32, 19),
// (40,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(40, 16),
// (39,19): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(39, 19),
// (47,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(47, 17),
// (56,19): error CS0841: Cannot use local variable 'x8' before it is declared
// Dummy(x8);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x8").WithArguments("x8").WithLocation(56, 19),
// (59,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(59, 34),
// (66,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(66, 19),
// (69,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x9) && x9); // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(69, 47),
// (68,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(68, 23),
// (81,29): error CS0103: The name 'y10' does not exist in the current context
// while (TakeOutParam(y10, out var x10));
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(81, 29),
// (98,29): error CS0103: The name 'y12' does not exist in the current context
// while (TakeOutParam(y12, out var x12));
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(98, 29),
// (97,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(97, 17),
// (115,46): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(115, 46),
// (112,19): error CS0841: Cannot use local variable 'x14' before it is declared
// Dummy(x14);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x14").WithArguments("x14").WithLocation(112, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[1]);
VerifyNotAnOutLocal(model, x7Ref[0]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1], x9Ref[2]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[1]);
VerifyNotAnOutLocal(model, y10Ref[0]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Do_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
do
{
}
while (TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Do_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (DoStatementSyntax)SyntaxFactory.ParseStatement(@"
do {} while (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Do_01()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
do
{
;
}
while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1));
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Do_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f;
do
{
f = false;
}
while (Dummy(f, TakeOutParam((f ? 1 : 2), out int x1), x1));
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Do_03()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
do
;
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1) && false);
if (f)
{
do
;
while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1) && false);
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Do_04()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
do
{
;
}
while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1, l, () => System.Console.WriteLine(x1)));
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
2
3
--
1
2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_ExpressionBodiedFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3(object o) => TakeOutParam(o, out int x3) && x3 > 0;
bool Test4(object o) => x4 && TakeOutParam(o, out int x4);
bool Test5(object o1, object o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0;
bool Test61 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test62 (object o) => TakeOutParam(o, out int x6) && x6 > 0;
bool Test71(object o) => TakeOutParam(o, out int x7) && x7 > 0;
void Test72() => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test11(object x11) => TakeOutParam(1, out int x11) &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,29): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4(object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 29),
// (13,67): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 67),
// (19,28): error CS0103: The name 'x7' does not exist in the current context
// void Test72() => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 28),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,56): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool Test11(object x11) => TakeOutParam(1, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 56)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForOutVar(model, x11Decl, x11Ref);
}
[Fact]
public void ExpressionBodiedFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1() => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void ExpressionBodiedFunctions_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1() => TakeOutParam(1, out var x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
[WorkItem(14214, "https://github.com/dotnet/roslyn/issues/14214")]
public void Scope_ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test3()
{
bool f (object o) => TakeOutParam(o, out int x3) && x3 > 0;
f(null);
}
void Test4()
{
bool f (object o) => x4 && TakeOutParam(o, out int x4);
f(null);
}
void Test5()
{
bool f (object o1, object o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0;
f(null, null);
}
void Test6()
{
bool f1 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool f2 (object o) => TakeOutParam(o, out int x6) && x6 > 0;
f1(null);
f2(null);
}
void Test7()
{
Dummy(x7, 1);
bool f (object o) => TakeOutParam(o, out int x7) && x7 > 0;
Dummy(x7, 2);
f(null);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
bool f (object o) => TakeOutParam(o, out int x11) &&
x11 > 0;
f(null);
}
void Test12()
{
bool f (object o) => TakeOutParam(o, out int x12) &&
x12 > 0;
var x12 = 11;
Dummy(x12);
f(null);
}
System.Action Test13()
{
return () =>
{
bool f (object o) => TakeOutParam(o, out int x13) && x13 > 0;
f(null);
};
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30),
// (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67),
// (39,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15),
// (43,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (18,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30),
// (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67),
// (39,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15),
// (43,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15),
// (51,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => TakeOutParam(o, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(51, 54),
// (58,54): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => TakeOutParam(o, out int x12) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(58, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
// Data flow for the following disabled due to https://github.com/dotnet/roslyn/issues/14214
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarWithoutDataFlow(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x11Decl, x11Ref[1]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
var x13Decl = GetOutVarDeclarations(tree, "x13").Single();
var x13Ref = GetReferences(tree, "x13").Single();
VerifyModelForOutVarWithoutDataFlow(model, x13Decl, x13Ref);
}
[Fact]
public void ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
bool f() => TakeOutParam(1, out int x1) && Dummy(x1);
return f();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void ExpressionBodiedLocalFunctions_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
bool f() => TakeOutParam(1, out var x1) && Dummy(x1);
return f();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void Scope_ExpressionBodiedProperties_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 => TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 => x4 && TakeOutParam(4, out int x4);
bool Test5 => TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 => TakeOutParam(6, out int x6) && x6 > 0; bool Test62 => TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 => TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool this[object x11] => TakeOutParam(1, out int x11) &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,19): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 => x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 19),
// (13,44): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 44),
// (19,26): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 26),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool this[object x11] => TakeOutParam(1, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForOutVar(model, x11Decl, x11Ref);
}
[Fact]
public void ExpressionBodiedProperties_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
System.Console.WriteLine(new X()[0]);
}
static bool Test1 => TakeOutParam(2, out int x1) && Dummy(x1);
bool this[object x] => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
True
1
True");
}
[Fact]
public void ExpressionBodiedProperties_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
System.Console.WriteLine(new X()[0]);
}
static bool Test1 => TakeOutParam(2, out var x1) && Dummy(x1);
bool this[object x] => TakeOutParam(1, out var x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
True
1
True");
}
[Fact]
public void Scope_ExpressionStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
Dummy(TakeOutParam(true, out var x1), x1);
{
Dummy(TakeOutParam(true, out var x1), x1);
}
Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
// Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46),
// (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42),
// (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope
// Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ExpressionStatement_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
bool test = true;
if (test)
Test2(Test1(out int x1), x1);
if (test)
{
Test2(Test1(out int x1), x1);
}
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_ExpressionStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ExpressionStatement_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Scope_FieldInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 = x4 && TakeOutParam(4, out int x4);
bool Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0;
bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9);
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,57): error CS0103: The name 'x8' does not exist in the current context
// bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(22, 57),
// (23,19): error CS0103: The name 'x9' does not exist in the current context
// bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(23, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReference(tree, "x8");
VerifyModelForOutVar(model, x8Decl);
VerifyNotInScope(model, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReference(tree, "x9");
VerifyNotInScope(model, x9Ref);
VerifyModelForOutVar(model, x9Decl);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Scope_FieldInitializers_02()
{
var source =
@"using static Test;
public enum X
{
Test3 = TakeOutParam(3, out int x3) ? x3 : 0,
Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0,
Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0 ? 1 : 0,
Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0,
Test72 = x7,
}
class Test
{
public static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,13): error CS0841: Cannot use local variable 'x4' before it is declared
// Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 13),
// (9,38): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 38),
// (8,13): error CS0133: The expression being assigned to 'X.Test5' must be constant
// Test5 = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0 ? 1 : 0").WithArguments("X.Test5").WithLocation(8, 13),
// (12,14): error CS0133: The expression being assigned to 'X.Test61' must be constant
// Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test61").WithLocation(12, 14),
// (12,70): error CS0133: The expression being assigned to 'X.Test62' must be constant
// Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test62").WithLocation(12, 70),
// (14,14): error CS0133: The expression being assigned to 'X.Test71' must be constant
// Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0").WithArguments("X.Test71").WithLocation(14, 14),
// (15,14): error CS0103: The name 'x7' does not exist in the current context
// Test72 = x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 14),
// (4,13): error CS0133: The expression being assigned to 'X.Test3' must be constant
// Test3 = TakeOutParam(3, out int x3) ? x3 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) ? x3 : 0").WithArguments("X.Test3").WithLocation(4, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IFieldInitializerOperation (Field: X.Test3) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... 3) ? x3 : 0')
Locals: Local_1: System.Int32 x3
IConditionalOperation (OperationKind.Conditional, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... 3) ? x3 : 0')
Condition:
IInvocationOperation (System.Boolean Test.TakeOutParam(System.Object y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '3')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
WhenTrue:
ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
WhenFalse:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
");
}
[Fact]
public void Scope_FieldInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
const bool Test4 = x4 && TakeOutParam(4, out int x4);
const bool Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
const bool Test72 = x7 > 2;
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,24): error CS0133: The expression being assigned to 'X.Test3' must be constant
// const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("X.Test3").WithLocation(8, 24),
// (10,24): error CS0841: Cannot use local variable 'x4' before it is declared
// const bool Test4 = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 24),
// (13,49): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 49),
// (12,24): error CS0133: The expression being assigned to 'X.Test5' must be constant
// const bool Test5 = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithArguments("X.Test5").WithLocation(12, 24),
// (16,25): error CS0133: The expression being assigned to 'X.Test61' must be constant
// const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test61").WithLocation(16, 25),
// (16,73): error CS0133: The expression being assigned to 'X.Test62' must be constant
// const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test62").WithLocation(16, 73),
// (18,25): error CS0133: The expression being assigned to 'X.Test71' must be constant
// const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("X.Test71").WithLocation(18, 25),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// const bool Test72 = x7 > 2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_FieldInitializers_04()
{
var source =
@"
class X : Y
{
public static void Main()
{
}
bool Test3 = TakeOutParam(out int x3, x3);
bool Test4 = TakeOutParam(out var x4, x4);
bool Test5 = TakeOutParam(out int x5, 5);
X()
: this(x5)
{
System.Console.WriteLine(x5);
}
X(object x)
: base(x5)
=> System.Console.WriteLine(x5);
static bool Test6 = TakeOutParam(out int x6, 6);
static X()
{
System.Console.WriteLine(x6);
}
static bool TakeOutParam(out int x, int y)
{
x = 123;
return true;
}
}
class Y
{
public Y(object y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,43): error CS0165: Use of unassigned local variable 'x3'
// bool Test3 = TakeOutParam(out int x3, x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(8, 43),
// (10,43): error CS8196: Reference to an implicitly-typed out variable 'x4' is not permitted in the same argument list.
// bool Test4 = TakeOutParam(out var x4, x4);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x4").WithArguments("x4").WithLocation(10, 43),
// (15,12): error CS0103: The name 'x5' does not exist in the current context
// : this(x5)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(15, 12),
// (17,34): error CS0103: The name 'x5' does not exist in the current context
// System.Console.WriteLine(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(17, 34),
// (21,12): error CS0103: The name 'x5' does not exist in the current context
// : base(x5)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(21, 12),
// (22,33): error CS0103: The name 'x5' does not exist in the current context
// => System.Console.WriteLine(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(22, 33),
// (27,34): error CS0103: The name 'x6' does not exist in the current context
// System.Console.WriteLine(x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(27, 34)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(4, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
VerifyNotInScope(model, x5Ref[3]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void FieldInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,45): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IFieldInitializerOperation (Field: System.Boolean X.Test1) (OperationKind.FieldInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)')
Locals: Local_1: System.Int32 x1
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
[WorkItem(10487, "https://github.com/dotnet/roslyn/issues/10487")]
public void FieldInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 = TakeOutParam(1, out int x1) && Dummy(() => x1);
static bool Dummy(System.Func<int> x)
{
System.Console.WriteLine(x());
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void FieldInitializers_04()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static System.Func<bool> Test1 = () => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void FieldInitializers_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
static bool a = false;
bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0;
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,54): error CS0165: Use of unassigned local variable 'x1'
// bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void FieldInitializers_06()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static int Test1 = TakeOutParam(1, out var x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void Scope_Fixed_01()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
}
void Test6()
{
fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1 = Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p = Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p = Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p = Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p = Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63),
// (68,44): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p = Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44),
// (86,44): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p = Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,55): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Fixed_02()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* x1 =
Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2),
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p = Dummy(TakeOutParam(true, out var x3) && x3))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* p1 = Dummy(TakeOutParam(true, out var x4) && x4),
p2 = Dummy(TakeOutParam(true, out var x4) && x4))
{
Dummy(x4);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,59): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59),
// (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32),
// (14,66): error CS0165: Use of unassigned local variable 'x1'
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 66),
// (23,21): error CS0128: A local variable named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,58): error CS0128: A local variable named 'x3' is already defined in this scope
// p = Dummy(TakeOutParam(true, out var x3) && x3))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58),
// (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// p = Dummy(TakeOutParam(true, out var x3) && x3))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31),
// (41,59): error CS0128: A local variable named 'x4' is already defined in this scope
// p2 = Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void Fixed_01()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
fixed (int* p = Dummy(TakeOutParam(""fixed"", out var x1), x1))
{
System.Console.WriteLine(x1);
}
}
static int[] Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new int[1];
}
static bool TakeOutParam(string y, out string x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput:
@"fixed
fixed");
}
[Fact]
public void Fixed_02()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
fixed (int* p = Dummy(TakeOutParam(""fixed"", out string x1), x1))
{
System.Console.WriteLine(x1);
}
}
static int[] Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new int[1];
}
static bool TakeOutParam(string y, out string x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput:
@"fixed
fixed");
}
[Fact]
public void Scope_For_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;
Dummy(TakeOutParam(true, out var x1) && x1)
;)
{
Dummy(x1);
}
}
void Test2()
{
for (;
Dummy(TakeOutParam(true, out var x2) && x2)
;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;
Dummy(TakeOutParam(true, out var x4) && x4)
;)
Dummy(x4);
}
void Test6()
{
for (;
Dummy(x6 && TakeOutParam(true, out var x6))
;)
Dummy(x6);
}
void Test7()
{
for (;
Dummy(TakeOutParam(true, out var x7) && x7)
;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;
Dummy(TakeOutParam(true, out var x8) && x8)
;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;
Dummy(TakeOutParam(true, out var x9) && x9)
;)
{
Dummy(x9);
for (;
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;)
Dummy(x9);
}
}
void Test10()
{
for (;
Dummy(TakeOutParam(y10, out var x10))
;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;
// Dummy(TakeOutParam(y11, out var x11))
// ;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;
Dummy(TakeOutParam(y12, out var x12))
;)
var y12 = 12;
}
//void Test13()
//{
// for (;
// Dummy(TakeOutParam(y13, out var x13))
// ;)
// let y13 = 12;
//}
void Test14()
{
for (;
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(TakeOutParam(true, out var x1) && x1)
)
{
Dummy(x1);
}
}
void Test2()
{
for (;;
Dummy(TakeOutParam(true, out var x2) && x2)
)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;;
Dummy(TakeOutParam(true, out var x4) && x4)
)
Dummy(x4);
}
void Test6()
{
for (;;
Dummy(x6 && TakeOutParam(true, out var x6))
)
Dummy(x6);
}
void Test7()
{
for (;;
Dummy(TakeOutParam(true, out var x7) && x7)
)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;;
Dummy(TakeOutParam(true, out var x8) && x8)
)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;;
Dummy(TakeOutParam(true, out var x9) && x9)
)
{
Dummy(x9);
for (;;
Dummy(TakeOutParam(true, out var x9) && x9) // 2
)
Dummy(x9);
}
}
void Test10()
{
for (;;
Dummy(TakeOutParam(y10, out var x10))
)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;;
// Dummy(TakeOutParam(y11, out var x11))
// )
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;;
Dummy(TakeOutParam(y12, out var x12))
)
var y12 = 12;
}
//void Test13()
//{
// for (;;
// Dummy(TakeOutParam(y13, out var x13))
// )
// let y13 = 12;
//}
void Test14()
{
for (;;
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (16,19): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(16, 19),
// (25,19): error CS0103: The name 'x2' does not exist in the current context
// Dummy(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(25, 19),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (44,19): error CS0103: The name 'x6' does not exist in the current context
// Dummy(x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(44, 19),
// (63,19): error CS0103: The name 'x8' does not exist in the current context
// Dummy(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(63, 19),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (74,19): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(74, 19),
// (78,23): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(78, 23),
// (71,14): warning CS0162: Unreachable code detected
// Dummy(TakeOutParam(true, out var x9) && x9)
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(71, 14),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44),
// (128,19): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(128, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref[0]);
VerifyNotInScope(model, x2Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref[0]);
VerifyNotInScope(model, x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0]);
VerifyNotInScope(model, x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyNotInScope(model, x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]);
VerifyNotInScope(model, x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
VerifyNotInScope(model, x14Ref[1]);
}
[Fact]
public void Scope_For_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var b =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (var b =
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (var b =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (var b =
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (var b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (var b =
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (var b1 =
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (var b2 =
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (var b =
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (var b =
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (var b =
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (var b =
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (var b =
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool b =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool b =
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool b =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (bool b =
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (bool b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool b =
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool b1 =
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (bool b2 =
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (bool b =
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool b =
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool b =
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (bool b =
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (bool b =
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var x1 =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{}
}
void Test2()
{
for (var x2 = true;
Dummy(TakeOutParam(true, out var x2) && x2)
;)
{}
}
void Test3()
{
for (var x3 = true;;
Dummy(TakeOutParam(true, out var x3) && x3)
)
{}
}
void Test4()
{
for (bool x4 =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
{}
}
void Test5()
{
for (bool x5 = true;
Dummy(TakeOutParam(true, out var x5) && x5)
;)
{}
}
void Test6()
{
for (bool x6 = true;;
Dummy(TakeOutParam(true, out var x6) && x6)
)
{}
}
void Test7()
{
for (bool x7 = true, b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{}
}
void Test8()
{
for (bool b1 = Dummy(TakeOutParam(true, out var x8) && x8),
b2 = Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2 = Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9))
{}
}
void Test10()
{
for (var b = x10;
Dummy(TakeOutParam(true, out var x10) && x10) &&
Dummy(TakeOutParam(true, out var x10) && x10);
Dummy(TakeOutParam(true, out var x10) && x10))
{}
}
void Test11()
{
for (bool b = x11;
Dummy(TakeOutParam(true, out var x11) && x11) &&
Dummy(TakeOutParam(true, out var x11) && x11);
Dummy(TakeOutParam(true, out var x11) && x11))
{}
}
void Test12()
{
for (Dummy(x12);
Dummy(x12) &&
Dummy(TakeOutParam(true, out var x12) && x12);
Dummy(TakeOutParam(true, out var x12) && x12))
{}
}
void Test13()
{
for (var b = x13;
Dummy(x13);
Dummy(TakeOutParam(true, out var x13) && x13),
Dummy(TakeOutParam(true, out var x13) && x13))
{}
}
void Test14()
{
for (bool b = x14;
Dummy(x14);
Dummy(TakeOutParam(true, out var x14) && x14),
Dummy(TakeOutParam(true, out var x14) && x14))
{}
}
void Test15()
{
for (Dummy(x15);
Dummy(x15);
Dummy(x15),
Dummy(TakeOutParam(true, out var x15) && x15))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,47): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 47),
// (13,54): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(TakeOutParam(true, out var x1) && x1)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 54),
// (21,47): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x2) && x2)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 47),
// (20,18): warning CS0219: The variable 'x2' is assigned but its value is never used
// for (var x2 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(20, 18),
// (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x3) && x3)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// (28,18): warning CS0219: The variable 'x3' is assigned but its value is never used
// for (var x3 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(28, 18),
// (37,47): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(37, 47),
// (37,54): error CS0165: Use of unassigned local variable 'x4'
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(37, 54),
// (45,47): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x5) && x5)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(45, 47),
// (44,19): warning CS0219: The variable 'x5' is assigned but its value is never used
// for (bool x5 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(44, 19),
// (53,47): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x6) && x6)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(53, 47),
// (52,19): warning CS0219: The variable 'x6' is assigned but its value is never used
// for (bool x6 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(52, 19),
// (61,47): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(TakeOutParam(true, out var x7) && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(61, 47),
// (69,52): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2 = Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(69, 52),
// (70,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(70, 47),
// (71,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(71, 47),
// (77,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(77, 23),
// (79,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(79, 47),
// (80,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(80, 47),
// (86,22): error CS0103: The name 'x10' does not exist in the current context
// for (var b = x10;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x10").WithArguments("x10").WithLocation(86, 22),
// (88,47): error CS0128: A local variable or function named 'x10' is already defined in this scope
// Dummy(TakeOutParam(true, out var x10) && x10);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x10").WithArguments("x10").WithLocation(88, 47),
// (89,47): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x10) && x10))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(89, 47),
// (95,23): error CS0103: The name 'x11' does not exist in the current context
// for (bool b = x11;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(95, 23),
// (97,47): error CS0128: A local variable or function named 'x11' is already defined in this scope
// Dummy(TakeOutParam(true, out var x11) && x11);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(97, 47),
// (98,47): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x11) && x11))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(98, 47),
// (104,20): error CS0103: The name 'x12' does not exist in the current context
// for (Dummy(x12);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(104, 20),
// (105,20): error CS0841: Cannot use local variable 'x12' before it is declared
// Dummy(x12) &&
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(105, 20),
// (107,47): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x12) && x12))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(107, 47),
// (113,22): error CS0103: The name 'x13' does not exist in the current context
// for (var b = x13;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(113, 22),
// (114,20): error CS0103: The name 'x13' does not exist in the current context
// Dummy(x13);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(114, 20),
// (116,47): error CS0128: A local variable or function named 'x13' is already defined in this scope
// Dummy(TakeOutParam(true, out var x13) && x13))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x13").WithArguments("x13").WithLocation(116, 47),
// (122,23): error CS0103: The name 'x14' does not exist in the current context
// for (bool b = x14;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(122, 23),
// (123,20): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(123, 20),
// (125,47): error CS0128: A local variable or function named 'x14' is already defined in this scope
// Dummy(TakeOutParam(true, out var x14) && x14))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(125, 47),
// (131,20): error CS0103: The name 'x15' does not exist in the current context
// for (Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(131, 20),
// (132,20): error CS0103: The name 'x15' does not exist in the current context
// Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(132, 20),
// (133,20): error CS0841: Cannot use local variable 'x15' before it is declared
// Dummy(x15),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x15").WithArguments("x15").WithLocation(133, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x7Decl);
VerifyNotAnOutLocal(model, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]);
VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(3, x10Decl.Length);
Assert.Equal(4, x10Ref.Length);
VerifyNotInScope(model, x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[1], x10Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x10Decl[1]);
VerifyModelForOutVar(model, x10Decl[2], x10Ref[3]);
var x11Decl = GetOutVarDeclarations(tree, "x11").ToArray();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Decl.Length);
Assert.Equal(4, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl[0], x11Ref[1], x11Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x11Decl[1]);
VerifyModelForOutVar(model, x11Decl[2], x11Ref[3]);
var x12Decl = GetOutVarDeclarations(tree, "x12").ToArray();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Decl.Length);
Assert.Equal(4, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForOutVar(model, x12Decl[0], x12Ref[1], x12Ref[2]);
VerifyModelForOutVar(model, x12Decl[1], x12Ref[3]);
var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(4, x13Ref.Length);
VerifyNotInScope(model, x13Ref[0]);
VerifyNotInScope(model, x13Ref[1]);
VerifyModelForOutVar(model, x13Decl[0], x13Ref[2], x13Ref[3]);
VerifyModelForOutVarDuplicateInSameScope(model, x13Decl[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyNotInScope(model, x14Ref[0]);
VerifyNotInScope(model, x14Ref[1]);
VerifyModelForOutVar(model, x14Decl[0], x14Ref[2], x14Ref[3]);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(4, x15Ref.Length);
VerifyNotInScope(model, x15Ref[0]);
VerifyNotInScope(model, x15Ref[1]);
VerifyModelForOutVar(model, x15Decl, x15Ref[2], x15Ref[3]);
}
[Fact]
public void Scope_For_07()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(x1),
Dummy(TakeOutParam(true, out var x1) && x1))
{}
}
void Test2()
{
for (;;
Dummy(TakeOutParam(true, out var x2) && x2),
Dummy(TakeOutParam(true, out var x2) && x2))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,20): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 20),
// (22,47): error CS0128: A local variable or function named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2) && x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
}
[Fact]
public void For_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void For_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
f = false, Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void For_03()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1); x0++)
{
l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1));
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 20
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(4, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_04()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++)
{
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 20
3 30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(4, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_05()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++)
{
l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1));
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 10
3 20
3 20
3 30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(5, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_06()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)))
{
x0++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"20
30
--
20
30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_07()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)), x0++)
{
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
--
10
20
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_Foreach_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Collections.IEnumerable Dummy(params object[] x) {return null;}
void Test1()
{
foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
}
void Test6()
{
foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// foreach (var i in Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// foreach (var i in Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
foreach (var i in Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
void Test15()
{
foreach (var x15 in
Dummy(TakeOutParam(1, out var x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,60): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 60),
// (35,33): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 33),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,65): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 65),
// (68,46): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 46),
// (86,46): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 46),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,57): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 57),
// (108,22): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(108, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Foreach_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
foreach (var i in Dummy(TakeOutParam(3, out var x1), x1))
{
System.Console.WriteLine(x1);
}
}
static System.Collections.IEnumerable Dummy(object y, object z)
{
System.Console.WriteLine(z);
return ""a"";
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"3
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_If_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (TakeOutParam(true, out var x1))
{
Dummy(x1);
}
else
{
System.Console.WriteLine(x1);
}
}
void Test2()
{
if (TakeOutParam(true, out var x2))
Dummy(x2);
else
System.Console.WriteLine(x2);
}
void Test3()
{
if (TakeOutParam(true, out var x3))
Dummy(x3);
else
{
var x3 = 12;
System.Console.WriteLine(x3);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
if (TakeOutParam(true, out var x4))
Dummy(x4);
}
void Test5(int x5)
{
if (TakeOutParam(true, out var x5))
Dummy(x5);
}
void Test6()
{
if (x6 && TakeOutParam(true, out var x6))
Dummy(x6);
}
void Test7()
{
if (TakeOutParam(true, out var x7) && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
if (TakeOutParam(true, out var x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
if (TakeOutParam(true, out var x9))
{
Dummy(x9);
if (TakeOutParam(true, out var x9)) // 2
Dummy(x9);
}
}
void Test10()
{
if (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
void Test12()
{
if (TakeOutParam(y12, out var x12))
var y12 = 12;
}
//void Test13()
//{
// if (TakeOutParam(y13, out var x13))
// let y13 = 12;
//}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (101,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(101, 13),
// (36,17): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x3 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(36, 17),
// (46,40): error CS0128: A local variable named 'x4' is already defined in this scope
// if (TakeOutParam(true, out var x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(46, 40),
// (52,40): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (TakeOutParam(true, out var x5))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(52, 40),
// (58,13): error CS0841: Cannot use local variable 'x6' before it is declared
// if (x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(58, 13),
// (66,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(66, 17),
// (83,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(83, 19),
// (84,44): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (TakeOutParam(true, out var x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(84, 44),
// (91,26): error CS0103: The name 'y10' does not exist in the current context
// if (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(91, 26),
// (100,26): error CS0103: The name 'y12' does not exist in the current context
// if (TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(100, 26),
// (101,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(101, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
}
[Fact]
public void Scope_If_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
if (TakeOutParam(true, out var x1))
{
}
else
{
}
x1++;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_If_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (IfStatementSyntax)SyntaxFactory.ParseStatement(@"
if (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void If_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
Test(2);
}
public static void Test(int val)
{
if (Dummy(val == 1, TakeOutParam(val, out var x1), x1))
{
System.Console.WriteLine(""true"");
System.Console.WriteLine(x1);
}
else
{
System.Console.WriteLine(""false"");
System.Console.WriteLine(x1);
}
System.Console.WriteLine(x1);
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
true
1
1
2
false
2
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void If_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
if (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
;
if (f)
{
if (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_Lambda_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
System.Action<object> Test1()
{
return (o) => let x1 = o;
}
System.Action<object> Test2()
{
return (o) => let var x2 = o;
}
void Test3()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x3) && x3 > 0));
}
void Test4()
{
Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
}
void Test5()
{
Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0));
}
void Test6()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0));
}
void Test7()
{
Dummy(x7, 1);
Dummy(x7,
(System.Func<object, bool>) (o => TakeOutParam(o, out int x7) && x7 > 0),
x7);
Dummy(x7, 2);
}
void Test8()
{
Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out int y8) && x8));
}
void Test9()
{
Dummy(TakeOutParam(true, out var x9),
(System.Func<object, bool>) (o => TakeOutParam(o, out int x9) &&
x9 > 0), x9);
}
void Test10()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) &&
x10 > 0),
TakeOutParam(true, out var x10), x10);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) &&
x11 > 0), x11);
}
void Test12()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) &&
x12 > 0),
x12);
var x12 = 11;
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,89): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,89): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (59,73): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(59, 73),
// (65,73): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(65, 73),
// (74,73): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(74, 73),
// (80,73): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(80, 73),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
[Fact]
public void Lambda_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1);
return l();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_LocalDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d = Dummy(TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var d = Dummy(TakeOutParam(true, out var x4), x4);
}
void Test6()
{
var d = Dummy(x6 && TakeOutParam(true, out var x6));
}
void Test8()
{
var d = Dummy(TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,50): error CS0128: A local variable named 'x4' is already defined in this scope
// var d = Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// var d = Dummy(x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_LocalDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
object d = Dummy(TakeOutParam(true, out var x4), x4);
}
void Test6()
{
object d = Dummy(x6 && TakeOutParam(true, out var x6));
}
void Test8()
{
object d = Dummy(TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
object d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,53): error CS0128: A local variable named 'x4' is already defined in this scope
// object d = Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 53),
// (24,26): error CS0841: Cannot use local variable 'x6' before it is declared
// object d = Dummy(x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 26),
// (36,50): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 50)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_LocalDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var x1 =
Dummy(TakeOutParam(true, out var x1), x1);
Dummy(x1);
}
void Test2()
{
object x2 =
Dummy(TakeOutParam(true, out var x2), x2);
Dummy(x2);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (13,56): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
}
[Fact]
public void Scope_LocalDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(TakeOutParam(true, out var x1), x1),
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1 = Dummy(TakeOutParam(true, out var x2), x2),
d2 = Dummy(TakeOutParam(true, out var x2), x2);
}
void Test3()
{
object d1 = Dummy(TakeOutParam(true, out var x3), x3),
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 = Dummy(TakeOutParam(true, out var x4), x4);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_LocalDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y1 = Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Int64 y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
public void Scope_LocalDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d =TakeOutParam(true, out var x1) && x1 != null;
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d =TakeOutParam(true, out var x1) && x1 != null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d =TakeOutParam(true, out var x1) && x1 != null;").WithLocation(11, 13),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var d = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
public void LocalDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2);
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x1);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
a
c
b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void LocalDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
if (true)
{
object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1);
}
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (d, dd) = (TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var (d, dd) = (TakeOutParam(true, out var x4), x4);
}
void Test6()
{
var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1);
}
void Test8()
{
var (d, dd) = (TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var (d, dd, ddd) = (TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,51): error CS0128: A local variable named 'x4' is already defined in this scope
// var (d, dd) = (TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 51),
// (24,24): error CS0841: Cannot use local variable 'x6' before it is declared
// var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 24),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object dd) = (TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
(object d, object dd) = (TakeOutParam(true, out var x4), x4);
}
void Test6()
{
(object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1);
}
void Test8()
{
(object d, object dd) = (TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
(object d, object dd, object ddd) = (TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,61): error CS0128: A local variable named 'x4' is already defined in this scope
// (object d, object dd) = (TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 61),
// (24,34): error CS0841: Cannot use local variable 'x6' before it is declared
// (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 34),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (x1, dd) =
(TakeOutParam(true, out var x1), x1);
Dummy(x1);
}
void Test2()
{
(object x2, object dd) =
(TakeOutParam(true, out var x2), x2);
Dummy(x2);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// (TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (13,56): error CS0841: Cannot use local variable 'x1' before it is declared
// (TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// (TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// (TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Dummy(x1));
Dummy(x1);
}
void Test2()
{
(object d1, object d2) = (Dummy(TakeOutParam(true, out var x2), x2),
Dummy(TakeOutParam(true, out var x2), x2));
}
void Test3()
{
(object d1, object d2) = (Dummy(TakeOutParam(true, out var x3), x3),
Dummy(x3));
}
void Test4()
{
(object d1, object d2) = (Dummy(x4),
Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,67): error CS0128: A local variable named 'x1' is already defined in this scope
// (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 67),
// (12,72): error CS0165: Use of unassigned local variable 'x1'
// (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(12, 72),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,41): error CS0841: Cannot use local variable 'x4' before it is declared
// (object d1, object d2) = (Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyNotAnOutLocal(model, x1Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
var (y1, dd) = (TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Boolean y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var (d, dd) = (TakeOutParam(true, out var x1), x1);
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var d = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
(object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x1);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
a
c
b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
if (true)
{
(object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), x1);
}
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
var (d1, (d2, d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
(Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2),
Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3)));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(d3);
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
f
a
c
e
b
d
f");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Decl.Length);
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl[0], x3Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
(var d1, (var d2, var d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
(Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2),
Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3)));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(d3);
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
f
a
c
e
b
d
f");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Decl.Length);
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl[0], x3Ref);
}
[Fact]
public void Scope_Lock_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
lock (Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
lock (Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0))
Dummy(x4);
}
void Test6()
{
lock (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
lock (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
lock (Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
lock (Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
lock (Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// lock (Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
lock (Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// lock (Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
lock (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,48): error CS0128: A local variable named 'x4' is already defined in this scope
// lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(29, 48),
// (35,21): error CS0841: Cannot use local variable 'x6' before it is declared
// lock (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 21),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (60,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(60, 19),
// (61,52): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 52),
// (68,34): error CS0103: The name 'y10' does not exist in the current context
// lock (Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 34),
// (86,34): error CS0103: The name 'y12' does not exist in the current context
// lock (Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 34),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,45): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Lock_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
if (true)
lock (Dummy(TakeOutParam(true, out var x1)))
{
}
x1++;
}
static object TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Lock_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LockStatementSyntax)SyntaxFactory.ParseStatement(@"
lock (Dummy(TakeOutParam(true, out var x1), x1)) ;
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Lock_01()
{
var source =
@"
public class X
{
public static void Main()
{
lock (Dummy(TakeOutParam(""lock"", out var x1), x1))
{
System.Console.WriteLine(x1);
}
System.Console.WriteLine(x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"lock
lock
lock");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Lock_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
lock (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{}
if (f)
{
lock (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
{}
}
}
static object Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Scope_ParameterDefault_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0)
{}
void Test4(bool p = x4 && TakeOutParam(4, out int x4))
{}
void Test5(bool p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
{}
void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0)
{
}
void Test72(bool p = x7 > 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("p").WithLocation(8, 25),
// (11,25): error CS0841: Cannot use local variable 'x4' before it is declared
// void Test4(bool p = x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25),
// (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50),
// (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test5(bool p = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithArguments("p").WithLocation(14, 25),
// (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27),
// (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76),
// (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("p").WithLocation(22, 26),
// (26,26): error CS0103: The name 'x7' does not exist in the current context
// void Test72(bool p = x7 > 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26),
// (29,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IParameterInitializerOperation (Parameter: [System.Boolean p = default(System.Boolean)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... ) && x3 > 0')
Locals: Local_1: System.Int32 x3
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... ) && x3 > 0')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'x3 > 0')
Left:
ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
");
}
[Fact]
public void Scope_ParameterDefault_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0)
{}
void Test4(bool p = x4 && TakeOutParam(4, out var x4))
{}
void Test5(bool p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)
{}
void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
{}
void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0)
{
}
void Test72(bool p = x7 > 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out var x3) && x3 > 0").WithArguments("p").WithLocation(8, 25),
// (11,25): error CS0841: Cannot use local variable 'x4' before it is declared
// void Test4(bool p = x4 && TakeOutParam(4, out var x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25),
// (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50),
// (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test5(bool p = TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithArguments("p").WithLocation(14, 25),
// (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27),
// (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76),
// (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out var x7) && x7 > 0").WithArguments("p").WithLocation(22, 26),
// (26,26): error CS0103: The name 'x7' does not exist in the current context
// void Test72(bool p = x7 > 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26),
// (29,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_PropertyInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 {get;} = TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 {get;} = x4 && TakeOutParam(4, out int x4);
bool Test5 {get;} = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test62 {get;} = TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 {get;} = TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 {get;} = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,25): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 {get;} = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 25),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (19,32): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 {get;} = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 32),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void PropertyInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 52)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IPropertyInitializerOperation (Property: System.Boolean X.Test1 { get; }) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)')
Locals: Local_1: System.Int32 x1
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void PropertyInitializers_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static System.Func<bool> Test1 {get;} = () => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void PropertyInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
static bool a = false;
bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0;
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,63): error CS0165: Use of unassigned local variable 'x1'
// bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 63)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void PropertyInitializers_04()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(new X().Test1);
}
int Test1 { get; } = TakeOutParam(1, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")]
public void Scope_Query_01()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1}
select x + y1;
Dummy(y1);
}
void Test2()
{
var res = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0}
from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2}
select x1 + x2 + y2 +
z2;
Dummy(z2);
}
void Test3()
{
var res = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0}
let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0
select new { x1, x2, y3,
z3};
Dummy(z3);
}
void Test4()
{
var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
void Test6()
{
var res = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0}
where x > y6 && TakeOutParam(1, out var z6) && z6 == 1
select x + y6 +
z6;
Dummy(z6);
}
void Test7()
{
var res = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0}
orderby x > y7 && TakeOutParam(1, out var z7) && z7 ==
u7,
x > y7 && TakeOutParam(1, out var u7) && u7 ==
z7
select x + y7 +
z7 + u7;
Dummy(z7);
Dummy(u7);
}
void Test8()
{
var res = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0}
select x > y8 && TakeOutParam(1, out var z8) && z8 == 1;
Dummy(z8);
}
void Test9()
{
var res = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0}
group x > y9 && TakeOutParam(1, out var z9) && z9 ==
u9
by
x > y9 && TakeOutParam(1, out var u9) && u9 ==
z9;
Dummy(z9);
Dummy(u9);
}
void Test10()
{
var res = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0}
from y10 in new[] { 1 }
select x1 + y10;
}
void Test11()
{
var res = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0}
let y11 = x1 + 1
select x1 + y11;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,26): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(25, 26),
// (27,15): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(27, 15),
// (35,32): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(35, 32),
// (37,15): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(37, 15),
// (45,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(45, 35),
// (47,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(47, 35),
// (49,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(49, 32),
// (49,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(49, 36),
// (52,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(52, 15),
// (53,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(53, 15),
// (61,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(61, 35),
// (63,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(63, 35),
// (66,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(66, 32),
// (66,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(66, 36),
// (69,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(69, 15),
// (70,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(70, 15),
// (78,26): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(78, 26),
// (80,15): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(80, 15),
// (87,27): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(87, 27),
// (89,27): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(89, 27),
// (91,26): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(91, 26),
// (91,31): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(91, 31),
// (93,15): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(93, 15),
// (94,15): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(94, 15),
// (102,15): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(102, 15),
// (112,25): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(112, 25),
// (109,25): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(109, 25),
// (114,15): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(114, 15),
// (115,15): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(115, 15),
// (121,24): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10'
// from y10 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(121, 24),
// (128,23): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11'
// let y11 = x1 + 1
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(128, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutVar(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutVar(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutVar(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutVar(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutVar(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutVar(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutVar(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutVar(model, y10Decl, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutVar(model, y11Decl, y11Ref[0]);
VerifyNotAnOutLocal(model, y11Ref[1]);
}
[Fact]
public void Scope_Query_03()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
select x1 into x1
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
select x1 into x1
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4 , out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(18, 35),
// (20,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(20, 35),
// (22,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(22, 32),
// (22,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(22, 36),
// (25,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(25, 15),
// (26,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(26, 15),
// (35,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(35, 35),
// (37,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(37, 35),
// (40,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(40, 32),
// (40,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(40, 36),
// (43,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(43, 15),
// (44,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(44, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_05()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
int y1 = 0, y2 = 0, y3 = 0, y4 = 0, y5 = 0, y6 = 0, y7 = 0, y8 = 0, y9 = 0, y10 = 0, y11 = 0, y12 = 0;
var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on TakeOutParam(4, out var y4) ? y4 : 0
equals TakeOutParam(5, out var y5) ? y5 : 0
where TakeOutParam(6, out var y6) && y6 == 1
orderby TakeOutParam(7, out var y7) && y7 > 0,
TakeOutParam(8, out var y8) && y8 > 0
group TakeOutParam(9, out var y9) && y9 > 0
by TakeOutParam(10, out var y10) && y10 > 0
into g
let x11 = TakeOutParam(11, out var y11) && y11 > 0
select TakeOutParam(12, out var y12) && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12 + (TakeOutParam(13, out var y13) ? y13 : 0);
Dummy(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62),
// (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62),
// (17,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(17, 62),
// (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62),
// (19,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(4, out var y4) ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(19, 51),
// (20,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(5, out var y5) ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(20, 58),
// (21,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(6, out var y6) && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(21, 49),
// (22,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(7, out var y7) && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(22, 51),
// (23,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(8, out var y8) && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(23, 51),
// (25,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(10, out var y10) && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(25, 47),
// (24,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(9, out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(24, 49),
// (27,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = TakeOutParam(11, out var y11) && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(27, 54),
// (28,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(12, out var y12) && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(28, 51)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(3, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForOutVarDuplicateInSameScope(model, yDecl);
VerifyNotAnOutLocal(model, yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl, yRef[0]);
break;
}
VerifyNotAnOutLocal(model, yRef[2]);
switch (i)
{
case 12:
VerifyNotAnOutLocal(model, yRef[1]);
break;
default:
VerifyNotAnOutLocal(model, yRef[1]);
break;
}
}
var y13Decl = GetOutVarDeclarations(tree, "y13").Single();
var y13Ref = GetReference(tree, "y13");
VerifyModelForOutVar(model, y13Decl, y13Ref);
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_06()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(TakeOutParam(out int y1),
TakeOutParam(out int y2),
TakeOutParam(out int y3),
TakeOutParam(out int y4),
TakeOutParam(out int y5),
TakeOutParam(out int y6),
TakeOutParam(out int y7),
TakeOutParam(out int y8),
TakeOutParam(out int y9),
TakeOutParam(out int y10),
TakeOutParam(out int y11),
TakeOutParam(out int y12),
from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on TakeOutParam(4, out var y4) ? y4 : 0
equals TakeOutParam(5, out var y5) ? y5 : 0
where TakeOutParam(6, out var y6) && y6 == 1
orderby TakeOutParam(7, out var y7) && y7 > 0,
TakeOutParam(8, out var y8) && y8 > 0
group TakeOutParam(9, out var y9) && y9 > 0
by TakeOutParam(10, out var y10) && y10 > 0
into g
let x11 = TakeOutParam(11, out var y11) && y11 > 0
select TakeOutParam(12, out var y12) && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62),
// (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62),
// (27,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(27, 62),
// (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62),
// (29,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(4, out var y4) ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(29, 51),
// (30,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(5, out var y5) ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(30, 58),
// (31,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(6, out var y6) && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(31, 49),
// (32,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(7, out var y7) && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(32, 51),
// (33,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(8, out var y8) && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(33, 51),
// (35,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(10, out var y10) && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(35, 47),
// (34,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(9, out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(34, 49),
// (37,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = TakeOutParam(11, out var y11) && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(37, 54),
// (38,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(12, out var y12) && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(38, 51)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).ToArray();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForOutVar(model, yDecl[0], yRef);
VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]);
break;
case 12:
VerifyModelForOutVar(model, yDecl[0], yRef[1]);
VerifyModelForOutVar(model, yDecl[1], yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl[0], yRef[1]);
VerifyModelForOutVar(model, yDecl[1], yRef[0]);
break;
}
}
}
[Fact]
public void Scope_Query_07()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(TakeOutParam(out int y3),
from x1 in new[] { 0 }
select x1
into x1
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on x1 equals x3
select y3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,62): error CS0128: A local variable named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
const string id = "y3";
var yDecl = GetOutVarDeclarations(tree, id).ToArray();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
// Since the name is declared twice in the same scope,
// both references are to the same declaration.
VerifyModelForOutVar(model, yDecl[0], yRef);
VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]);
}
[Fact]
public void Scope_Query_08()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new[] { Dummy(TakeOutParam(out var y1),
TakeOutParam(out var y2),
TakeOutParam(out var y3),
TakeOutParam(out var y4)
) ? 1 : 0}
from y1 in new[] { 1 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by x1
into y4
select y4;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// from y1 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(19, 24),
// (20,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(20, 24),
// (22,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(22, 23),
// (25,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(25, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 5; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_09()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by 1
into y4
select y4 == null ? 1 : 0
into x2
join y5 in new[] { Dummy(TakeOutParam(out var y1),
TakeOutParam(out var y2),
TakeOutParam(out var y3),
TakeOutParam(out var y4),
TakeOutParam(out var y5)
) ? 1 : 0 }
on x2 equals y5
select x2;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// var res = from y1 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(14, 24),
// (15,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(15, 24),
// (17,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(17, 23),
// (20,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(20, 24),
// (23,24): error CS1931: The range variable 'y5' conflicts with a previous declaration of 'y5'
// join y5 in new[] { Dummy(TakeOutParam(out var y1),
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y5").WithArguments("y5").WithLocation(23, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 6; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
switch (i)
{
case 4:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
case 5:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
default:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
}
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
[WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void Scope_Query_10()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 }
select y1;
}
void Test2()
{
var res = from y2 in new[] { 0 }
join x3 in new[] { 1 }
on TakeOutParam(out var y2) ? y2 : 0
equals x3
select y2;
}
void Test3()
{
var res = from x3 in new[] { 0 }
join y3 in new[] { 1 }
on x3
equals TakeOutParam(out var y3) ? y3 : 0
select y3;
}
void Test4()
{
var res = from y4 in new[] { 0 }
where TakeOutParam(out var y4) && y4 == 1
select y4;
}
void Test5()
{
var res = from y5 in new[] { 0 }
orderby TakeOutParam(out var y5) && y5 > 1,
1
select y5;
}
void Test6()
{
var res = from y6 in new[] { 0 }
orderby 1,
TakeOutParam(out var y6) && y6 > 1
select y6;
}
void Test7()
{
var res = from y7 in new[] { 0 }
group TakeOutParam(out var y7) && y7 == 3
by y7;
}
void Test8()
{
var res = from y8 in new[] { 0 }
group y8
by TakeOutParam(out var y8) && y8 == 3;
}
void Test9()
{
var res = from y9 in new[] { 0 }
let x4 = TakeOutParam(out var y9) && y9 > 0
select y9;
}
void Test10()
{
var res = from y10 in new[] { 0 }
select TakeOutParam(out var y10) && y10 > 0;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// error CS0412 is misleading and reported due to preexisting bug https://github.com/dotnet/roslyn/issues/12052
compilation.VerifyDiagnostics(
// (15,59): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(15, 59),
// (23,48): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(out var y2) ? y2 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(23, 48),
// (33,52): error CS0136: A local or parameter named 'y3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(out var y3) ? y3 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y3").WithArguments("y3").WithLocation(33, 52),
// (40,46): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(out var y4) && y4 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(40, 46),
// (47,48): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(out var y5) && y5 > 1,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(47, 48),
// (56,48): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(out var y6) && y6 > 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(56, 48),
// (63,46): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(out var y7) && y7 == 3
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(63, 46),
// (71,43): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(out var y8) && y8 == 3;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(71, 43),
// (77,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x4 = TakeOutParam(out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(77, 49),
// (84,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(out var y10) && y10 > 0;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(84, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 11; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(i == 10 ? 1 : 2, yRef.Length);
switch (i)
{
case 4:
case 6:
VerifyModelForOutVar(model, yDecl, yRef[0]);
VerifyNotAnOutLocal(model, yRef[1]);
break;
case 8:
VerifyModelForOutVar(model, yDecl, yRef[1]);
VerifyNotAnOutLocal(model, yRef[0]);
break;
case 10:
VerifyModelForOutVar(model, yDecl, yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl, yRef[0]);
VerifyNotAnOutLocal(model, yRef[1]);
break;
}
}
}
[Fact]
public void Scope_Query_11()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new [] { 1 }
where Dummy(TakeOutParam(x1, out var y1),
from x2 in new [] { y1 }
where TakeOutParam(x1, out var y1)
select x2)
select x1;
}
void Test2()
{
var res = from x1 in new [] { 1 }
where Dummy(TakeOutParam(x1, out var y2),
TakeOutParam(x1 + 1, out var y2))
select x1;
}
void Test3()
{
var res = from x1 in new [] { 1 }
where TakeOutParam(out int y3, y3)
select x1;
}
void Test4()
{
var res = from x1 in new [] { 1 }
where TakeOutParam(out var y4, y4)
select x1;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x, int y)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope
// TakeOutParam(x1 + 1, out var y2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60),
// (33,50): error CS0165: Use of unassigned local variable 'y3'
// where TakeOutParam(out int y3, y3)
Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50),
// (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list.
// where TakeOutParam(out var y4, y4)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (17,62): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(x1, out var y1)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(17, 62),
// (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope
// TakeOutParam(x1 + 1, out var y2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60),
// (33,50): error CS0165: Use of unassigned local variable 'y3'
// where TakeOutParam(out int y3, y3)
Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50),
// (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list.
// where TakeOutParam(out var y4, y4)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").ToArray();
var y1Ref = GetReferences(tree, "y1").Single();
Assert.Equal(2, y1Decl.Length);
VerifyModelForOutVar(model, y1Decl[0], y1Ref);
VerifyModelForOutVar(model, y1Decl[1]);
var y2Decl = GetOutVarDeclarations(tree, "y2").ToArray();
Assert.Equal(2, y2Decl.Length);
VerifyModelForOutVar(model, y2Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, y2Decl[1]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").Single();
VerifyModelForOutVarWithoutDataFlow(model, y3Decl, y3Ref);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").Single();
VerifyModelForOutVarWithoutDataFlow(model, y4Decl, y4Ref);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")]
public void Query_01()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
Test1();
}
static void Test1()
{
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) && Print(y2) ? 1 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) && Print(y3) ? 1 : 0}
on TakeOutParam(4, out var y4) && Print(y4) ? 1 : 0
equals TakeOutParam(5, out var y5) && Print(y5) ? 1 : 0
where TakeOutParam(6, out var y6) && Print(y6)
orderby TakeOutParam(7, out var y7) && Print(y7),
TakeOutParam(8, out var y8) && Print(y8)
group TakeOutParam(9, out var y9) && Print(y9)
by TakeOutParam(10, out var y10) && Print(y10)
into g
let x11 = TakeOutParam(11, out var y11) && Print(y11)
select TakeOutParam(12, out var y12) && Print(y12);
res.ToArray();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput:
@"1
3
5
2
4
6
7
8
10
9
11
12
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
VerifyModelForOutVar(model, yDecl, yRef);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(yDecl))).Type.ToTestDisplayString());
}
}
[Fact]
public void Query_02()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
Test1();
}
static void Test1()
{
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0}
select Print(x1);
res.ToArray();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetOutVarDeclarations(tree, "y1").Single();
var yRef = GetReferences(tree, "y1").Single();
VerifyModelForOutVar(model, yDecl, yRef);
}
[Fact]
public void Query_03()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
static void Test1()
{
var res = from a in new[] { true }
select a && TakeOutParam(3, out int x1) || x1 > 0;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,62): error CS0165: Use of unassigned local variable 'x1'
// select a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 62)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
compilation.VerifyOperationTree(x1Decl, expectedOperationTree:
@"
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
");
}
[Fact]
public void Query_04()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static int Test1()
{
var res = from a in new[] { 1 }
select TakeOutParam(a, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
return res.Single();
}
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Query_05()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
static void Test1()
{
var res = from a in (new[] { 1 }).AsQueryable()
select TakeOutParam(a, out int x1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,46): error CS8198: An expression tree may not contain an out argument variable declaration.
// select TakeOutParam(a, out int x1);
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x1").WithLocation(13, 46)
);
}
[Fact]
public void Scope_ReturnStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null; }
object Test1()
{
return Dummy(TakeOutParam(true, out var x1), x1);
{
return Dummy(TakeOutParam(true, out var x1), x1);
}
return Dummy(TakeOutParam(true, out var x1), x1);
}
object Test2()
{
return Dummy(x2, TakeOutParam(true, out var x2));
}
object Test3(int x3)
{
return Dummy(TakeOutParam(true, out var x3), x3);
}
object Test4()
{
var x4 = 11;
Dummy(x4);
return Dummy(TakeOutParam(true, out var x4), x4);
}
object Test5()
{
return Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//object Test6()
//{
// let x6 = 11;
// Dummy(x6);
// return Dummy(TakeOutParam(true, out var x6), x6);
//}
//object Test7()
//{
// return Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
object Test8()
{
return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
object Test9(bool y9)
{
if (y9)
return Dummy(TakeOutParam(true, out var x9), x9);
return null;
}
System.Func<object> Test10(bool y10)
{
return () =>
{
if (y10)
return Dummy(TakeOutParam(true, out var x10), x10);
return null;};
}
object Test11()
{
Dummy(x11);
return Dummy(TakeOutParam(true, out var x11), x11);
}
object Test12()
{
return Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,53): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 53),
// (16,49): error CS0128: A local variable or function named 'x1' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 49),
// (14,13): warning CS0162: Unreachable code detected
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(14, 13),
// (21,22): error CS0841: Cannot use local variable 'x2' before it is declared
// return Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 22),
// (26,49): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 49),
// (33,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 49),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,86): error CS0128: A local variable or function named 'x8' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 86),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ReturnStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
int Dummy(params object[] x) { return 0;}
int Test1(bool val)
{
if (val)
return Dummy(TakeOutParam(true, out var x1));
x1++;
return 0;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ReturnStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ReturnStatementSyntax)SyntaxFactory.ParseStatement(@"
return Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Return_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test();
}
static object Test()
{
return Dummy(TakeOutParam(""return"", out var x1), x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"return");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Return_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(true);
Test(false);
}
static object Test(bool val)
{
if (val)
return Dummy(TakeOutParam(""return 1"", out var x2), x2);
if (!val)
{
return Dummy(TakeOutParam(""return 2"", out var x2), x2);
}
return null;
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"return 1
return 2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]);
VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]);
}
[Fact]
public void Scope_Switch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
switch (TakeOutParam(1, out var x1) ? x1 : 0)
{
case 0:
Dummy(x1, 0);
break;
}
Dummy(x1, 1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
switch (TakeOutParam(4, out var x4) ? x4 : 0)
{
case 4:
Dummy(x4);
break;
}
}
void Test5(int x5)
{
switch (TakeOutParam(5, out var x5) ? x5 : 0)
{
case 5:
Dummy(x5);
break;
}
}
void Test6()
{
switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0))
{
case 6:
Dummy(x6);
break;
}
}
void Test7()
{
switch (TakeOutParam(7, out var x7) ? x7 : 0)
{
case 7:
var x7 = 12;
Dummy(x7);
break;
}
}
void Test9()
{
switch (TakeOutParam(9, out var x9) ? x9 : 0)
{
case 9:
Dummy(x9, 0);
switch (TakeOutParam(9, out var x9) ? x9 : 0)
{
case 9:
Dummy(x9, 1);
break;
}
break;
}
}
void Test10()
{
switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0))
{
case 10:
var y10 = 12;
Dummy(y10);
break;
}
}
//void Test11()
//{
// switch (y11 + (TakeOutParam(11, out var x11) ? x11 : 0))
// {
// case 11:
// let y11 = 12;
// Dummy(y11);
// break;
// }
//}
void Test14()
{
switch (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14) ? 1 : 0)
{
case 0:
Dummy(x14);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (27,41): error CS0128: A local variable named 'x4' is already defined in this scope
// switch (TakeOutParam(4, out var x4) ? x4 : 0)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(27, 41),
// (37,41): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (TakeOutParam(5, out var x5) ? x5 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(37, 41),
// (47,17): error CS0841: Cannot use local variable 'x6' before it is declared
// switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(47, 17),
// (60,21): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(60, 21),
// (71,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9, 0);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(71, 23),
// (72,49): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (TakeOutParam(9, out var x9) ? x9 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(72, 49),
// (85,17): error CS0103: The name 'y10' does not exist in the current context
// switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 17),
// (108,43): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(108, 43)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(3, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Switch_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
switch (TakeOutParam(1, out var x1) ? 1 : 0)
{
case 0:
break;
}
Dummy(x1, 1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,15): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(19, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Switch_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@"
switch (Dummy(TakeOutParam(true, out var x1), x1)) {}
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Switch_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test1(0);
Test1(1);
}
static bool Dummy1(bool val, params object[] x) {return val;}
static T Dummy2<T>(T val, params object[] x) {return val;}
static void Test1(int val)
{
switch (Dummy2(val, TakeOutParam(""Test1 {0}"", out var x1)))
{
case 0 when Dummy1(true, TakeOutParam(""case 0"", out var y1)):
System.Console.WriteLine(x1, y1);
break;
case int z1:
System.Console.WriteLine(x1, z1);
break;
}
System.Console.WriteLine(x1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"Test1 case 0
Test1 {0}
Test1 1
Test1 {0}");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Switch_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
switch (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{}
if (f)
{
switch (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
{}
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_SwitchLabelGuard_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test1(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
case 1 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
case 2 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
}
}
void Test2(int val)
{
switch (val)
{
case 0 when Dummy(x2, TakeOutParam(true, out var x2)):
Dummy(x2);
break;
}
}
void Test3(int x3, int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x3), x3):
Dummy(x3);
break;
}
}
void Test4(int val)
{
var x4 = 11;
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x4), x4):
Dummy(x4);
break;
case 1 when Dummy(x4): Dummy(x4); break;
}
}
void Test5(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x5), x5):
Dummy(x5);
break;
}
var x5 = 11;
Dummy(x5);
}
//void Test6(int val)
//{
// let x6 = 11;
// switch (val)
// {
// case 0 when Dummy(x6):
// Dummy(x6);
// break;
// case 1 when Dummy(TakeOutParam(true, out var x6), x6):
// Dummy(x6);
// break;
// }
//}
//void Test7(int val)
//{
// switch (val)
// {
// case 0 when Dummy(TakeOutParam(true, out var x7), x7):
// Dummy(x7);
// break;
// }
// let x7 = 11;
// Dummy(x7);
//}
void Test8(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8):
Dummy(x8);
break;
}
}
void Test9(int val)
{
switch (val)
{
case 0 when Dummy(x9):
int x9 = 9;
Dummy(x9);
break;
case 2 when Dummy(x9 = 9):
Dummy(x9);
break;
case 1 when Dummy(TakeOutParam(true, out var x9), x9):
Dummy(x9);
break;
}
}
//void Test10(int val)
//{
// switch (val)
// {
// case 1 when Dummy(TakeOutParam(true, out var x10), x10):
// Dummy(x10);
// break;
// case 0 when Dummy(x10):
// let x10 = 10;
// Dummy(x10);
// break;
// case 2 when Dummy(x10 = 10, x10):
// Dummy(x10);
// break;
// }
//}
void Test11(int val)
{
switch (x11 ? val : 0)
{
case 0 when Dummy(x11):
Dummy(x11, 0);
break;
case 1 when Dummy(TakeOutParam(true, out var x11), x11):
Dummy(x11, 1);
break;
}
}
void Test12(int val)
{
switch (x12 ? val : 0)
{
case 0 when Dummy(TakeOutParam(true, out var x12), x12):
Dummy(x12, 0);
break;
case 1 when Dummy(x12):
Dummy(x12, 1);
break;
}
}
void Test13()
{
switch (TakeOutParam(1, out var x13) ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case 1 when Dummy(TakeOutParam(true, out var x13), x13):
Dummy(x13);
break;
}
}
void Test14(int val)
{
switch (val)
{
case 1 when Dummy(TakeOutParam(true, out var x14), x14):
Dummy(x14);
Dummy(TakeOutParam(true, out var x14), x14);
Dummy(x14);
break;
}
}
void Test15(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x15), x15):
case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Dummy(x15);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (30,31): error CS0841: Cannot use local variable 'x2' before it is declared
// case 0 when Dummy(x2, TakeOutParam(true, out var x2)):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31),
// (40,58): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x3), x3):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(40, 58),
// (51,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x4), x4):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(51, 58),
// (62,58): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x5), x5):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(62, 58),
// (102,95): error CS0128: A local variable named 'x8' is already defined in this scope
// case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(102, 95),
// (112,31): error CS0841: Cannot use local variable 'x9' before it is declared
// case 0 when Dummy(x9):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(112, 31),
// (119,58): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x9), x9):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(119, 58),
// (144,17): error CS0103: The name 'x11' does not exist in the current context
// switch (x11 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(144, 17),
// (146,31): error CS0103: The name 'x11' does not exist in the current context
// case 0 when Dummy(x11):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 31),
// (147,23): error CS0103: The name 'x11' does not exist in the current context
// Dummy(x11, 0);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(147, 23),
// (157,17): error CS0103: The name 'x12' does not exist in the current context
// switch (x12 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(157, 17),
// (162,31): error CS0103: The name 'x12' does not exist in the current context
// case 1 when Dummy(x12):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(162, 31),
// (163,23): error CS0103: The name 'x12' does not exist in the current context
// Dummy(x12, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(163, 23),
// (175,58): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x13), x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(175, 58),
// (185,58): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x14), x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(185, 58),
// (198,58): error CS0128: A local variable named 'x15' is already defined in this scope
// case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(198, 58),
// (198,64): error CS0165: Use of unassigned local variable 'x15'
// case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(198, 64)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(6, x1Ref.Length);
for (int i = 0; i < x1Decl.Length; i++)
{
VerifyModelForOutVar(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]);
}
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(4, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref[0], x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyNotAnOutLocal(model, x4Ref[3]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref[0], x5Ref[1]);
VerifyNotAnOutLocal(model, x5Ref[2]);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(6, x9Ref.Length);
VerifyNotAnOutLocal(model, x9Ref[0]);
VerifyNotAnOutLocal(model, x9Ref[1]);
VerifyNotAnOutLocal(model, x9Ref[2]);
VerifyNotAnOutLocal(model, x9Ref[3]);
VerifyModelForOutVar(model, x9Decl, x9Ref[4], x9Ref[5]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(5, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyNotInScope(model, x11Ref[1]);
VerifyNotInScope(model, x11Ref[2]);
VerifyModelForOutVar(model, x11Decl, x11Ref[3], x11Ref[4]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(5, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForOutVar(model, x12Decl, x12Ref[1], x12Ref[2]);
VerifyNotInScope(model, x12Ref[3]);
VerifyNotInScope(model, x12Ref[4]);
var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(5, x13Ref.Length);
VerifyModelForOutVar(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyModelForOutVar(model, x13Decl[1], x13Ref[3], x13Ref[4]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVar(model, x14Decl[1], isDelegateCreation: false, isExecutableCode: true, isShadowed: true);
var x15Decl = GetOutVarDeclarations(tree, "x15").ToArray();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Decl.Length);
Assert.Equal(3, x15Ref.Length);
for (int i = 0; i < x15Ref.Length; i++)
{
VerifyModelForOutVar(model, x15Decl[0], x15Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl[1]);
}
[Fact]
public void Scope_SwitchLabelGuard_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_03()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
while (TakeOutParam(x1, out var y1) && Print(y1)) break;
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return false;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_04()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
do
val = 0;
while (TakeOutParam(x1, out var y1) && Print(y1));
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return false;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_05()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
lock ((object)TakeOutParam(x1, out var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_06()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
if (TakeOutParam(x1, out var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_07()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
switch (TakeOutParam(x1, out var y1))
{
default: break;
}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_08()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var x in Test(1)) {}
}
static System.Collections.IEnumerable Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
yield return TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_09()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var z1 = x1 > 0 & TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_10()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
a: TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (14,1): warning CS0164: This label has not been referenced
// a: TakeOutParam(x1, out var y1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(14, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_11()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static bool Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
return TakeOutParam(x1, out var y1) && Print(y1);
System.Console.WriteLine(y1);
break;
}
return false;
}
static bool Print<T>(T x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (15,17): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(15, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_12()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static bool Test(int val)
{
try
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
throw Dummy(TakeOutParam(x1, out var y1), y1);
System.Console.WriteLine(y1);
break;
}
}
catch
{}
return false;
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (17,21): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(17, 21)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_13()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var (z0, z1) = (x1 > 0, TakeOutParam(x1, out var y1));
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_14()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var (z0, (z1, z2)) = (x1 > 0, (TakeOutParam(x1, out var y1), true));
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelPattern_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test8(object val)
{
switch (val)
{
case int x8
when Dummy(x8, TakeOutParam(false, out var x8), x8):
Dummy(x8);
break;
}
}
void Test13()
{
switch (TakeOutParam(1, out var x13) ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case int x13 when Dummy(x13):
Dummy(x13);
break;
}
}
void Test14(object val)
{
switch (val)
{
case int x14 when Dummy(x14):
Dummy(x14);
Dummy(TakeOutParam(true, out var x14), x14);
Dummy(x14);
break;
}
}
void Test16(object val)
{
switch (val)
{
case int x16 when Dummy(x16):
case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Dummy(x16);
break;
}
}
void Test17(object val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x17), x17):
case int x17 when Dummy(x17):
Dummy(x17);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,64): error CS0128: A local variable named 'x8' is already defined in this scope
// when Dummy(x8, TakeOutParam(false, out var x8), x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(15, 64),
// (28,22): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x13 when Dummy(x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(28, 22),
// (38,22): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x14 when Dummy(x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(38, 22),
// (51,58): error CS0128: A local variable named 'x16' is already defined in this scope
// case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x16").WithArguments("x16").WithLocation(51, 58),
// (51,64): error CS0165: Use of unassigned local variable 'x16'
// case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x16").WithArguments("x16").WithLocation(51, 64),
// (62,22): error CS0128: A local variable named 'x17' is already defined in this scope
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x17").WithArguments("x17").WithLocation(62, 22),
// (62,37): error CS0165: Use of unassigned local variable 'x17'
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(62, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyNotAnOutLocal(model, x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl);
var x13Decl = GetOutVarDeclarations(tree, "x13").Single();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(5, x13Ref.Length);
VerifyModelForOutVar(model, x13Decl, x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyNotAnOutLocal(model, x13Ref[3]);
VerifyNotAnOutLocal(model, x13Ref[4]);
var x14Decl = GetOutVarDeclarations(tree, "x14").Single();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(4, x14Ref.Length);
VerifyNotAnOutLocal(model, x14Ref[0]);
VerifyNotAnOutLocal(model, x14Ref[1]);
VerifyNotAnOutLocal(model, x14Ref[2]);
VerifyNotAnOutLocal(model, x14Ref[3]);
VerifyModelForOutVar(model, x14Decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: true);
var x16Decl = GetOutVarDeclarations(tree, "x16").Single();
var x16Ref = GetReferences(tree, "x16").ToArray();
Assert.Equal(3, x16Ref.Length);
for (int i = 0; i < x16Ref.Length; i++)
{
VerifyNotAnOutLocal(model, x16Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x16Decl);
var x17Decl = GetOutVarDeclarations(tree, "x17").Single();
var x17Ref = GetReferences(tree, "x17").ToArray();
Assert.Equal(3, x17Ref.Length);
VerifyModelForOutVar(model, x17Decl, x17Ref);
}
[Fact]
public void Scope_ThrowStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1()
{
throw Dummy(TakeOutParam(true, out var x1), x1);
{
throw Dummy(TakeOutParam(true, out var x1), x1);
}
throw Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
throw Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
throw Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
throw Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
throw Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// throw Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
// throw Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
throw Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
throw Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
throw Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
throw Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,52): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 52),
// (16,48): error CS0128: A local variable or function named 'x1' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 48),
// (21,21): error CS0841: Cannot use local variable 'x2' before it is declared
// throw Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 21),
// (26,48): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 48),
// (33,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 48),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,85): error CS0128: A local variable or function named 'x8' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 85),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ThrowStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1(bool val)
{
if (val)
throw Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ThrowStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ThrowStatementSyntax)SyntaxFactory.ParseStatement(@"
throw Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Throw_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test();
}
static void Test()
{
try
{
throw Dummy(TakeOutParam(""throw"", out var x2), x2);
}
catch
{
}
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"throw");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(1, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
}
[Fact]
public void Throw_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(true);
Test(false);
}
static void Test(bool val)
{
try
{
if (val)
throw Dummy(TakeOutParam(""throw 1"", out var x2), x2);
if (!val)
{
throw Dummy(TakeOutParam(""throw 2"", out var x2), x2);
}
}
catch
{
}
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"throw 1
throw 2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]);
VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]);
}
[Fact]
public void Scope_Using_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,49): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 49),
// (35,22): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 22),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,53): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 53),
// (68,35): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 35),
// (86,35): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 35),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,46): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (var d = Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d = Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (var d = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (var d = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d = Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d = Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d = Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d = Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d = Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (var d = Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (var d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d = Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61),
// (68,43): error CS0103: The name 'y10' does not exist in the current context
// using (var d = Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43),
// (86,43): error CS0103: The name 'y12' does not exist in the current context
// using (var d = Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,54): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (System.IDisposable d = Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (System.IDisposable d = Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (System.IDisposable d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,72): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 72),
// (35,45): error CS0841: Cannot use local variable 'x6' before it is declared
// using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 45),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,76): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 76),
// (68,58): error CS0103: The name 'y10' does not exist in the current context
// using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 58),
// (86,58): error CS0103: The name 'y12' does not exist in the current context
// using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 58),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,69): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 69)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
{
Dummy(x2);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,58): error CS0128: A local variable named 'x1' is already defined in this scope
// using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58),
// (12,63): error CS0841: Cannot use local variable 'x1' before it is declared
// using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(12, 63),
// (20,73): error CS0128: A local variable named 'x2' is already defined in this scope
// using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73),
// (20,78): error CS0165: Use of unassigned local variable 'x2'
// using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 78)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
}
[Fact]
public void Scope_Using_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1),
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x2), x2),
d2 = Dummy(TakeOutParam(true, out var x2), x2))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x3), x3),
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2 = Dummy(TakeOutParam(true, out var x4), x4))
{
Dummy(x4);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,35): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,73): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
public void Using_01()
{
var source =
@"
public class X
{
public static void Main()
{
using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2)))
{
System.Console.WriteLine(d1);
System.Console.WriteLine(x1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x2);
}
using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1)))
{
System.Console.WriteLine(x1);
}
}
static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C : System.IDisposable
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public void Dispose()
{
System.Console.WriteLine(""Disposing {0}"", _val);
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"a
b
c
d
Disposing c
Disposing a
f
Disposing e");
}
[Fact]
public void Scope_While_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
while (TakeOutParam(true, out var x1) && x1)
{
Dummy(x1);
}
}
void Test2()
{
while (TakeOutParam(true, out var x2) && x2)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
while (TakeOutParam(true, out var x4) && x4)
Dummy(x4);
}
void Test6()
{
while (x6 && TakeOutParam(true, out var x6))
Dummy(x6);
}
void Test7()
{
while (TakeOutParam(true, out var x7) && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
while (TakeOutParam(true, out var x8) && x8)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
while (TakeOutParam(true, out var x9) && x9)
{
Dummy(x9);
while (TakeOutParam(true, out var x9) && x9) // 2
Dummy(x9);
}
}
void Test10()
{
while (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// while (TakeOutParam(y11, out var x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
while (TakeOutParam(y12, out var x12))
var y12 = 12;
}
//void Test13()
//{
// while (TakeOutParam(y13, out var x13))
// let y13 = 12;
//}
void Test14()
{
while (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43),
// (35,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 16),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 47),
// (68,29): error CS0103: The name 'y10' does not exist in the current context
// while (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 29),
// (86,29): error CS0103: The name 'y12' does not exist in the current context
// while (TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 29),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,46): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_While_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
while (TakeOutParam(true, out var x1))
{
;
}
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_While_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (WhileStatementSyntax)SyntaxFactory.ParseStatement(@"
while (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void While_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{
System.Console.WriteLine(x1);
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
1
2
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
f = false;
f = true;
if (f)
{
while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
4");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void While_03()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1))
{
l.Add(() => System.Console.WriteLine(x1));
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
2
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_04()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1)))
{
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
2
3
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_05()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1)))
{
l.Add(() => System.Console.WriteLine(x1));
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
1
2
2
3
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_Yield_01()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null;}
IEnumerable Test1()
{
yield return Dummy(TakeOutParam(true, out var x1), x1);
{
yield return Dummy(TakeOutParam(true, out var x1), x1);
}
yield return Dummy(TakeOutParam(true, out var x1), x1);
}
IEnumerable Test2()
{
yield return Dummy(x2, TakeOutParam(true, out var x2));
}
IEnumerable Test3(int x3)
{
yield return Dummy(TakeOutParam(true, out var x3), x3);
}
IEnumerable Test4()
{
var x4 = 11;
Dummy(x4);
yield return Dummy(TakeOutParam(true, out var x4), x4);
}
IEnumerable Test5()
{
yield return Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//IEnumerable Test6()
//{
// let x6 = 11;
// Dummy(x6);
// yield return Dummy(TakeOutParam(true, out var x6), x6);
//}
//IEnumerable Test7()
//{
// yield return Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
IEnumerable Test8()
{
yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
IEnumerable Test9(bool y9)
{
if (y9)
yield return Dummy(TakeOutParam(true, out var x9), x9);
}
IEnumerable Test11()
{
Dummy(x11);
yield return Dummy(TakeOutParam(true, out var x11), x11);
}
IEnumerable Test12()
{
yield return Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (16,59): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(16, 59),
// (18,55): error CS0128: A local variable or function named 'x1' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(18, 55),
// (23,28): error CS0841: Cannot use local variable 'x2' before it is declared
// yield return Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(23, 28),
// (28,55): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(28, 55),
// (35,55): error CS0128: A local variable or function named 'x4' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(35, 55),
// (41,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(41, 13),
// (41,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(41, 13),
// (61,92): error CS0128: A local variable or function named 'x8' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(61, 92),
// (72,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(72, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_Yield_02()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
IEnumerable Test1()
{
if (true)
yield return TakeOutParam(true, out var x1);
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Yield_03()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
IEnumerable Test1()
{
yield return 0;
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (YieldStatementSyntax)SyntaxFactory.ParseStatement(@"
yield return Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Yield_01()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var o in Test())
{}
}
static System.Collections.IEnumerable Test()
{
yield return Dummy(TakeOutParam(""yield1"", out var x1), x1);
yield return Dummy(TakeOutParam(""yield2"", out var x2), x2);
System.Console.WriteLine(x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"yield1
yield2
yield1");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Yield_02()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var o in Test())
{}
}
static System.Collections.IEnumerable Test()
{
bool f = true;
if (f)
yield return Dummy(TakeOutParam(""yield1"", out var x1), x1);
if (f)
{
yield return Dummy(TakeOutParam(""yield2"", out var x1), x1);
}
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"yield1
yield2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_LabeledStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
a: Dummy(TakeOutParam(true, out var x1), x1);
{
b: Dummy(TakeOutParam(true, out var x1), x1);
}
c: Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
a: Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
a: Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
a: Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
a: Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
//a: Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
//a: Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
a: Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
a: Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
a: Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
a: Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// b: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46),
// (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope
// c: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42),
// (12,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(12, 1),
// (14,1): warning CS0164: This label has not been referenced
// b: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(14, 1),
// (16,1): warning CS0164: This label has not been referenced
// c: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(16, 1),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// a: Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (21,1): warning CS0164: This label has not been referenced
// a: Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(21, 1),
// (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// a: Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42),
// (26,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(26, 1),
// (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// a: Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42),
// (33,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(33, 1),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (38,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x5), x5);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(38, 1),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope
// a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79),
// (59,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(59, 1),
// (65,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x9), x9);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x9), x9);").WithLocation(65, 1),
// (65,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x9), x9);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(65, 1),
// (73,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x10), x10);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x10), x10);").WithLocation(73, 1),
// (73,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x10), x10);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(73, 1),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (80,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x11), x11);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(80, 1),
// (85,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x12), x12);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(85, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_LabeledStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
a: Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x1));
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x1));").WithLocation(13, 1),
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9),
// (13,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_LabeledStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LabeledStatementSyntax)SyntaxFactory.ParseStatement(@"
a: b: Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Labeled_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
a: b: c:Test2(Test1(out int x1), x1);
System.Console.Write(x1);
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics(
// (11,1): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(11, 1),
// (11,4): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(11, 4),
// (11,7): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(11, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Labeled_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
bool test = true;
if (test)
{
a: Test2(Test1(out int x1), x1);
}
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics(
// (15,1): warning CS0164: This label has not been referenced
// a: Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(15, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void DataFlow_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1,
x1);
}
static void Test(out int x, int y)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,22): error CS0165: Use of unassigned local variable 'x1'
// x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void DataFlow_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1,
ref x1);
}
static void Test(out int x, ref int y)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,22): error CS0165: Use of unassigned local variable 'x1'
// ref x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void DataFlow_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1);
var x2 = 1;
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,13): warning CS0219: The variable 'x2' is assigned but its value is never used
// var x2 = 1;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(7, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single();
var dataFlow = model.AnalyzeDataFlow(x2Decl);
Assert.True(dataFlow.Succeeded);
Assert.Equal("System.Int32 x2", dataFlow.VariablesDeclared.Single().ToTestDisplayString());
Assert.Equal("System.Int32 x1", dataFlow.WrittenOutside.Single().ToTestDisplayString());
}
[Fact]
public void TypeMismatch_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1);
}
static void Test(out short x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,18): error CS1503: Argument 1: cannot convert from 'out int' to 'out short'
// Test(out int x1);
Diagnostic(ErrorCode.ERR_BadArgType, "int x1").WithArguments("1", "out int", "out short").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[Fact]
public void Parse_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(int x1);
Test(ref int x2);
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,14): error CS1525: Invalid expression term 'int'
// Test(int x1);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 14),
// (6,18): error CS1003: Syntax error, ',' expected
// Test(int x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 18),
// (7,18): error CS1525: Invalid expression term 'int'
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18),
// (7,22): error CS1003: Syntax error, ',' expected
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_SyntaxError, "x2").WithArguments(",", "").WithLocation(7, 22),
// (6,18): error CS0103: The name 'x1' does not exist in the current context
// Test(int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 18),
// (7,22): error CS0103: The name 'x2' does not exist in the current context
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree).Any());
}
[Fact]
public void Parse_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1.);
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,24): error CS1003: Syntax error, ',' expected
// Test(out int x1.);
Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",", ".").WithLocation(6, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[Fact]
public void Parse_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out System.Collections.Generic.IEnumerable<System.Int32>);
}
static void Test(out System.Collections.Generic.IEnumerable<System.Int32> x)
{
x = null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,18): error CS0118: 'IEnumerable<int>' is a type but is used like a variable
// Test(out System.Collections.Generic.IEnumerable<System.Int32>);
Diagnostic(ErrorCode.ERR_BadSKknown, "System.Collections.Generic.IEnumerable<System.Int32>").WithArguments("System.Collections.Generic.IEnumerable<int>", "type", "variable").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree).Any());
}
[Fact]
public void GetAliasInfo_01()
{
var text = @"
using a = System.Int32;
public class Cls
{
public static void Main()
{
Test1(out a x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GetAliasInfo_02()
{
var text = @"
using var = System.Int32;
public class Cls
{
public static void Main()
{
Test1(out var x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void VarIsNotVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out var x)
{
x = new var() {val = 123};
return null;
}
static void Test2(object x, var y)
{
System.Console.WriteLine(y.val);
}
struct var
{
public int val;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void VarIsNotVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1);
}
struct var
{
public int val;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0103: The name 'Test1' does not exist in the current context
// Test1(out var x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 9),
// (11,20): warning CS0649: Field 'Cls.var.val' is never assigned to, and will always have its default value 0
// public int val;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "val").WithArguments("Cls.var.val", "0").WithLocation(11, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("Cls.var", ((ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void SimpleVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void SimpleVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static void Test2(object x, object y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,15): error CS0103: The name 'Test1' does not exist in the current context
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void SimpleVar_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1,
out x1);
}
static object Test1(out int x, out int x2)
{
x = 123;
x2 = 124;
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,23): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list.
// out x1);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1,
Test1(out x1,
3));
}
static object Test1(out int x, int x2)
{
x = 123;
x2 = 124;
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,25): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list.
// Test1(out x1,
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(ref int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,25): error CS1620: Argument 1 must be passed with the 'ref' keyword
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadArgRef, "var x1").WithArguments("1", "ref").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,25): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_07()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic x = null;
Test2(x.Test1(out var x1),
x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,31): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(x.Test1(out var x1),
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 31)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new Test1(out var x1), x1);
}
class Test1
{
public Test1(out int x)
{
x = 123;
}
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void SimpleVar_09()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new System.Action(out var x1),
x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,37): error CS0149: Method name expected
// Test2(new System.Action(out var x1),
Diagnostic(ErrorCode.ERR_MethodNameExpected, "var x1").WithLocation(6, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, isDelegateCreation: true, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void ConstructorInitializers_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x, object y)
{
System.Console.WriteLine(y);
}
public Test2()
: this(Test1(out var x1), x1)
{}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (25,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// : this(Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(25, 26)
);
var initializer = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
var typeInfo = model.GetTypeInfo(initializer);
var symbolInfo = model.GetSymbolInfo(initializer);
var group = model.GetMemberGroup(initializer);
Assert.Equal("System.Void", typeInfo.Type.ToTestDisplayString());
Assert.Equal("Cls.Test2..ctor(System.Object x, System.Object y)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Empty(group); // https://github.com/dotnet/roslyn/issues/24936
}
[Fact]
public void ConstructorInitializers_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test3());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
public Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}
class Test3 : Test2
{
public Test3()
: base(Test1(out var x1), x1)
{}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (29,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// : base(Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(29, 26)
);
}
[Fact]
public void ConstructorInitializers_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
class Test2
{
Test2(out int x)
{
x = 2;
}
public Test2()
: this(out var x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void ConstructorInitializers_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test3());
}
static void Do(object x){}
class Test2
{
public Test2(out int x)
{
x = 1;
}
}
class Test3 : Test2
{
public Test3()
: base(out var x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void ConstructorInitializers_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(System.Func<object> x)
{
System.Console.WriteLine(x());
}
public Test2()
: this(() =>
{
Test1(out var x1);
return x1;
})
{}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_07()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (23,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2()
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(23, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var analyzer = new ConstructorInitializers_08_SyntaxAnalyzer();
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular)
.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.True(analyzer.ActionFired);
}
private class ConstructorInitializers_08_SyntaxAnalyzer : DiagnosticAnalyzer
{
public bool ActionFired { get; private set; }
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Handle, SyntaxKind.ThisConstructorInitializer);
}
private void Handle(SyntaxNodeAnalysisContext context)
{
ActionFired = true;
var tree = context.Node.SyntaxTree;
var model = context.SemanticModel;
var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node.Parent;
SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model);
Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(constructorDeclaration));
MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[constructorDeclaration];
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Initializer).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Body).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.ExpressionBody).IsDefaultOrEmpty);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Decl));
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[0]));
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[1]));
}
}
[Fact]
public void ConstructorInitializers_09()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_10()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (22,38): error CS0165: Use of unassigned local variable 'x1'
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_11()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (21,37): error CS0165: Use of unassigned local variable 'x1'
// => System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(21, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_12()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2(bool a)
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(19, 9),
// (22,38): error CS0165: Use of unassigned local variable 'x1'
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_13()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_14()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_15()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2(bool a)
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(19, 9),
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_16()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object a, object b, ref int x)
{
System.Console.WriteLine(x);
x++;
}
public Test2()
: this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_17()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object a, object b, ref int x)
{
System.Console.WriteLine(x);
x++;
}
public Test2()
: this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void SimpleVar_14()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out dynamic x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
references: new MetadataReference[] { CSharpRef },
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("dynamic x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_15()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new Test1(out var var), var);
}
class Test1
{
public Test1(out int x)
{
x = 123;
}
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var varDecl = GetOutVarDeclaration(tree, "var");
var varRef = GetReferences(tree, "var").Skip(1).Single();
VerifyModelForOutVar(model, varDecl, varRef);
}
[Fact]
public void SimpleVar_16()
{
var text = @"
public class Cls
{
public static void Main()
{
if (Test1(out var x1))
{
System.Console.WriteLine(x1);
}
}
static bool Test1(out int x)
{
x = 123;
return true;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString());
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void VarAndBetterness_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1, null);
Test2(out var x2, null);
}
static object Test1(out int x, object y)
{
x = 123;
System.Console.WriteLine(x);
return null;
}
static object Test1(out short x, string y)
{
x = 124;
System.Console.WriteLine(x);
return null;
}
static object Test2(out int x, string y)
{
x = 125;
System.Console.WriteLine(x);
return null;
}
static object Test2(out short x, object y)
{
x = 126;
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = GetOutVarDeclaration(tree, "x2");
VerifyModelForOutVar(model, x2Decl);
}
[Fact]
public void VarAndBetterness_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1, null);
}
static object Test1(out int x, object y)
{
x = 123;
System.Console.WriteLine(x);
return null;
}
static object Test1(out short x, object y)
{
x = 124;
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Cls.Test1(out int, object)' and 'Cls.Test1(out short, object)'
// Test1(out var x1, null);
Diagnostic(ErrorCode.ERR_AmbigCall, "Test1").WithArguments("Cls.Test1(out int, object)", "Cls.Test1(out short, object)").WithLocation(6, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.ArgIterator x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_03()
{
var text = @"
public class Cls
{
public static void Main() {}
async void Test()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(11, 25),
// (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(8, 25),
// (6,16): 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 Test()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void RestrictedTypes_04()
{
var text = @"
public class Cls
{
public static void Main() {}
async void Test()
{
Test2(Test1(out System.ArgIterator x1), x1);
var x = default(System.ArgIterator);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
targetFramework: TargetFramework.Mscorlib45,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(12, 25),
// (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// Test2(Test1(out System.ArgIterator x1), x1);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 25),
// (9,9): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// var x = default(System.ArgIterator);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(9, 9),
// (6,16): 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 Test()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ElementAccess_01()
{
var text = @"
public class Cls
{
public static void Main()
{
var x = new [] {1};
Test2(x[out var x1]);
Test2(x1);
Test2(x[out var _]);
}
static void Test2(object x) { }
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var model = compilation.GetSemanticModel(tree);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out var x1]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(x[out var x1]);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25),
// (9,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out var _]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(9, 21),
// (9,21): error CS8183: Cannot infer the type of implicitly-typed discard.
// Test2(x[out var _]);
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(9, 21)
);
}
[Fact]
public void PointerAccess_01()
{
var text = @"
public class Cls
{
public static unsafe void Main()
{
int* p = (int*)0;
Test2(p[out var x1]);
Test2(x1);
}
static void Test2(object x) { }
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe.WithAllowUnsafe(true),
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var model = compilation.GetSemanticModel(tree);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(p[out var x1]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(p[out var x1]);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25)
);
}
[Fact]
public void ElementAccess_02()
{
var text = @"
public class Cls
{
public static void Main()
{
var x = new [] {1};
Test2(x[out int x1], x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out int x1], x1);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,21): error CS0165: Use of unassigned local variable 'x1'
// Test2(x[out int x1], x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(7, 21)
);
}
[Fact]
[WorkItem(12058, "https://github.com/dotnet/roslyn/issues/12058")]
public void MissingArgumentAndNamedOutVarArgument()
{
var source =
@"class Program
{
public static void Main(string[] args)
{
if (M(s: out var s))
{
string s2 = s;
}
}
public static bool M(int i, out string s)
{
s = i.ToString();
return true;
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (5,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Program.M(int, out string)'
// if (M(s: out var s))
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("i", "Program.M(int, out string)").WithLocation(5, 13)
);
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out var x);
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out int x) + x;
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_03()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out var x) + x;
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_04()
{
var text = @"
public class Cls
{
public static void Main()
{
for (var y = Test1(out var x) + x; y != 0 ; y = 0)
{
System.Console.WriteLine(y);
}
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_05()
{
var text = @"
public class Cls
{
public static void Main()
{
foreach (var y in new [] {Test1(out var x) + x})
{
System.Console.WriteLine(y);
}
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")]
public void LocalVariableTypeInferenceAndOutVar_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(x: 1, out var y);
System.Console.WriteLine(y);
}
static void Test1(int x, ref int y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular7_1);
compilation.VerifyDiagnostics(
// (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// Test1(x: 1, out var y);
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "out var y").WithArguments("7.2").WithLocation(6, 21),
// (6,25): error CS1620: Argument 2 must be passed with the 'ref' keyword
// Test1(x: 1, out var y);
Diagnostic(ErrorCode.ERR_BadArgRef, "var y").WithArguments("2", "ref").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetDeclaration(tree, "y");
VerifyModelForOutVar(model, yDecl, GetReferences(tree, "y").ToArray());
}
[Fact]
[WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")]
public void LocalVariableTypeInferenceAndOutVar_07()
{
var text = @"
public class Cls
{
public static void Main()
{
int x = 0;
Test1(y: ref x, y: out var y);
System.Console.WriteLine(y);
}
static void Test1(int x, ref int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Cls.Test1(int, ref int)'
// Test1(y: ref x, y: out var y);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Test1").WithArguments("x", "Cls.Test1(int, ref int)").WithLocation(7, 9));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetDeclaration(tree, "y");
var yRef = GetReferences(tree, "y").ToArray();
Assert.Equal(3, yRef.Length);
Assert.Equal("System.Console.WriteLine(y)", yRef[2].Parent.Parent.Parent.ToString());
VerifyModelForOutVar(model, yDecl, yRef[2]);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamic()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int z];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()",
@"{
// Code size 87 (0x57)
.maxstack 7
.locals init (object V_0, //d
int V_1) //z
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0007: brtrue.s IL_003e
IL_0009: ldc.i4.0
IL_000a: ldtoken ""Cls""
IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0014: ldc.i4.2
IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001a: dup
IL_001b: ldc.i4.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0023: stelem.ref
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: ldc.i4.s 17
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target""
IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_004d: ldloc.0
IL_004e: ldloca.s V_1
IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)""
IL_0055: pop
IL_0056: ret
}");
}
[Fact]
public void IndexingDynamicWithDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int _];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()",
@"
{
// Code size 87 (0x57)
.maxstack 7
.locals init (object V_0, //d
int V_1)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0007: brtrue.s IL_003e
IL_0009: ldc.i4.0
IL_000a: ldtoken ""Cls""
IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0014: ldc.i4.2
IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001a: dup
IL_001b: ldc.i4.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0023: stelem.ref
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: ldc.i4.s 17
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target""
IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_004d: ldloc.0
IL_004e: ldloca.s V_1
IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)""
IL_0055: pop
IL_0056: ret
}
");
}
[Fact]
public void IndexingDynamicWithVarDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out var _];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
var comp = CreateCompilation(text, options: TestOptions.DebugDll, references: new[] { CSharpRef });
comp.VerifyDiagnostics(
// (7,23): error CS8183: Cannot infer the type of implicitly-typed discard.
// var x = d[out var _];
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 23)
);
}
[Fact]
public void IndexingDynamicWithShortDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out _];
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,23): error CS8183: Cannot infer the type of implicitly-typed discard.
// var x = d[out _];
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 23)
);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamicWithOutVar()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out var x1] + x1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl));
Assert.True(x1.Type.IsErrorType());
VerifyModelForOutVar(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// var x = d[out var x1] + x1;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 27)
);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamicWithOutInt()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int x1] + x1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl));
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
compilation.VerifyDiagnostics();
}
[ClrOnlyFact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void OutVariableDeclarationInIndex()
{
var source1 =
@".class interface public abstract import IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 )
.method public abstract virtual instance int32 get_Item([out] int32& i) { }
.method public abstract virtual instance void set_Item([out] int32& i, int32 v) { }
.property instance int32 Item([out] int32&)
{
.get instance int32 IA::get_Item([out] int32&)
.set instance void IA::set_Item([out] int32&, int32)
}
.method public abstract virtual instance int32 get_P([out] int32& i) { }
.method public abstract virtual instance void set_P([out] int32& i, int32 v) { }
.property instance int32 P([out] int32&)
{
.get instance int32 IA::get_P([out] int32&)
.set instance void IA::set_P([out] int32&, int32)
}
}
.class public A implements IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ret
}
// i = 1; return 2;
.method public virtual instance int32 get_P([out] int32& i)
{
ldarg.1
ldc.i4.1
stind.i4
ldc.i4.2
ret
}
// i = 3; return;
.method public virtual instance void set_P([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.3
stind.i4
ret
}
.property instance int32 P([out] int32&)
{
.get instance int32 A::get_P([out] int32&)
.set instance void A::set_P([out] int32&, int32)
}
// i = 4; return 5;
.method public virtual instance int32 get_Item([out] int32& i)
{
ldarg.1
ldc.i4.4
stind.i4
ldc.i4.5
ret
}
// i = 6; return;
.method public virtual instance void set_Item([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.6
stind.i4
ret
}
.property instance int32 Item([out] int32&)
{
.get instance int32 A::get_Item([out] int32&)
.set instance void A::set_Item([out] int32&, int32)
}
}";
var reference1 = CompileIL(source1);
var source2Template =
@"using System;
class B
{{
public static void Main()
{{
A a = new A();
IA ia = a;
Console.WriteLine(ia.P[out {0} x1] + "" "" + x1);
ia.P[out {0} x2] = 4;
Console.WriteLine(x2);
Console.WriteLine(ia[out {0} x3] + "" "" + x3);
ia[out {0} x4] = 4;
Console.WriteLine(x4);
}}
}}";
string[] fillIns = new[] { "int", "var" };
foreach (var fillIn in fillIns)
{
var source2 = string.Format(source2Template, fillIn);
var compilation = CreateCompilation(source2, references: new[] { reference1 });
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x2Ref[0]).Type.ToTestDisplayString());
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x3Ref[0]).Type.ToTestDisplayString());
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(1, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref[0]).Type.ToTestDisplayString());
CompileAndVerify(source2, references: new[] { reference1 }, expectedOutput:
@"2 1
3
5 4
6")
.VerifyIL("B.Main()",
@"{
// Code size 113 (0x71)
.maxstack 4
.locals init (int V_0, //x1
int V_1, //x2
int V_2, //x3
int V_3, //x4
int V_4)
IL_0000: newobj ""A..ctor()""
IL_0005: dup
IL_0006: ldloca.s V_0
IL_0008: callvirt ""int IA.P[out int].get""
IL_000d: stloc.s V_4
IL_000f: ldloca.s V_4
IL_0011: call ""string int.ToString()""
IL_0016: ldstr "" ""
IL_001b: ldloca.s V_0
IL_001d: call ""string int.ToString()""
IL_0022: call ""string string.Concat(string, string, string)""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: dup
IL_002d: ldloca.s V_1
IL_002f: ldc.i4.4
IL_0030: callvirt ""void IA.P[out int].set""
IL_0035: ldloc.1
IL_0036: call ""void System.Console.WriteLine(int)""
IL_003b: dup
IL_003c: ldloca.s V_2
IL_003e: callvirt ""int IA.this[out int].get""
IL_0043: stloc.s V_4
IL_0045: ldloca.s V_4
IL_0047: call ""string int.ToString()""
IL_004c: ldstr "" ""
IL_0051: ldloca.s V_2
IL_0053: call ""string int.ToString()""
IL_0058: call ""string string.Concat(string, string, string)""
IL_005d: call ""void System.Console.WriteLine(string)""
IL_0062: ldloca.s V_3
IL_0064: ldc.i4.4
IL_0065: callvirt ""void IA.this[out int].set""
IL_006a: ldloc.3
IL_006b: call ""void System.Console.WriteLine(int)""
IL_0070: ret
}");
}
}
[ClrOnlyFact]
public void OutVariableDiscardInIndex()
{
var source1 =
@".class interface public abstract import IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 )
.method public abstract virtual instance int32 get_Item([out] int32& i) { }
.method public abstract virtual instance void set_Item([out] int32& i, int32 v) { }
.property instance int32 Item([out] int32&)
{
.get instance int32 IA::get_Item([out] int32&)
.set instance void IA::set_Item([out] int32&, int32)
}
.method public abstract virtual instance int32 get_P([out] int32& i) { }
.method public abstract virtual instance void set_P([out] int32& i, int32 v) { }
.property instance int32 P([out] int32&)
{
.get instance int32 IA::get_P([out] int32&)
.set instance void IA::set_P([out] int32&, int32)
}
}
.class public A implements IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ret
}
// i = 1; System.Console.WriteLine(11); return 111;
.method public virtual instance int32 get_P([out] int32& i)
{
ldarg.1
ldc.i4.1
stind.i4
ldc.i4.s 11
call void [mscorlib]System.Console::WriteLine(int32)
ldc.i4 0x06F
ret
}
// i = 2; System.Console.Write(22); return;
.method public virtual instance void set_P([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.2
stind.i4
ldc.i4.s 22
call void [mscorlib]System.Console::WriteLine(int32)
ret
}
.property instance int32 P([out] int32&)
{
.get instance int32 A::get_P([out] int32&)
.set instance void A::set_P([out] int32&, int32)
}
// i = 3; System.Console.WriteLine(33) return 333;
.method public virtual instance int32 get_Item([out] int32& i)
{
ldarg.1
ldc.i4.3
stind.i4
ldc.i4.s 33
call void [mscorlib]System.Console::WriteLine(int32)
ldc.i4 0x14D
ret
}
// i = 4; System.Console.WriteLine(44); return;
.method public virtual instance void set_Item([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.4
stind.i4
ldc.i4.s 44
call void [mscorlib]System.Console::WriteLine(int32)
ret
}
.property instance int32 Item([out] int32&)
{
.get instance int32 A::get_Item([out] int32&)
.set instance void A::set_Item([out] int32&, int32)
}
}";
var reference1 = CompileIL(source1);
var source2Template =
@"using System;
class B
{{
public static void Main()
{{
A a = new A();
IA ia = a;
Console.WriteLine(ia.P[out {0} _]);
ia.P[out {0} _] = 4;
Console.WriteLine(ia[out {0} _]);
ia[out {0} _] = 4;
}}
}}";
string[] fillIns = new[] { "int", "var", "" };
foreach (var fillIn in fillIns)
{
var source2 = string.Format(source2Template, fillIn);
var compilation = CreateCompilation(source2, references: new[] { reference1 }, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput:
@"11
111
22
33
333
44")
.VerifyIL("B.Main()",
@"
{
// Code size 58 (0x3a)
.maxstack 3
.locals init (A V_0, //a
IA V_1, //ia
int V_2)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloca.s V_2
IL_000c: callvirt ""int IA.P[out int].get""
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: nop
IL_0017: ldloc.1
IL_0018: ldloca.s V_2
IL_001a: ldc.i4.4
IL_001b: callvirt ""void IA.P[out int].set""
IL_0020: nop
IL_0021: ldloc.1
IL_0022: ldloca.s V_2
IL_0024: callvirt ""int IA.this[out int].get""
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ldloc.1
IL_0030: ldloca.s V_2
IL_0032: ldc.i4.4
IL_0033: callvirt ""void IA.this[out int].set""
IL_0038: nop
IL_0039: ret
}");
}
}
[Fact]
public void ElementAccess_04()
{
var text = @"
using System.Collections.Generic;
public class Cls
{
public static void Main()
{
var list = new Dictionary<int, long>
{
[out var x1] = 3,
[out var _] = 4,
[out _] = 5
};
System.Console.Write(x1);
System.Console.Write(_);
{
int _ = 1;
var list2 = new Dictionary<int, long> { [out _] = 6 };
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.ToTestDisplayString());
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (9,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out var x1] = 3,
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(9, 18),
// (10,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out var _] = 4,
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(10, 18),
// (11,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out _] = 5
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(11, 18),
// (14,30): error CS0103: The name '_' does not exist in the current context
// System.Console.Write(_);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 30),
// (18,58): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var list2 = new Dictionary<int, long> { [out _] = 6 };
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(18, 58)
);
}
[Fact]
public void ElementAccess_05()
{
var text = @"
public class Cls
{
public static void Main()
{
int[out var x1] a = null; // fatal syntax error - 'out' is skipped
int b(out var x2) = null; // parsed as a local function with syntax error
int c[out var x3] = null; // fatal syntax error - 'out' is skipped
int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
x4 = 0;
}
}";
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.Equal(1, compilation.SyntaxTrees[0].GetRoot().DescendantNodesAndSelf().OfType<DeclarationExpressionSyntax>().Count());
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
compilation.VerifyDiagnostics(
// (6,13): error CS1003: Syntax error, ',' expected
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 13),
// (6,21): error CS1003: Syntax error, ',' expected
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 21),
// (7,27): error CS1002: ; expected
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(7, 27),
// (7,27): error CS1525: Invalid expression term '='
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 27),
// (8,14): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_CStyleArray, "[out var x3]").WithLocation(8, 14),
// (8,15): error CS1003: Syntax error, ',' expected
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 15),
// (8,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "var").WithLocation(8, 19),
// (8,23): error CS1003: Syntax error, ',' expected
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 23),
// (8,23): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "x3").WithLocation(8, 23),
// (10,17): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x4").WithLocation(10, 17),
// (10,17): error CS1003: Syntax error, '[' expected
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(10, 17),
// (10,28): error CS1003: Syntax error, ']' expected
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(10, 28),
// (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[out var x1]").WithLocation(6, 12),
// (6,17): error CS0103: The name 'var' does not exist in the current context
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 17),
// (6,21): error CS0103: The name 'x1' does not exist in the current context
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 21),
// (7,13): error CS8112: 'b(out var)' is a local function and must therefore always have a body.
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "b").WithArguments("b(out var)").WithLocation(7, 13),
// (7,19): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 19),
// (8,29): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 29),
// (8,19): error CS0103: The name 'var' does not exist in the current context
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19),
// (8,23): error CS0103: The name 'x3' does not exist in the current context
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(8, 23),
// (7,13): error CS0177: The out parameter 'x2' must be assigned to before control leaves the current method
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_ParamUnassigned, "b").WithArguments("x2").WithLocation(7, 13),
// (6,25): warning CS0219: The variable 'a' is assigned but its value is never used
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(6, 25),
// (10,13): warning CS0168: The variable 'd' is declared but never used
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.WRN_UnreferencedVar, "d").WithArguments("d").WithLocation(10, 13),
// (10,16): warning CS0168: The variable 'e' is declared but never used
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(10, 16),
// (7,13): warning CS8321: The local function 'b' is declared but never used
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "b").WithArguments("b").WithLocation(7, 13)
);
}
[Fact]
public void ElementAccess_06()
{
var text = @"
public class Cls
{
public static void Main()
{
{
int[] e = null;
var z1 = e?[out var x1];
x1 = 1;
}
{
int[][] e = null;
var z2 = e?[out var x2]?[out var x3];
x2 = 1;
x3 = 2;
}
{
int[][] e = null;
var z3 = e?[0]?[out var x4];
x4 = 1;
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(model.GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var x2Decl = GetOutVarDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
Assert.True(model.GetTypeInfo(x2Ref).Type.TypeKind == TypeKind.Error);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
Assert.True(model.GetTypeInfo(x3Ref).Type.TypeKind == TypeKind.Error);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
Assert.True(model.GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (8,29): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z1 = e?[out var x1];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(8, 29),
// (8,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// var z1 = e?[out var x1];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(8, 33),
// (13,29): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z2 = e?[out var x2]?[out var x3];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x2").WithArguments("1", "out").WithLocation(13, 29),
// (13,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x2'.
// var z2 = e?[out var x2]?[out var x3];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x2").WithArguments("x2").WithLocation(13, 33),
// (19,33): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z3 = e?[0]?[out var x4];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x4").WithArguments("1", "out").WithLocation(19, 33),
// (19,37): error CS8197: Cannot infer the type of implicitly-typed out variable 'x4'.
// var z3 = e?[0]?[out var x4];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x4").WithArguments("x4").WithLocation(19, 37)
);
}
[Fact]
public void FixedFieldSize()
{
var text = @"
unsafe struct S
{
fixed int F1[out var x1, x1];
//fixed int F2[3 is int x2 ? x2 : 3];
//fixed int F2[3 is int x3 ? 3 : 3, x3];
}
";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseDebugDll.WithAllowUnsafe(true),
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.Empty(GetOutVarDeclarations(tree, "x1"));
compilation.VerifyDiagnostics(
// (4,18): error CS1003: Syntax error, ',' expected
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(4, 18),
// (4,26): error CS1003: Syntax error, ',' expected
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(4, 26),
// (4,17): error CS7092: A fixed buffer may only have one dimension.
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x1, x1]").WithLocation(4, 17),
// (4,22): error CS0103: The name 'var' does not exist in the current context
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 22)
);
}
[Fact]
public void Scope_DeclaratorArguments_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
int d,e(Dummy(TakeOutParam(true, out var x1), x1));
}
void Test4()
{
var x4 = 11;
Dummy(x4);
int d,e(Dummy(TakeOutParam(true, out var x4), x4));
}
void Test6()
{
int d,e(Dummy(x6 && TakeOutParam(true, out var x6)));
}
void Test8()
{
int d,e(Dummy(TakeOutParam(true, out var x8), x8));
System.Console.WriteLine(x8);
}
void Test14()
{
int d,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (19,50): error CS0128: A local variable named 'x4' is already defined in this scope
// int d,e(Dummy(TakeOutParam(true, out var x4), x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// int d,e(Dummy(x6 && TakeOutParam(true, out var x6)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (30,34): error CS0165: Use of unassigned local variable 'x8'
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(30, 34),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
private static void AssertContainedInDeclaratorArguments(DeclarationExpressionSyntax decl)
{
Assert.True(decl.Ancestors().OfType<VariableDeclaratorSyntax>().First().ArgumentList.Contains(decl));
}
private static void AssertContainedInDeclaratorArguments(params DeclarationExpressionSyntax[] decls)
{
foreach (var decl in decls)
{
AssertContainedInDeclaratorArguments(decl);
}
}
[Fact]
public void Scope_DeclaratorArguments_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d, x1(
Dummy(TakeOutParam(true, out var x1), x1));
Dummy(x1);
}
void Test2()
{
object d, x2(
Dummy(TakeOutParam(true, out var x2), x2));
Dummy(x2);
}
void Test3()
{
object x3, d(
Dummy(TakeOutParam(true, out var x3), x3));
Dummy(x3);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,13): error CS0818: Implicitly-typed variables must be initialized
// var d, x1(
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(12, 13),
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (21,15): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 15),
// (27,54): error CS0128: A local variable named 'x3' is already defined in this scope
// Dummy(TakeOutParam(true, out var x3), x3));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(27, 54),
// (28,15): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(28, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1( Dummy(x1));
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2(Dummy(TakeOutParam(true, out var x2), x2));
}
void Test3()
{
object d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2(Dummy(x3));
}
void Test4()
{
object d1,e(Dummy(x4)],
d2(Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1( Dummy(x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (14,15): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 15),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2(Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1,e(Dummy(x4)],
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2 = Dummy(TakeOutParam(true, out var x2), x2);
}
void Test3()
{
object d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 (Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (13,27): error CS0165: Use of unassigned local variable 'x1'
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 27),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59),
// (26,27): error CS0165: Use of unassigned local variable 'x3'
// d2 = Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(26, 27),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl[0]);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y, y1(Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
var y1 = model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single();
Assert.Equal("var y1", y1.ToTestDisplayString());
Assert.True(((ILocalSymbol)y1).Type.IsErrorType());
}
[Fact]
public void Scope_DeclaratorArguments_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d,e(TakeOutParam(true, out var x1) && x1 != null);
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d =TakeOutParam(true, out var x1) && x1 != null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d,e(TakeOutParam(true, out var x1) && x1 != null);").WithLocation(11, 13),
// (11,17): error CS0818: Implicitly-typed variables must be initialized
// var d,e(TakeOutParam(true, out var x1) && x1 != null);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(11, 17),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var e = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "e").Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(e);
Assert.Equal("var e", symbol.ToTestDisplayString());
Assert.True(symbol.Type.IsErrorType());
}
[Fact]
[WorkItem(13460, "https://github.com/dotnet/roslyn/issues/13460")]
public void Scope_DeclaratorArguments_07()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var z, z1(x1, out var u1, x1 > 0 & TakeOutParam(x1, out var y1)];
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
AssertContainedInDeclaratorArguments(y1Decl);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.True(((ITypeSymbol)model.GetTypeInfo(zRef).Type).IsErrorType());
}
[Fact]
[WorkItem(13459, "https://github.com/dotnet/roslyn/issues/13459")]
public void Scope_DeclaratorArguments_08()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x1) && x1)
);;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x2) && x2)
);;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool a, b(
Dummy(TakeOutParam(true, out var x4) && x4)
);;)
Dummy(x4);
}
void Test6()
{
for (bool a, b(
Dummy(x6 && TakeOutParam(true, out var x6))
);;)
Dummy(x6);
}
void Test7()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x7) && x7)
);;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x8) && x8)
);;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool a1, b1(
Dummy(TakeOutParam(true, out var x9) && x9)
);;)
{
Dummy(x9);
for (bool a2, b2(
Dummy(TakeOutParam(true, out var x9) && x9) // 2
);;)
Dummy(x9);
}
}
void Test10()
{
for (bool a, b(
Dummy(TakeOutParam(y10, out var x10))
);;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool a, b(
// Dummy(TakeOutParam(y11, out var x11))
// );;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool a, b(
Dummy(TakeOutParam(y12, out var x12))
);;)
var y12 = 12;
}
//void Test13()
//{
// for (bool a, b(
// Dummy(TakeOutParam(y13, out var x13))
// );;)
// let y13 = 12;
//}
void Test14()
{
for (bool a, b(
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
);;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_09()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
for (bool d, x4(
Dummy(TakeOutParam(true, out var x4) && x4)
);;)
{}
}
void Test7()
{
for (bool x7 = true, b(
Dummy(TakeOutParam(true, out var x7) && x7)
);;)
{}
}
void Test8()
{
for (bool d,b1(Dummy(TakeOutParam(true, out var x8) && x8)],
b2(Dummy(TakeOutParam(true, out var x8) && x8));
Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2(Dummy(TakeOutParam(true, out var x9) && x9));
Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,47): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 47),
// (21,47): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(TakeOutParam(true, out var x7) && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(21, 47),
// (20,19): warning CS0219: The variable 'x7' is assigned but its value is never used
// for (bool x7 = true, b(
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x7").WithArguments("x7").WithLocation(20, 19),
// (29,52): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2(Dummy(TakeOutParam(true, out var x8) && x8));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(29, 52),
// (30,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(30, 47),
// (31,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(31, 47),
// (37,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(37, 23),
// (39,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(39, 47),
// (40,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(40, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x7Decl);
VerifyNotAnOutLocal(model, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl[0]);
AssertContainedInDeclaratorArguments(x8Decl[1]);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]);
VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl[0]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]);
VerifyModelForOutVar(model, x9Decl[2], x9Ref[3]);
}
[Fact]
public void Scope_DeclaratorArguments_10()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,e(Dummy(TakeOutParam(true, out var x1), x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (var d,e(Dummy(TakeOutParam(true, out var x2), x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d,e(Dummy(TakeOutParam(true, out var x4), x4)))
Dummy(x4);
}
void Test6()
{
using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Dummy(x6);
}
void Test7()
{
using (var d,e(Dummy(TakeOutParam(true, out var x7) && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d,e(Dummy(TakeOutParam(true, out var x8), x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d,a(Dummy(TakeOutParam(true, out var x9), x9)))
{
Dummy(x9);
using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d,e(Dummy(TakeOutParam(y11, out var x11), x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12)))
var y12 = 12;
}
//void Test13()
//{
// using (var d,e(Dummy(TakeOutParam(y13, out var x13), x13)))
// let y13 = 12;
//}
void Test14()
{
using (var d,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d,e(Dummy(TakeOutParam(true, out var x4), x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61),
// (68,43): error CS0103: The name 'y10' does not exist in the current context
// using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43),
// (86,43): error CS0103: The name 'y12' does not exist in the current context
// using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,54): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
AssertContainedInDeclaratorArguments(x10Decl);
VerifyModelForOutVarWithoutDataFlow(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_11()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2)))
{
Dummy(x2);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,58): error CS0128: A local variable or function named 'x1' is already defined in this scope
// using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58),
// (20,73): error CS0128: A local variable or function named 'x2' is already defined in this scope
// using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
AssertContainedInDeclaratorArguments(x2Decl);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
}
[Fact]
public void Scope_DeclaratorArguments_12()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2(Dummy(TakeOutParam(true, out var x2), x2)))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2(Dummy(TakeOutParam(true, out var x4), x4)))
{
Dummy(x4);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,35): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,73): error CS0128: A local variable named 'x2' is already defined in this scope
// d2(Dummy(TakeOutParam(true, out var x2), x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_13()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x1) && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x2) && x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4)))
Dummy(x4);
}
void Test6()
{
fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Dummy(x6);
}
void Test7()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x7) && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x8) && x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1,a(Dummy(TakeOutParam(true, out var x9) && x9)))
{
Dummy(x9);
fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10))))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p,e(Dummy(TakeOutParam(y11, out var x11))))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12))))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p,e(Dummy(TakeOutParam(y13, out var x13))))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)))
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63),
// (68,44): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10))))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44),
// (86,44): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12))))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,55): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_14()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* d,x1(
Dummy(TakeOutParam(true, out var x1) && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* d,p(Dummy(TakeOutParam(true, out var x2) && x2)],
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p(Dummy(TakeOutParam(true, out var x3) && x3)))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* d,p1(Dummy(TakeOutParam(true, out var x4) && x4)],
p2(Dummy(TakeOutParam(true, out var x4) && x4)))
{
Dummy(x4);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (14,59): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59),
// (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// Dummy(TakeOutParam(true, out var x1) && x1)))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32),
// (23,21): error CS0128: A local variable named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,58): error CS0128: A local variable named 'x3' is already defined in this scope
// p(Dummy(TakeOutParam(true, out var x3) && x3)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58),
// (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// p(Dummy(TakeOutParam(true, out var x3) && x3)))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31),
// (41,59): error CS0128: A local variable named 'x4' is already defined in this scope
// p2(Dummy(TakeOutParam(true, out var x4) && x4)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_15()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
bool Test4 [x4 && TakeOutParam(4, out var x4)];
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
private static void VerifyModelNotSupported(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
var variableDeclaratorSyntax = GetVariableDesignation(decl);
Assert.Null(model.GetDeclaredSymbol(variableDeclaratorSyntax));
Assert.Null(model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax));
var identifierText = decl.Identifier().ValueText;
Assert.False(model.LookupSymbols(decl.SpanStart, name: identifierText).Any());
Assert.False(model.LookupNames(decl.SpanStart).Contains(identifierText));
Assert.Null(model.GetSymbolInfo(decl.Type).Symbol);
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: null, expectedType: null);
VerifyModelNotSupported(model, references);
}
private static void VerifyModelNotSupported(SemanticModel model, params IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
Assert.Null(model.GetSymbolInfo(reference).Symbol);
Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
Assert.DoesNotContain(reference.Identifier.ValueText, model.LookupNames(reference.SpanStart));
Assert.True(((ITypeSymbol)model.GetTypeInfo(reference).Type).IsErrorType());
}
}
[Fact]
public void Scope_DeclaratorArguments_16()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
fixed
bool Test4 [x4 && TakeOutParam(4, out var x4)];
fixed
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
fixed
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
fixed
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
fixed
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField,
(int)ErrorCode.ERR_NoImplicitConv
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 [x4 && TakeOutParam(4, out var x4)];
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (20,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 [Dummy(x7, 2)];
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 25),
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_17()
{
var source =
@"
public class X
{
public static void Main()
{
}
const
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
const
bool Test4 [x4 && TakeOutParam(4, out var x4)];
const
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
const
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
const
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
const
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_18()
{
var source =
@"
public class X
{
public static void Main()
{
}
event
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
event
bool Test4 [x4 && TakeOutParam(4, out var x4)];
event
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
event
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
event
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
event
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.ERR_EventNotDelegate,
(int)ErrorCode.WRN_UnreferencedEvent
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_19()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool d[2], Test3 (out var x3);
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (8,28): error CS1003: Syntax error, '[' expected
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(8, 28),
// (8,39): error CS1003: Syntax error, ']' expected
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(8, 39),
// (8,33): error CS8185: A declaration is not allowed in this context.
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x3").WithLocation(8, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_20()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool Test3[out var x3];
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,22): error CS1003: Syntax error, ',' expected
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 22),
// (8,30): error CS1003: Syntax error, ',' expected
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 30),
// (8,21): error CS7092: A fixed buffer may only have one dimension.
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x3]").WithLocation(8, 21),
// (8,26): error CS0103: The name 'var' does not exist in the current context
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 26)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree, "x3").Any());
}
[Fact]
public void StaticType()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out StaticType x1);
}
static object Test1(out StaticType x)
{
throw new System.NotSupportedException();
}
static class StaticType {}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS0721: 'Cls.StaticType': static types cannot be used as parameters
// static object Test1(out StaticType x)
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "Test1").WithArguments("Cls.StaticType").WithLocation(9, 19),
// (6,19): error CS0723: Cannot declare a variable of static type 'Cls.StaticType'
// Test1(out StaticType x1);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "StaticType").WithArguments("Cls.StaticType").WithLocation(6, 19)
);
}
[Fact]
public void GlobalCode_Catch_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
try {}
catch when (TakeOutParam(out var x1) && x1 > 0)
{
Dummy(x1);
}
var x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out var x4) && x4 > 0)
{
Dummy(x4);
}
try {}
catch when (x6 && TakeOutParam(out var x6))
{
Dummy(x6);
}
try {}
catch when (TakeOutParam(out var x7) && x7 > 0)
{
var x7 = 12;
Dummy(x7);
}
try {}
catch when (TakeOutParam(out var x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
try {}
catch when (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
// try {}
// catch when (TakeOutParam(y11, out var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
try {}
catch when (Dummy(TakeOutParam(out var x14),
TakeOutParam(out var x14), // 2
x14))
{
Dummy(x14);
}
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out var x15), x15))
{
Dummy(x15);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (20,13): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13),
// (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9),
// (38,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26),
// (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38),
// (52,26): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26),
// (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42),
// (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (14,34): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(14, 34),
// (20,13): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13),
// (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9),
// (38,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26),
// (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38),
// (52,26): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26),
// (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42),
// (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42),
// (85,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope
// static bool TakeOutParam(object y, out int x)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13),
// (85,13): warning CS8321: The local function 'TakeOutParam' is declared but never used
// static bool TakeOutParam(object y, out int x)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
}
[Fact]
public void GlobalCode_Catch_02()
{
var source =
@"
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Block_01()
{
string source =
@"
{
H.TakeOutParam(1, out var x1);
H.Dummy(x1);
}
object x2;
{
H.TakeOutParam(2, out var x2);
H.Dummy(x2);
}
{
H.TakeOutParam(3, out var x3);
}
H.Dummy(x3);
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x3' does not exist in the current context
// H.Dummy(x3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotInScope(model, x3Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,8): warning CS0168: The variable 'x2' is declared but never used
// object x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(7, 8),
// (9,31): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(9, 31),
// (15,9): error CS0103: The name 'x3' does not exist in the current context
// H.Dummy(x3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotInScope(model, x3Ref);
}
}
[Fact]
public void GlobalCode_Block_02()
{
string source =
@"
{
H.TakeOutParam(1, out var x1);
System.Console.WriteLine(x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_For_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
for (
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
for ( // 2
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
var x4 = 11;
Dummy(x4);
for (
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
for (
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
for (
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
for (
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
for (
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
for (
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
// for (
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
for (
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
// for (
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
for (
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5),
// (25,15): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15),
// (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9),
// (42,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26),
// (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46),
// (56,28): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28),
// (72,28): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28),
// (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37),
// (11,1): warning CS0162: Unreachable code detected
// for ( // 2
Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1),
// (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (20,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(20, 42),
// (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5),
// (25,15): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15),
// (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9),
// (42,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26),
// (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46),
// (56,28): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28),
// (72,28): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28),
// (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37),
// (11,1): warning CS0162: Unreachable code detected
// for ( // 2
Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1),
// (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
}
[Fact]
public void GlobalCode_For_02()
{
var source =
@"
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
f = false;
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_Foreach_01()
{
var source =
@"using static Helpers;
System.Collections.IEnumerable Dummy(params object[] x) {return null;}
foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
var x4 = 11;
Dummy(x4);
foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
// foreach (var i in Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
// foreach (var i in Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
foreach (var i in Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
foreach (var x15 in
Dummy(TakeOutParam(1, out var x15), x15))
{
Dummy(x15);
}
static class Helpers
{
public static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
public static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,25): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57),
// (39,38): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38),
// (51,38): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38),
// (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49),
// (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (15,52): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 52),
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,25): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57),
// (39,38): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38),
// (51,38): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38),
// (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49),
// (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
}
[Fact]
public void GlobalCode_Foreach_02()
{
var source =
@"
bool f = true;
foreach (var i in Dummy(TakeOutParam(3, out var x1), x1))
{
System.Console.WriteLine(x1);
}
static System.Collections.IEnumerable Dummy(object y, object z)
{
System.Console.WriteLine(z);
return ""a"";
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"3
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Lambda_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x3) && x3 > 0));
Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out var x5) &&
TakeOutParam(o2, out var x5) &&
x5 > 0));
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0));
Dummy(x7, 1);
Dummy(x7,
(System.Func<object, bool>) (o => TakeOutParam(o, out var x7) && x7 > 0),
x7);
Dummy(x7, 2);
Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Dummy(TakeOutParam(true, out var x9),
(System.Func<object, bool>) (o => TakeOutParam(o, out var x9) &&
x9 > 0), x9);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x10) &&
x10 > 0),
TakeOutParam(true, out var x10), x10);
var x11 = 11;
Dummy(x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x11) &&
x11 > 0), x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x12) &&
x12 > 0),
x12);
var x12 = 11;
Dummy(x12);
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = true;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,41): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41),
// (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82),
// (14,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7),
// (15,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7),
// (17,9): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9),
// (18,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutField(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutField(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutField(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,41): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41),
// (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82),
// (14,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7),
// (15,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7),
// (17,9): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9),
// (18,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7),
// (20,7): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int'
// Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 7),
// (20,79): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int'
// Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(o, out var y8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 79),
// (37,9): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(37, 9),
// (47,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope
// static bool TakeOutParam(bool y, out bool x)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13),
// (47,13): warning CS8321: The local function 'TakeOutParam' is declared but never used
// static bool TakeOutParam(bool y, out bool x)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void GlobalCode_Lambda_02()
{
var source =
@"
System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1);
System.Console.WriteLine(l());
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Lambda_03()
{
var source =
@"
System.Console.WriteLine(((System.Func<bool>)(() => TakeOutParam(1, out int x1) && Dummy(x1)))());
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Query_01()
{
var source =
@"
using System.Linq;
bool Dummy(params object[] x) {return true;}
var r01 = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1}
select x + y1;
Dummy(y1);
var r02 = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0}
from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2}
select x1 + x2 + y2 +
z2;
Dummy(z2);
var r03 = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0}
let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0
select new { x1, x2, y3,
z3};
Dummy(z3);
var r04 = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
var r05 = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
var r06 = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0}
where x > y6 && TakeOutParam(1, out var z6) && z6 == 1
select x + y6 +
z6;
Dummy(z6);
var r07 = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0}
orderby x > y7 && TakeOutParam(1, out var z7) && z7 ==
u7,
x > y7 && TakeOutParam(1, out var u7) && u7 ==
z7
select x + y7 +
z7 + u7;
Dummy(z7);
Dummy(u7);
var r08 = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0}
select x > y8 && TakeOutParam(1, out var z8) && z8 == 1;
Dummy(z8);
var r09 = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0}
group x > y9 && TakeOutParam(1, out var z9) && z9 ==
u9
by
x > y9 && TakeOutParam(1, out var u9) && u9 ==
z9;
Dummy(z9);
Dummy(u9);
var r10 = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0}
from y10 in new[] { 1 }
select x1 + y10;
var r11 = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0}
let y11 = x1 + 1
select x1 + y11;
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (14,21): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21),
// (21,25): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25),
// (28,29): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29),
// (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29),
// (32,25): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25),
// (32,29): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29),
// (41,29): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29),
// (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29),
// (46,25): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25),
// (46,29): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29),
// (55,21): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21),
// (61,21): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21),
// (63,21): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21),
// (65,21): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21),
// (65,26): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26),
// (80,17): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17),
// (77,17): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17),
// (16,7): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7),
// (23,7): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7),
// (35,7): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7),
// (36,7): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7),
// (49,7): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7),
// (50,7): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7),
// (57,7): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7),
// (67,7): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7),
// (68,7): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7),
// (73,7): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7),
// (82,7): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7),
// (83,7): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutField(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutField(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutField(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutField(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutField(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutField(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutField(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutField(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutField(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutField(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutField(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutField(model, y10Decl, y10Ref[0]);
VerifyNotAnOutField(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutField(model, y11Decl, y11Ref[0]);
VerifyNotAnOutField(model, y11Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (14,21): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21),
// (16,7): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7),
// (21,25): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25),
// (23,7): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7),
// (28,29): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29),
// (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29),
// (32,25): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25),
// (32,29): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29),
// (35,7): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7),
// (36,7): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7),
// (41,29): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29),
// (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29),
// (46,25): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25),
// (46,29): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29),
// (49,7): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7),
// (50,7): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7),
// (55,21): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21),
// (57,7): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7),
// (61,21): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21),
// (63,21): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21),
// (65,21): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21),
// (65,26): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26),
// (67,7): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7),
// (68,7): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7),
// (73,7): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7),
// (77,17): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17),
// (80,17): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17),
// (82,7): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7),
// (83,7): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7),
// (86,18): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10'
// from y10 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(86, 18),
// (90,17): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11'
// let y11 = x1 + 1
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(90, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutVar(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutVar(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutVar(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutVar(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutVar(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutVar(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutVar(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutVar(model, y10Decl, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutVar(model, y11Decl, y11Ref[0]);
VerifyNotAnOutLocal(model, y11Ref[1]);
}
}
[Fact]
public void GlobalCode_Query_02()
{
var source =
@"
using System.Linq;
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0}
select Print(x1);
res.ToArray();
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetOutVarDeclarations(tree, "y1").Single();
var yRef = GetReferences(tree, "y1").Single();
VerifyModelForOutField(model, yDecl, yRef);
}
[Fact]
public void GlobalCode_Using_01()
{
var source =
@"
System.IDisposable Dummy(params object[] x) {return null;}
using (Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
using (Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
var x4 = 11;
Dummy(x4);
using (Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
using (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
using (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
using (Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
using (Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
using (Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
// using (Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
using (Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
// using (Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
using (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,14): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45),
// (39,27): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27),
// (51,27): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27),
// (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (15,41): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 41),
// (18,14): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45),
// (39,27): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27),
// (51,27): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27),
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9),
// (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
}
[Fact]
public void GlobalCode_Using_02()
{
var source =
@"
using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2)))
{
System.Console.WriteLine(d1);
System.Console.WriteLine(x1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x2);
}
using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1)))
{
System.Console.WriteLine(x1);
}
static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
class C : System.IDisposable
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public void Dispose()
{
System.Console.WriteLine(""Disposing {0}"", _val);
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"a
b
c
d
Disposing c
Disposing a
f
Disposing e");
}
[Fact]
public void GlobalCode_ExpressionStatement_01()
{
string source =
@"
H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
H.TakeOutParam(2, out int x2);
H.TakeOutParam(3, out int x3);
object x3;
H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,27): error CS0102: The type 'Script' already contains a definition for 'x2'
// H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,36): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope
// H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36),
// (13,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
private static void AssertNoGlobalStatements(SyntaxTree tree)
{
Assert.Empty(tree.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>());
}
[Fact]
public void GlobalCode_ExpressionStatement_02()
{
string source =
@"
H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
H.TakeOutParam(2, out var x2);
H.TakeOutParam(3, out var x3);
object x3;
H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,27): error CS0102: The type 'Script' already contains a definition for 'x2'
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,36): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36),
// (13,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ExpressionStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_IfStatement_01()
{
string source =
@"
if (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
if (H.TakeOutParam(2, out int x2)) {}
if (H.TakeOutParam(3, out int x3)) {}
object x3;
if (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
if (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
int x6 = 6;
if (H.Dummy())
{
string x6 = ""6"";
H.Dummy(x6);
}
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,31): error CS0102: The type 'Script' already contains a definition for 'x2'
// if (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,40): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40),
// (30,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(30, 17),
// (30,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(30, 21),
// (30,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(30, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope
// if (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (21,5): warning CS0219: The variable 'x6' is assigned but its value is never used
// int x6 = 6;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(21, 5),
// (24,12): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// string x6 = "6";
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(24, 12),
// (33,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(33, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_IfStatement_02()
{
string source =
@"
if (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
if (H.TakeOutParam(2, out var x2)) {}
if (H.TakeOutParam(3, out var x3)) {}
object x3;
if (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
if (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,31): error CS0102: The type 'Script' already contains a definition for 'x2'
// if (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,40): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[0], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope
// if (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40),
// (16,29): error CS0841: Cannot use local variable 'x5' before it is declared
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x5").WithArguments("x5").WithLocation(16, 29),
// (21,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 34),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]);
}
}
[Fact]
public void GlobalCode_IfStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
if (H.TakeOutParam(1, out var x1))
{
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_IfStatement_04()
{
string source =
@"
System.Console.WriteLine(x1);
if (H.TakeOutParam(1, out var x1))
H.Dummy(H.TakeOutParam(""11"", out var x1), x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static void Dummy(object x, object y)
{
System.Console.WriteLine(y);
}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_YieldReturnStatement_01()
{
string source =
@"
yield return H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
yield return H.TakeOutParam(2, out int x2);
yield return H.TakeOutParam(3, out int x3);
object x3;
yield return H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,40): error CS0102: The type 'Script' already contains a definition for 'x2'
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,49): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49),
// (2,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1),
// (6,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1),
// (8,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1),
// (11,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type
// yield return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out int x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1),
// (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_YieldReturnStatement_02()
{
string source =
@"
yield return H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
yield return H.TakeOutParam(2, out var x2);
yield return H.TakeOutParam(3, out var x3);
object x3;
yield return H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,40): error CS0102: The type 'Script' already contains a definition for 'x2'
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,49): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49),
// (2,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1),
// (6,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1),
// (8,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1),
// (11,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type
// yield return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out var x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1),
// (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_01()
{
string source =
@"
return H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
return H.TakeOutParam(2, out int x2);
return H.TakeOutParam(3, out int x3);
object x3;
return H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,34): error CS0102: The type 'Script' already contains a definition for 'x2'
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,43): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out int x1)").WithArguments("bool", "int").WithLocation(2, 8),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out int x2)").WithArguments("bool", "int").WithLocation(6, 8),
// (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out int x3)").WithArguments("bool", "int").WithLocation(8, 8),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))").WithArguments("bool", "int").WithLocation(11, 8),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (14,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_02()
{
string source =
@"
return H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
return H.TakeOutParam(2, out var x2);
return H.TakeOutParam(3, out var x3);
object x3;
return H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,34): error CS0102: The type 'Script' already contains a definition for 'x2'
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,43): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out var x1)").WithArguments("bool", "int").WithLocation(2, 8),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out var x2)").WithArguments("bool", "int").WithLocation(6, 8),
// (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out var x3)").WithArguments("bool", "int").WithLocation(8, 8),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))").WithArguments("bool", "int").WithLocation(11, 8),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (14,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
Test();
return H.Dummy(H.TakeOutParam(1, out var x1), x1);
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool Dummy(object x, object y)
{
System.Console.WriteLine(y);
return true;
}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_ThrowStatement_01()
{
string source =
@"
throw H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
throw H.TakeOutParam(2, out int x2);
throw H.TakeOutParam(3, out int x3);
object x3;
throw H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static System.Exception Dummy(params object[] x) {return null;}
public static System.Exception TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// throw H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// throw H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ThrowStatement_02()
{
string source =
@"
throw H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
throw H.TakeOutParam(2, out var x2);
throw H.TakeOutParam(3, out var x3);
object x3;
throw H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static System.Exception Dummy(params object[] x) {return null;}
public static System.Exception TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// throw H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// throw H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_01()
{
string source =
@"
switch (H.TakeOutParam(1, out int x1)) {default: break;}
H.Dummy(x1);
object x2;
switch (H.TakeOutParam(2, out int x2)) {default: break;}
switch (H.TakeOutParam(3, out int x3)) {default: break;}
object x3;
switch (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {default: break;}
switch (H.TakeOutParam(51, out int x5))
{
default:
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
break;
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,35): error CS0102: The type 'Script' already contains a definition for 'x2'
// switch (H.TakeOutParam(2, out int x2)) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,44): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44),
// (25,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17),
// (25,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21),
// (25,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope
// switch (H.TakeOutParam(2, out int x2)) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44),
// (17,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 37),
// (28,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_02()
{
string source =
@"
switch (H.TakeOutParam(1, out var x1)) {default: break;}
H.Dummy(x1);
object x2;
switch (H.TakeOutParam(2, out var x2)) {default: break;}
switch (H.TakeOutParam(3, out var x3)) {default: break;}
object x3;
switch (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {default: break;}
switch (H.TakeOutParam(51, out var x5))
{
default:
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
break;
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,35): error CS0102: The type 'Script' already contains a definition for 'x2'
// switch (H.TakeOutParam(2, out var x2)) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,44): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44),
// (25,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17),
// (25,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21),
// (25,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope
// switch (H.TakeOutParam(2, out var x2)) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44),
// (17,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 34),
// (28,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
switch (H.TakeOutParam(1, out var x1))
{
default:
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
break;
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_WhileStatement_01()
{
string source =
@"
while (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
while (H.TakeOutParam(2, out int x2)) {}
while (H.TakeOutParam(3, out int x3)) {}
object x3;
while (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
while (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(3, out int x3)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_WhileStatement_02()
{
string source =
@"
while (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
while (H.TakeOutParam(2, out var x2)) {}
while (H.TakeOutParam(3, out var x3)) {}
object x3;
while (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
while (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(3, out var x3)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_WhileStatement_03()
{
string source =
@"
while (H.TakeOutParam(1, out var x1))
{
System.Console.WriteLine(x1);
break;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void GlobalCode_DoStatement_01()
{
string source =
@"
do {} while (H.TakeOutParam(1, out int x1));
H.Dummy(x1);
object x2;
do {} while (H.TakeOutParam(2, out int x2));
do {} while (H.TakeOutParam(3, out int x3));
object x3;
do {} while (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4)));
do
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
while (H.TakeOutParam(51, out int x5));
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(2, out int x2));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40),
// (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(3, out int x3));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (22,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_DoStatement_02()
{
string source =
@"
do {} while (H.TakeOutParam(1, out var x1));
H.Dummy(x1);
object x2;
do {} while (H.TakeOutParam(2, out var x2));
do {} while (H.TakeOutParam(3, out var x3));
object x3;
do {} while (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4)));
do
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
while (H.TakeOutParam(51, out var x5));
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(2, out var x2));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40),
// (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(3, out var x3));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (22,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_DoStatement_03()
{
string source =
@"
int f = 1;
do
{
}
while (H.TakeOutParam(f++, out var x1) && Test(x1) < 3);
int Test(int x)
{
System.Console.WriteLine(x);
return x;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void GlobalCode_LockStatement_01()
{
string source =
@"
lock (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
lock (H.TakeOutParam(2, out int x2)) {}
lock (H.TakeOutParam(3, out int x3)) {}
object x3;
lock (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
lock (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static object Dummy(params object[] x) {return true;}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// lock (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// lock (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_LockStatement_02()
{
string source =
@"
lock (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
lock (H.TakeOutParam(2, out var x2)) {}
lock (H.TakeOutParam(3, out var x3)) {}
object x3;
lock (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
lock (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static object Dummy(params object[] x) {return true;}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// lock (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// lock (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_LockStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
lock (H.TakeOutParam(1, out var x1))
{
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_LockStatement_04()
{
string source =
@"
System.Console.WriteLine(x1);
lock (H.TakeOutParam(1, out var x1))
H.Dummy(H.TakeOutParam(""11"", out var x1), x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static void Dummy(object x, object y)
{
System.Console.WriteLine(y);
}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_DeconstructionDeclarationStatement_01()
{
string source =
@"
(bool a, int b) = (H.TakeOutParam(1, out int x1), 1);
H.Dummy(x1);
object x2;
(bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
(bool e, int f) = (H.TakeOutParam(3, out int x3), 3);
object x3;
(bool g, bool h) = (H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
(bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
H.TakeOutParam(6, out int x6));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref[0]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (16,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(16, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref[0]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_01()
{
string source =
@"
a: H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
b: H.TakeOutParam(2, out int x2);
c: H.TakeOutParam(3, out int x3);
object x3;
d: H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,30): error CS0102: The type 'Script' already contains a definition for 'x2'
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,39): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39),
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_02()
{
string source =
@"
a: H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
b: H.TakeOutParam(2, out var x2);
c: H.TakeOutParam(3, out var x3);
object x3;
d: H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,30): error CS0102: The type 'Script' already contains a definition for 'x2'
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,39): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39),
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_LabeledStatement_04()
{
string source =
@"
a:
bool b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
c:
bool d = H.TakeOutParam(2, out int x2);
e:
bool f = H.TakeOutParam(3, out int x3);
object x3;
g:
bool h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
i:
bool x5 = H.TakeOutParam(5, out int x5);
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutField(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// bool x5 = H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
VerifyNotAnOutLocal(model, x5Ref[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_05()
{
string source =
@"
a:
bool b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
c:
bool d = H.TakeOutParam(2, out var x2);
e:
bool f = H.TakeOutParam(3, out var x3);
object x3;
g:
bool h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
i:
bool x5 = H.TakeOutParam(5, out var x5);
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutField(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// bool x5 = H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
VerifyNotAnOutLocal(model, x5Ref[1]);
}
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
public void GlobalCode_LabeledStatement_06_Script()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_LabeledStatement_06_SimpleProgram()
{
string source =
@"
a:b:c:
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(compilation, expectedOutput:
@"1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_07()
{
string source =
@"l1:
(bool a, int b) = (H.TakeOutParam(1, out int x1), 1);
H.Dummy(x1);
object x2;
l2:
(bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
l3:
(bool e, int f) = (H.TakeOutParam(3, out int x3), 3);
object x3;
l4:
(bool g, bool h) = (H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
l5:
(bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
H.TakeOutParam(6, out int x6));
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (22,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref);
}
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_08()
{
string source =
@"l1:
(bool a, int b) = (H.TakeOutParam(1, out var x1), 1);
H.Dummy(x1);
object x2;
l2:
(bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
l3:
(bool e, int f) = (H.TakeOutParam(3, out var x3), 3);
object x3;
l4:
(bool g, bool h) = (H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
l5:
(bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
H.TakeOutParam(6, out var x6));
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out var x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out var x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (22,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref);
}
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_09()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:
var (d, e) = (H.TakeOutParam(1, out var x1), 1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_01()
{
string source =
@"
bool b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
bool d = H.TakeOutParam(2, out int x2);
bool f = H.TakeOutParam(3, out int x3);
object x3;
bool h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
bool x5 =
H.TakeOutParam(5, out int x5);
bool i = H.TakeOutParam(5, out int x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope
// x6;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10),
// (19,10): warning CS0168: The variable 'x6' is declared but never used
// x6;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
}
}
[Fact]
public void GlobalCode_FieldDeclaration_02()
{
string source =
@"
bool b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
bool d = H.TakeOutParam(2, out var x2);
bool f = H.TakeOutParam(3, out var x3);
object x3;
bool h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
bool x5 =
H.TakeOutParam(5, out var x5);
bool i = H.TakeOutParam(5, out var x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope
// x6;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10),
// (19,10): warning CS0168: The variable 'x6' is declared but never used
// x6;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
}
}
[Fact]
public void GlobalCode_FieldDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static var b = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_05()
{
string source =
@"
bool b = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_06()
{
string source =
@"
bool b = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_07()
{
string source =
@"
Test();
bool a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2);
Test();
bool Test()
{
System.Console.WriteLine(""{0} {1}"", x1, x2);
return false;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0 0
1 0
1 2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_01()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
bool d { get; } = H.TakeOutParam(2, out int x2);
bool f { get; } = H.TakeOutParam(3, out int x3);
object x3;
bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
bool x5 { get; } =
H.TakeOutParam(5, out int x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,45): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d { get; } = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,54): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25),
// (20,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool b { get; } = H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool d { get; } = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6),
// (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool f { get; } = H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6),
// (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6),
// (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54),
// (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool x5 { get; } =
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6),
// (20,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13),
// (20,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25),
// (20,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1),
// (23,1): error CS0165: Use of unassigned local variable 'x3'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
}
}
[Fact]
public void GlobalCode_PropertyDeclaration_02()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
bool d { get; } = H.TakeOutParam(2, out var x2);
bool f { get; } = H.TakeOutParam(3, out var x3);
object x3;
bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
bool x5 { get; } =
H.TakeOutParam(5, out var x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,45): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d { get; } = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,54): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25),
// (20,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool b { get; } = H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool d { get; } = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6),
// (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool f { get; } = H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6),
// (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6),
// (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54),
// (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool x5 { get; } =
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6),
// (20,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13),
// (20,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25),
// (20,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1),
// (23,1): error CS0165: Use of unassigned local variable 'x3'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
}
}
[Fact]
public void GlobalCode_PropertyDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
bool d { get; set; } = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static bool b { get; } = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_05()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_06()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_01()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
event System.Action d = H.TakeOutParam(2, out int x2);
event System.Action f = H.TakeOutParam(3, out int x3);
object x3;
event System.Action h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
event System.Action x5 =
H.TakeOutParam(5, out int x5);
event System.Action i = H.TakeOutParam(5, out int x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,51): error CS0102: The type 'Script' already contains a definition for 'x2'
// event System.Action d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,52): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected };
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29),
// (23,33): error CS0103: The name 'x6' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
}
[Fact]
public void GlobalCode_EventDeclaration_02()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
event System.Action d = H.TakeOutParam(2, out var x2);
event System.Action f = H.TakeOutParam(3, out var x3);
object x3;
event System.Action h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
event System.Action x5 =
H.TakeOutParam(5, out var x5);
event System.Action i = H.TakeOutParam(5, out var x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,51): error CS0102: The type 'Script' already contains a definition for 'x2'
// event System.Action d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,52): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected };
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29),
// (23,33): error CS0103: The name 'x6' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
}
[Fact]
public void GlobalCode_EventDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
event System.Action d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static event System.Action b = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_05()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_06()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_07()
{
string source =
@"
Test();
event System.Action a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2);
Test();
System.Action Test()
{
System.Console.WriteLine(""{0} {1}"", x1, x2);
return null;
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0 0
1 0
1 2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_DeclaratorArguments_01()
{
string source =
@"
bool a, b(out var x1);
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,21): error CS1003: Syntax error, ']' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21),
// (3,19): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(3, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,21): error CS1003: Syntax error, ']' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21),
// (3,6): warning CS0168: The variable 'a' is declared but never used
// bool a, b(out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6),
// (3,9): warning CS0168: The variable 'b' is declared but never used
// bool a, b(out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_02()
{
string source =
@"
label:
bool a, b(H.TakeOutParam(1, out var x1));
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,40): error CS1003: Syntax error, ']' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40),
// (2,1): warning CS0164: This label has not been referenced
// label:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,40): error CS1003: Syntax error, ']' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40),
// (2,1): warning CS0164: This label has not been referenced
// label:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1),
// (4,9): error CS0165: Use of unassigned local variable 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(4, 9),
// (3,6): warning CS0168: The variable 'a' is declared but never used
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6),
// (3,9): warning CS0168: The variable 'b' is declared but never used
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_03()
{
string source =
@"
event System.Action a, b(H.TakeOutParam(1, out var x1));
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25),
// (3,25): error CS1003: Syntax error, '[' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25),
// (3,55): error CS1003: Syntax error, ']' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25),
// (3,25): error CS1003: Syntax error, '[' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25),
// (3,55): error CS1003: Syntax error, ']' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6),
// (8,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelNotSupported(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_04()
{
string source =
@"
fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static int TakeOutParam<T>(T y, out T x)
{
x = y;
return 3;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"),
parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,18): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18),
// (3,20): error CS0133: The expression being assigned to 'b' must be constant
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("b").WithLocation(3, 20),
// (3,12): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12),
// (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,12): error CS0116: A namespace cannot directly contain members such as fields or methods
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(3, 12),
// (3,18): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18),
// (3,20): error CS0133: The expression being assigned to '<invalid-global-code>.b' must be constant
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("<invalid-global-code>.b").WithLocation(3, 20),
// (3,12): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12),
// (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (8,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelNotSupported(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
}
}
[Fact]
public void GlobalCode_RestrictedType_01()
{
string source =
@"
H.TakeOutParam(out var x1);
H.TakeOutParam(out System.ArgIterator x2);
class H
{
public static void TakeOutParam(out System.ArgIterator x)
{
x = default(System.ArgIterator);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (9,37): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// public static void TakeOutParam(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 37),
// (5,20): error CS0610: Field or property cannot be of type 'ArgIterator'
// H.TakeOutParam(out System.ArgIterator x2);
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(5, 20),
// (3,20): error CS0610: Field or property cannot be of type 'ArgIterator'
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "var").WithArguments("System.ArgIterator").WithLocation(3, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl);
}
[Fact]
public void GlobalCode_StaticType_01()
{
string source =
@"
H.TakeOutParam(out var x1);
H.TakeOutParam(out StaticType x2);
class H
{
public static void TakeOutParam(out StaticType x)
{
x = default(System.ArgIterator);
}
}
static class StaticType{}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (5,31): error CS0723: Cannot declare a variable of static type 'StaticType'
// H.TakeOutParam(out StaticType x2);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x2").WithArguments("StaticType").WithLocation(5, 31),
// (9,24): error CS0721: 'StaticType': static types cannot be used as parameters
// public static void TakeOutParam(out StaticType x)
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "TakeOutParam").WithArguments("StaticType").WithLocation(9, 24),
// (3,24): error CS0723: Cannot declare a variable of static type 'StaticType'
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x1").WithArguments("StaticType").WithLocation(3, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl);
}
[Fact]
public void GlobalCode_InferenceFailure_01()
{
string source =
@"
H.TakeOutParam(out var x1, x1);
class H
{
public static void TakeOutParam(out int x, long y)
{
x = 1;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (3,24): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.TakeOutParam(out var x1, x1);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact]
public void GlobalCode_InferenceFailure_02()
{
string source =
@"
var a = b;
var b = H.TakeOutParam(out var x1, a);
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single());
Assert.True(b.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = H.TakeOutParam(out var x1, a);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
}
[Fact]
public void GlobalCode_InferenceFailure_03()
{
string source =
@"
var a = H.TakeOutParam(out var x1, b);
var b = a;
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single());
Assert.True(b.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = a;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
}
[Fact]
public void GlobalCode_InferenceFailure_04()
{
string source =
@"
var a = x1;
var b = H.TakeOutParam(out var x1, a);
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var a = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "a").Single());
Assert.True(a.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (3,5): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var a = x1;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(3, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclarations(tree, "x1").Single();
x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = H.TakeOutParam(out var x1, a);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(4, 32)
);
}
[Fact]
public void GlobalCode_InferenceFailure_05()
{
string source =
@"
var a = H.TakeOutParam(out var x1, b);
var b = x1;
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (3,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var a = H.TakeOutParam(out var x1, b);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 32)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var bDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single();
var b = (IFieldSymbol)model.GetDeclaredSymbol(bDecl);
Assert.True(b.Type.IsErrorType());
x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
Assert.False(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = x1;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
}
[Fact]
public void GlobalCode_InferenceFailure_06()
{
string source =
@"
H.TakeOutParam(out var x1);
class H
{
public static int TakeOutParam<T>(out T x)
{
x = default(T);
return 123;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24),
// (2,3): error CS0411: The type arguments for method 'H.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("H.TakeOutParam<T>(out T)").WithLocation(2, 3)
);
compilation.GetDeclarationDiagnostics().Verify(
// (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/17377")]
public void GlobalCode_InferenceFailure_07()
{
string source =
@"
H.M((var x1, int x2));
H.M(x1);
class H
{
public static void M(object a) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10),
// (2,6): error CS8185: A declaration is not allowed in this context.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(2, 6),
// (2,14): error CS8185: A declaration is not allowed in this context.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(2, 14),
// (2,5): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, int x2)").WithArguments("System.ValueTuple`2").WithLocation(2, 5),
// (2,5): error CS1503: Argument 1: cannot convert from '(var, int)' to 'object'
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_BadArgType, "(var x1, int x2)").WithArguments("1", "(var, int)", "object").WithLocation(2, 5)
);
compilation.GetDeclarationDiagnostics().Verify(
// (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact, WorkItem(17321, "https://github.com/dotnet/roslyn/issues/17321")]
public void InferenceFailure_01()
{
string source =
@"
class H
{
object M1() => M(M(1), x1);
static object M(object o1) => o1;
static void M(object o1, object o2) {}
}
";
var node0 = SyntaxFactory.ParseCompilationUnit(source);
var one = node0.DescendantNodes().OfType<LiteralExpressionSyntax>().Single();
var decl = SyntaxFactory.DeclarationExpression(
type: SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("var")),
designation: SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier("x1")));
var node1 = node0.ReplaceNode(one, decl);
var tree = node1.SyntaxTree;
Assert.NotNull(tree);
var compilation = CreateCompilation(new[] { tree });
compilation.VerifyDiagnostics(
// (4,24): error CS8185: A declaration is not allowed in this context.
// object M1() => M(M(varx1), x1);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "varx1").WithLocation(4, 24)
);
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_AliasInfo_01()
{
string source =
@"
H.TakeOutParam(1, out var x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void GlobalCode_AliasInfo_02()
{
string source =
@"
using var = System.Int32;
H.TakeOutParam(1, out var x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GlobalCode_AliasInfo_03()
{
string source =
@"
using a = System.Int32;
H.TakeOutParam(1, out a x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GlobalCode_AliasInfo_04()
{
string source =
@"
H.TakeOutParam(1, out int x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")]
public void ExpressionVariableInCase_1()
{
string source =
@"
class Program
{
static void Main(string[] args)
{
switch (true)
{
case !TakeOutParam(3, out var x1):
System.Console.WriteLine(x1);
break;
}
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// The point of this test is that it should not crash.
compilation.VerifyDiagnostics(
// (8,18): error CS0150: A constant value is expected
// case !TakeOutParam(3, out var x1):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!TakeOutParam(3, out var x1)").WithLocation(8, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
[Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")]
public void ExpressionVariableInCase_2()
{
string source =
@"
class Program
{
static void Main(string[] args)
{
switch (true)
{
case !TakeOutParam(3, out UndeclaredType x1):
System.Console.WriteLine(x1);
break;
}
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// The point of this test is that it should not crash.
compilation.VerifyDiagnostics(
// (8,19): error CS0103: The name 'TakeOutParam' does not exist in the current context
// case !TakeOutParam(3, out UndeclaredType x1):
Diagnostic(ErrorCode.ERR_NameNotInContext, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(8, 19),
// (8,39): error CS0246: The type or namespace name 'UndeclaredType' could not be found (are you missing a using directive or an assembly reference?)
// case !TakeOutParam(3, out UndeclaredType x1):
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndeclaredType").WithArguments("UndeclaredType").WithLocation(8, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
private static void VerifyModelForOutField(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
VerifyModelForOutField(model, decl, false, references);
}
private static void VerifyModelForOutFieldDuplicate(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
VerifyModelForOutField(model, decl, true, references);
}
private static void VerifyModelForOutField(
SemanticModel model,
DeclarationExpressionSyntax decl,
bool duplicate,
params IdentifierNameSyntax[] references)
{
var variableDesignationSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDesignationSyntax);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(SymbolKind.Field, symbol.Kind);
Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax));
var symbols = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText);
var names = model.LookupNames(decl.SpanStart);
if (duplicate)
{
Assert.True(symbols.Count() > 1);
Assert.Contains(symbol, symbols);
}
else
{
Assert.Same(symbol, symbols.Single());
}
Assert.Contains(decl.Identifier().ValueText, names);
var local = (IFieldSymbol)symbol;
var declarator = decl.Ancestors().OfType<VariableDeclaratorSyntax>().FirstOrDefault();
var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement &&
(declarator.ArgumentList?.Contains(decl)).GetValueOrDefault();
// We're not able to get type information at such location (out var argument in global code) at this point
// See https://github.com/dotnet/roslyn/issues/13569
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: inFieldDeclaratorArgumentlist ? null : local.Type);
foreach (var reference in references)
{
var referenceInfo = model.GetSymbolInfo(reference);
symbols = model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText);
if (duplicate)
{
Assert.Null(referenceInfo.Symbol);
Assert.Contains(symbol, referenceInfo.CandidateSymbols);
Assert.True(symbols.Count() > 1);
Assert.Contains(symbol, symbols);
}
else
{
Assert.Same(symbol, referenceInfo.Symbol);
Assert.Same(symbol, symbols.Single());
Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
}
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
}
if (!inFieldDeclaratorArgumentlist)
{
var dataFlowParent = (ExpressionSyntax)decl.Parent.Parent.Parent;
if (model.IsSpeculativeSemanticModel)
{
Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent));
}
else
{
var dataFlow = model.AnalyzeDataFlow(dataFlowParent);
if (dataFlow.Succeeded)
{
Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
}
}
}
}
[Fact]
public void MethodTypeArgumentInference_01()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out int a);
TakeOutParam(out long b);
}
static void TakeOutParam<T>(out T x)
{
x = default(T);
System.Console.WriteLine(typeof(T));
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.Int32
System.Int64");
}
[Fact]
public void MethodTypeArgumentInference_02()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var a);
}
static void TakeOutParam<T>(out T x)
{
x = default(T);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out var a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T)").WithLocation(6, 9)
);
}
[Fact]
public void MethodTypeArgumentInference_03()
{
var source =
@"
public class X
{
public static void Main()
{
long a = 0;
TakeOutParam(out int b, a);
int c;
TakeOutParam(out c, a);
}
static void TakeOutParam<T>(out T x, T y)
{
x = default(T);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out int b, a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(7, 9),
// (9,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out c, a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(9, 9)
);
}
[Fact]
public void MethodTypeArgumentInference_04()
{
var source =
@"
public class X
{
public static void Main()
{
byte a = 0;
int b = 0;
TakeOutParam(out int c, a);
TakeOutParam(out b, a);
}
static void TakeOutParam<T>(out T x, T y)
{
x = default(T);
System.Console.WriteLine(typeof(T));
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.Int32
System.Int32");
}
[Fact, WorkItem(14825, "https://github.com/dotnet/roslyn/issues/14825")]
public void OutVarDeclaredInReceiverUsedInArgument()
{
var source =
@"using System.Linq;
public class C
{
public string[] Goo2(out string x) { x = """"; return null; }
public string[] Goo3(bool b) { return null; }
public string[] Goo5(string u) { return null; }
public void Test()
{
var t1 = Goo2(out var x1).Concat(Goo5(x1));
var t2 = Goo3(t1 is var x2).Concat(Goo5(x2.First()));
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.String", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString());
}
[Fact]
public void OutVarDiscard()
{
var source =
@"
public class C
{
static void Main()
{
M(out int _);
M(out var _);
M(out _);
}
static void M(out int x) { x = 1; System.Console.Write(""M""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "MMM");
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.Single();
var model = comp.Compilation.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetTypeInfo(discard1).Type);
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("int _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetTypeInfo(discard2).Type);
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
var discard3 = GetDiscardIdentifiers(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard3));
var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol;
Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
comp.VerifyIL("C.Main()", @"
{
// Code size 22 (0x16)
.maxstack 1
.locals init (int V_0)
IL_0000: ldloca.s V_0
IL_0002: call ""void C.M(out int)""
IL_0007: ldloca.s V_0
IL_0009: call ""void C.M(out int)""
IL_000e: ldloca.s V_0
IL_0010: call ""void C.M(out int)""
IL_0015: ret
}
");
}
[Fact]
public void NamedOutVarDiscard()
{
var source =
@"
public class C
{
static void Main()
{
M(y: out string _, x: out int _);
M(y: out var _, x: out var _);
M(y: out _, x: out _);
}
static void M(out int x, out string y) { x = 1; y = ""hello""; System.Console.Write(""M""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "MMM");
comp.VerifyDiagnostics();
}
[Fact]
public void OutVarDiscardInCtor_01()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out int i1);
new C(out int _);
new C(out var _);
new C(out _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CCCC");
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("int _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("int", declaration1.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration2.Type));
var discard3 = GetDiscardIdentifiers(tree).First();
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol;
Assert.Equal("int _", discard3Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
}
[Fact]
public void OutVarDiscardInCtor_02()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out long x1);
new C(out long _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int'
// new C(out long x1);
Diagnostic(ErrorCode.ERR_BadArgType, "long x1").WithArguments("1", "out long", "out int").WithLocation(7, 19),
// (8,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int'
// new C(out long _);
Diagnostic(ErrorCode.ERR_BadArgType, "long _").WithArguments("1", "out long", "out int").WithLocation(8, 19),
// (7,19): error CS0165: Use of unassigned local variable 'x1'
// new C(out long x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x1").WithArguments("x1").WithLocation(7, 19)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVarWithoutDataFlow(model, x1Decl);
var discard1 = GetDiscardDesignations(tree).Single();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("long _", declaration1.ToString());
Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("long", declaration1.Type.ToString());
Assert.Equal("System.Int64", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int64", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int64", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
}
[Fact]
public void OutVarDiscardAliasInfo_01()
{
var source =
@"
using alias1 = System.Int32;
using var = System.Int32;
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out alias1 _);
new C(out var _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CC");
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("alias1 _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("alias1", declaration1.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Equal("alias1=System.Int32", model.GetAliasInfo(declaration1.Type).ToTestDisplayString());
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Equal("var=System.Int32", model.GetAliasInfo(declaration2.Type).ToTestDisplayString());
}
[Fact]
public void OutVarDiscardAliasInfo_02()
{
var source =
@"
enum alias1 : long {}
class var {}
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out alias1 _);
new C(out var _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (10,19): error CS1503: Argument 1: cannot convert from 'out alias1' to 'out int'
// new C(out alias1 _);
Diagnostic(ErrorCode.ERR_BadArgType, "alias1 _").WithArguments("1", "out alias1", "out int").WithLocation(10, 19),
// (11,19): error CS1503: Argument 1: cannot convert from 'out var' to 'out int'
// new C(out var _);
Diagnostic(ErrorCode.ERR_BadArgType, "var _").WithArguments("1", "out var", "out int").WithLocation(11, 19)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("alias1 _", declaration1.ToString());
Assert.Equal("alias1", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("alias1", declaration1.Type.ToString());
Assert.Equal("alias1", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("alias1", typeInfo.Type.ToTestDisplayString());
Assert.Equal("alias1", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("var", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, model.GetTypeInfo(declaration2).Type.TypeKind);
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("var", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration2.Type));
}
[Fact]
public void OutVarDiscardInCtorInitializer()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C ""); }
static void Main()
{
new Derived2(out int i2);
new Derived3(out int i3);
new Derived4();
}
}
public class Derived2 : C
{
public Derived2(out int i) : base(out int _) { i = 2; System.Console.Write(""Derived2 ""); }
}
public class Derived3 : C
{
public Derived3(out int i) : base(out var _) { i = 3; System.Console.Write(""Derived3 ""); }
}
public class Derived4 : C
{
public Derived4(out int i) : base(out _) { i = 4; }
public Derived4() : this(out _) { System.Console.Write(""Derived4""); }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C Derived2 C Derived3 C Derived4");
}
[Fact]
public void DiscardNotRecognizedInOtherScenarios()
{
var source =
@"
public class C
{
void M<T>()
{
_.ToString();
M(_);
_<T>.ToString();
(_<T>, _<T>) = (1, 2);
M<_>();
new C() { _ = 1 };
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (6,9): error CS0103: The name '_' does not exist in the current context
// _.ToString();
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 9),
// (7,11): error CS0103: The name '_' does not exist in the current context
// M(_);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 11),
// (8,9): error CS0103: The name '_' does not exist in the current context
// _<T>.ToString();
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(8, 9),
// (9,10): error CS0103: The name '_' does not exist in the current context
// (_<T>, _<T>) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 10),
// (9,16): error CS0103: The name '_' does not exist in the current context
// (_<T>, _<T>) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 16),
// (10,11): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?)
// M<_>();
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(10, 11),
// (11,19): error CS0117: 'C' does not contain a definition for '_'
// new C() { _ = 1 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "_").WithArguments("C", "_").WithLocation(11, 19)
);
}
[Fact]
public void TypedDiscardInMethodTypeInference()
{
var source =
@"
public class C
{
static void M<T>(out T t)
{
t = default(T);
System.Console.Write(t.GetType().ToString());
}
static void Main()
{
M(out int _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "System.Int32");
}
[Fact]
public void UntypedDiscardInMethodTypeInference()
{
var source =
@"
public class C
{
static void M<T>(out T t)
{
t = default(T);
}
static void Main()
{
M(out var _);
M(out _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (10,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(out var _);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(10, 9),
// (11,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(out _);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(11, 9)
);
}
[Fact]
public void PickOverloadWithTypedDiscard()
{
var source =
@"
public class C
{
static void M(out object x) { x = 1; System.Console.Write(""object returning M. ""); }
static void M(out int x) { x = 2; System.Console.Write(""int returning M.""); }
static void Main()
{
M(out object _);
M(out int _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "object returning M. int returning M.");
}
[Fact]
public void CannotPickOverloadWithUntypedDiscard()
{
var source =
@"
public class C
{
static void M(out object x) { x = 1; }
static void M(out int x) { x = 2; }
static void Main()
{
M(out var _);
M(out _);
M(out byte _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)'
// M(out var _);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(8, 9),
// (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)'
// M(out _);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(9, 9),
// (10,15): error CS1503: Argument 1: cannot convert from 'out byte' to 'out object'
// M(out byte _);
Diagnostic(ErrorCode.ERR_BadArgType, "byte _").WithArguments("1", "out byte", "out object").WithLocation(10, 15)
);
}
[Fact]
public void NoOverloadWithDiscard()
{
var source =
@"
public class A { }
public class B : A
{
static void M(A a)
{
a.M2(out A x);
a.M2(out A _);
}
}
public static class S
{
public static void M2(this A self, out B x) { x = null; }
}";
var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll, references: new[] { Net40.SystemCore });
comp.VerifyDiagnostics(
// (7,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B'
// a.M2(out A x);
Diagnostic(ErrorCode.ERR_BadArgType, "A x").WithArguments("2", "out A", "out B").WithLocation(7, 18),
// (8,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B'
// a.M2(out A _);
Diagnostic(ErrorCode.ERR_BadArgType, "A _").WithArguments("2", "out A", "out B").WithLocation(8, 18)
);
}
[Fact]
[WorkItem(363727, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/363727")]
public void FindCorrectBinderOnEmbeddedStatementWithMissingIdentifier()
{
var source =
@"
public class C
{
static void M(string x)
{
if(true)
&& int.TryParse(x, out int y)) id(iVal);
// Note that the embedded statement is parsed as a missing identifier, followed by && with many spaces attached as leading trivia
}
}";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "x").Single();
Assert.Equal("x", x.ToString());
Assert.Equal("System.String x", model.GetSymbolInfo(x).Symbol.ToTestDisplayString());
}
[Fact]
public void DuplicateDeclarationInSwitchBlock()
{
var text = @"
public class C
{
public static void Main(string[] args)
{
switch (args.Length)
{
case 0:
M(M(out var x1), x1);
M(M(out int x1), x1);
break;
case 1:
M(M(out int x1), x1);
break;
}
}
static int M(out int z) => z = 1;
static int M(int a, int b) => a+b;
}";
var comp = CreateCompilationWithMscorlib45(text);
comp.VerifyDiagnostics(
// (10,29): error CS0128: A local variable or function named 'x1' is already defined in this scope
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(10, 29),
// (13,29): error CS0128: A local variable or function named 'x1' is already defined in this scope
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 29),
// (13,34): error CS0165: Use of unassigned local variable 'x1'
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 34)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var x6Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x6Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x6Decl.Length);
Assert.Equal(3, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[2]);
}
[Fact]
public void DeclarationInLocalFunctionParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
int x = z1 + z2;
}
static int M(out int z) => z = 1;
static bool M(int a, int b) => a+b == 0;
}
";
// 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,75): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 75),
// (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z1), z1)").WithArguments("b").WithLocation(6, 30),
// (6,61): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61),
// (7,75): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 75),
// (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z2), z2)").WithArguments("b").WithLocation(7, 30),
// (7,61): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61),
// (9,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17),
// (9,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22),
// (6,14): warning CS8321: The local function 'Local2' is declared but never used
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14),
// (7,14): warning CS8321: The local function 'Local5' is declared but never used
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInAnonymousMethodParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
System.Action<bool, int> d1 = delegate (
bool b = M(M(out int z1), z1),
int s2 = z1)
{ var t = z1; };
System.Action<bool, int> d2 = delegate (
bool b = M(M(out var z2), z2),
int s2 = z2)
{ var t = z2; };
int x = z1 + z2;
d1 = d2 = null;
}
static int M(out int z) => z = 1;
static int M(int a, int b) => a+b;
}
";
// the scope of an expression variable introduced in the default expression
// of a lambda parameter is that default expression.
var compilation = CreateCompilationWithMscorlib45(text);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_DefaultValueNotAllowed).Verify(
// (9,55): error CS0103: The name 'z1' does not exist in the current context
// { var t = z1; };
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 55),
// (13,55): error CS0103: The name 'z2' does not exist in the current context
// { var t = z2; };
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(13, 55),
// (15,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(15, 17),
// (15,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(15, 22)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var z1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "z1").First();
Assert.Equal("System.Int32", model.GetTypeInfo(z1).Type.ToTestDisplayString());
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void Scope_LocalFunction_Attribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(p = TakeOutParam(out int x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out int x4))]
[Test(p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out int x6) && x6 > 0,
p2 = TakeOutParam(out int x6) && x6 > 0)]
[Test(p = TakeOutParam(out int x7) && x7 > 0)]
[Test(p = x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,23): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23),
// (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48),
// (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45),
// (15,23): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_02()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(TakeOutParam(out int x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out int x4))]
[Test(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(TakeOutParam(out int x6) && x6 > 0,
TakeOutParam(out int x6) && x6 > 0)]
[Test(TakeOutParam(out int x7) && x7 > 0)]
[Test(x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,19): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19),
// (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44),
// (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40),
// (15,19): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_03()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(p = TakeOutParam(out var x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out var x4))]
[Test(p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out var x6) && x6 > 0,
p2 = TakeOutParam(out var x6) && x6 > 0)]
[Test(p = TakeOutParam(out var x7) && x7 > 0)]
[Test(p = x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,23): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23),
// (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48),
// (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45),
// (15,23): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_04()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(TakeOutParam(out var x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out var x4))]
[Test(TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(TakeOutParam(out var x6) && x6 > 0,
TakeOutParam(out var x6) && x6 > 0)]
[Test(TakeOutParam(out var x7) && x7 > 0)]
[Test(x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,19): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19),
// (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44),
// (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40),
// (15,19): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_05()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var x1);
TakeOutParam(out var x2);
void Local1(
[Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
int p1)
{
p1 = 0;
}
Local1(x2);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (10,44): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]);
}
[Fact]
public void Scope_LocalFunction_Attribute_06()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var x1);
TakeOutParam(out var x2);
void Local1(
[Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
int p1)
{
p1 = 0;
}
Local1(x2);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (10,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]);
}
[Fact]
public void Scope_InvalidArrayDimensions01()
{
var text = @"
public class Cls
{
public static void Main()
{
int x1 = 0;
int[Test1(out int x1), x1] _1;
int[Test1(out int x2), x2] x2;
}
static int Test1(out int x)
{
x = 1;
return 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x1), x1]").WithLocation(7, 12),
// (7,27): error CS0128: A local variable or function named 'x1' is already defined in this scope
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 27),
// (8,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x2), x2]").WithLocation(8, 12),
// (8,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(8, 36),
// (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used
// int x1 = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13),
// (7,27): warning CS0168: The variable 'x1' is declared but never used
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(7, 27),
// (7,36): warning CS0168: The variable '_1' is declared but never used
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "_1").WithArguments("_1").WithLocation(7, 36),
// (8,27): warning CS0168: The variable 'x2' is declared but never used
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 27),
// (8,36): warning CS0168: The variable 'x2' is declared but never used
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyNotAnOutLocal(model, x1Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref);
}
[Fact]
public void Scope_InvalidArrayDimensions_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
void Test1()
{
using (int[] d = null)
{
Dummy(x1);
}
}
void Test2()
{
using (int[] d = null)
Dummy(x2);
}
void Test3()
{
var x3 = 11;
Dummy(x3);
using (int[] d = null)
Dummy(x3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
// replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]'
var syntaxTree = Parse(source, filename: "file.cs");
for (int i = 0; i < 3; i++)
{
var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2);
var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single();
{
var rankSpecifierNew = rankSpecifierOld
.WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(
SyntaxFactory.NodeOrTokenList(
SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"),
SyntaxFactory.Token(SyntaxKind.CommaToken),
SyntaxFactory.ParseExpression($"x{i + 1}")
)));
syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree;
}
}
var compilation = CreateCompilation(syntaxTree, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// file.cs(12,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x1),x1] d = null").WithArguments("int[*,*]").WithLocation(12, 16),
// file.cs(12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 19),
// file.cs(12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20),
// file.cs(12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51),
// file.cs(14,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19),
// file.cs(20,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x2),x2] d = null").WithArguments("int[*,*]").WithLocation(20, 16),
// file.cs(20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(20, 19),
// file.cs(20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20),
// file.cs(20,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 51),
// file.cs(21,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19),
// file.cs(29,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x3),x3] d = null").WithArguments("int[*,*]").WithLocation(29, 16),
// file.cs(29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3),x3]").WithLocation(29, 19),
// file.cs(29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20),
// file.cs(29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// file.cs(29,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 51),
// file.cs(30,19): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]);
}
[Fact]
public void Scope_InvalidArrayDimensions_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
void Test1()
{
using int[TakeOutParam(true, out var x1), x1] d = null;
Dummy(x1);
}
void Test2()
{
var x2 = 11;
Dummy(x2);
using int[TakeOutParam(true, out var x2), x2] d = null;
Dummy(x2);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x1), x1] d = null;").WithArguments("int[*,*]").WithLocation(12, 9),
// (12,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 18),
// (12,19): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 19),
// (12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51),
// (13,15): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 15),
// (21,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x2), x2] d = null;").WithArguments("int[*,*]").WithLocation(21, 9),
// (21,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(21, 18),
// (21,19): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 19),
// (21,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(21, 46),
// (21,46): warning CS0168: The variable 'x2' is declared but never used
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(21, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(3, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyNotAnOutLocal(model, x2Ref[2]);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, isShadowed: true);
}
[Fact]
public void Scope_InvalidArrayDimensions_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(object x) {return true;}
void Test1()
{
for (int[] a = null;;)
Dummy(x1);
}
void Test2()
{
var x2 = 11;
Dummy(x2);
for (int[] a = null;;)
Dummy(x2);
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
// replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]'
var syntaxTree = Parse(source, filename: "file.cs");
for (int i = 0; i < 2; i++)
{
var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2);
var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single();
{
var rankSpecifierNew = rankSpecifierOld
.WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(
SyntaxFactory.NodeOrTokenList(
SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"),
SyntaxFactory.Token(SyntaxKind.CommaToken),
SyntaxFactory.ParseExpression($"x{i + 1}")
)));
syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree;
}
}
var compilation = CreateCompilation(syntaxTree, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// file.cs(12,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 17),
// file.cs(12,18): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 18),
// file.cs(12,49): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 49),
// file.cs(13,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 19),
// file.cs(12,53): warning CS0219: The variable 'a' is assigned but its value is never used
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(12, 53),
// file.cs(21,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(21, 17),
// file.cs(21,45): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 45),
// file.cs(21,18): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 18),
// file.cs(21,49): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(21, 49),
// file.cs(22,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(22, 19),
// file.cs(21,53): warning CS0219: The variable 'a' is assigned but its value is never used
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(21, 53)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(3, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref[1], x2Ref[2]);
}
[Fact]
public void Scope_InvalidArrayDimensions_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
unsafe void Test1()
{
fixed (int[TakeOutParam(true, out var x1), x1] d = null)
{
Dummy(x1);
}
}
unsafe void Test2()
{
fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Dummy(x2);
}
unsafe void Test3()
{
var x3 = 11;
Dummy(x3);
fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Dummy(x3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test1()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test1").WithLocation(10, 17),
// (12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 19),
// (12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20),
// (12,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 52),
// (12,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(12, 56),
// (14,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19),
// (18,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test2()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test2").WithLocation(18, 17),
// (20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(20, 19),
// (20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20),
// (20,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 52),
// (20,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(20, 56),
// (21,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19),
// (24,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test3()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test3").WithLocation(24, 17),
// (29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3), x3]").WithLocation(29, 19),
// (29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20),
// (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// (29,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 52),
// (29,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(29, 56),
// (30,19): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]);
}
[Fact]
public void DeclarationInNameof_00()
{
var text = @"
class C
{
public static void Main()
{
var x = nameof(M2(M1(out var x1), x1)).ToString();
}
static int M1(out int z) => z = 1;
static int M2(int a, int b) => 2;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,24): error CS8081: Expression does not have a name.
// var x = nameof(M2(M1(out var x1), x1)).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M2(M1(out var x1), x1)").WithLocation(6, 24)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var name = "x1";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(1, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
[Fact]
public void DeclarationInNameof_01()
{
var text = @"
class C
{
public static void Main(int arg)
{
void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
int x = z1 + z2;
}
static int M(out int z) => z = 1;
static bool M(object a, int b) => b == 0;
}
";
// 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,83): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 83),
// (6,39): error CS8081: Expression does not have a name.
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 39),
// (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out int z1)), z1)").WithArguments("b").WithLocation(6, 30),
// (6,69): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 69),
// (7,83): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 83),
// (7,39): error CS8081: Expression does not have a name.
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 39),
// (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 30),
// (7,69): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 69),
// (9,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17),
// (9,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22),
// (6,14): warning CS8321: The local function 'Local2' is declared but never used
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14),
// (7,14): warning CS8321: The local function 'Local5' is declared but never used
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, reference: refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_02a()
{
var text = @"
[My(C.M(nameof(C.M(out int z1)), z1), z1)]
[My(C.M(nameof(C.M(out var z2)), z2), z2)]
class C
{
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
class MyAttribute: System.Attribute
{
public MyAttribute(bool x, int y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (2,16): error CS8081: Expression does not have a name.
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 16),
// (2,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 5),
// (2,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 39),
// (3,16): error CS8081: Expression does not have a name.
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 16),
// (3,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 5),
// (3,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 39)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_02b()
{
var text1 = @"
[assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
[assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
";
var text2 = @"
class C
{
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
class MyAttribute: System.Attribute
{
public MyAttribute(bool x, int y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(new[] { text1, text2 });
compilation.VerifyDiagnostics(
// (2,26): error CS8081: Expression does not have a name.
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 26),
// (2,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 15),
// (2,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 49),
// (3,26): error CS8081: Expression does not have a name.
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 26),
// (3,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 15),
// (3,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 49)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_03()
{
var text = @"
class C
{
public static void Main(string[] args)
{
switch ((object)args.Length)
{
case !M(nameof(M(out int z1)), z1):
System.Console.WriteLine(z1);
break;
case !M(nameof(M(out var z2)), z2):
System.Console.WriteLine(z2);
break;
}
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (8,28): error CS8081: Expression does not have a name.
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(8, 28),
// (8,18): error CS0150: A constant value is expected
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out int z1)), z1)").WithLocation(8, 18),
// (11,28): error CS8081: Expression does not have a name.
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(11, 28),
// (11,18): error CS0150: A constant value is expected
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out var z2)), z2)").WithLocation(11, 18),
// (8,44): error CS0165: Use of unassigned local variable 'z1'
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(8, 44),
// (11,44): error CS0165: Use of unassigned local variable 'z2'
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(11, 44)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_04()
{
var text = @"
class C
{
const bool a = M(nameof(M(out int z1)), z1);
const bool b = M(nameof(M(out var z2)), z2);
const bool c = (z1 + z2) == 0;
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (5,29): error CS8081: Expression does not have a name.
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(5, 29),
// (5,20): error CS0133: The expression being assigned to 'C.b' must be constant
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("C.b").WithLocation(5, 20),
// (6,21): error CS0103: The name 'z1' does not exist in the current context
// const bool c = (z1 + z2) == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 21),
// (6,26): error CS0103: The name 'z2' does not exist in the current context
// const bool c = (z1 + z2) == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(6, 26),
// (4,29): error CS8081: Expression does not have a name.
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(4, 29),
// (4,20): error CS0133: The expression being assigned to 'C.a' must be constant
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("C.a").WithLocation(4, 20)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_05()
{
var text = @"
class C
{
public static void Main(string[] args)
{
const bool a = M(nameof(M(out int z1)), z1);
const bool b = M(nameof(M(out var z2)), z2);
bool c = (z1 + z2) == 0;
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,33): error CS8081: Expression does not have a name.
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 33),
// (6,24): error CS0133: The expression being assigned to 'a' must be constant
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("a").WithLocation(6, 24),
// (7,33): error CS8081: Expression does not have a name.
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 33),
// (7,24): error CS0133: The expression being assigned to 'b' must be constant
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 24),
// (6,49): error CS0165: Use of unassigned local variable 'z1'
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(6, 49),
// (7,49): error CS0165: Use of unassigned local variable 'z2'
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(7, 49)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_06()
{
var text = @"
class C
{
public static void Main(string[] args)
{
string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString();
bool c = z1 == 0;
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,27): error CS8081: Expression does not have a name.
// string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(System.Action)(() => M(M(out var z1), z1))").WithLocation(6, 27),
// (7,18): error CS0103: The name 'z1' does not exist in the current context
// bool c = z1 == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(7, 18)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var name = "z1";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVar(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_01()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p =>
{
weakRef.TryGetTarget(out var x);
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_02()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p1 =>
{
void Local1 (Action<T> onNext = p2 =>
{
weakRef.TryGetTarget(out var x);
})
{
}
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_03()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p1 =>
{
void Local1 (Action<T> onNext = p2 =>
{
void Local1 (Action<T> onNext = p3 =>
{
weakRef.TryGetTarget(out var x);
})
{
}
})
{
}
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_04()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (object onNext = from p in y select weakRef.TryGetTarget(out var x))
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_05()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (object onNext = from p in y
select (Action<T>)( p =>
{
void Local2 (object onNext = from p in y select weakRef.TryGetTarget(out var x))
{
}
}
)
)
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_06()
{
string source = @"
class C
{
void M<T>()
{
System.Type t = typeof(int[p =>
{
weakRef.TryGetTarget(out var x);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_07()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[p1 =>
{
System.Type t2 = typeof(int[p2 =>
{
weakRef.TryGetTarget(out var x);
}]);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_08()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[p1 =>
{
System.Type t2 = typeof(int[p2 =>
{
System.Type t3 = typeof(int[p3 =>
{
weakRef.TryGetTarget(out var x);
}]);
}]);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_09()
{
string source = @"
class C
{
void M<T>()
{
System.Type t = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_10()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[from p in y
select (Action<T>)( p =>
{
System.Type t2 = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]);
}
)
]
);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(445600, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=445600")]
public void GetEnclosingBinderInternalRecovery_11()
{
var text = @"
class Program
{
static void Main(string[] args)
{
foreach
other(some().F(a => TestOutVar(out var x) ? x : 1));
}
static void TestOutVar(out int a)
{
a = 0;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (6,16): error CS1003: Syntax error, '(' expected
// foreach
Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", "").WithLocation(6, 16),
// (7,60): error CS1515: 'in' expected
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_InExpected, ";").WithLocation(7, 60),
// (7,60): error CS0230: Type and identifier are both required in a foreach statement
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_BadForeachDecl, ";").WithLocation(7, 60),
// (7,60): error CS1525: Invalid expression term ';'
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 60),
// (7,60): error CS1026: ) expected
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(7, 60)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var xDecl = GetOutVarDeclaration(tree, "x");
var xRef = GetReferences(tree, "x", 1);
VerifyModelForOutVarWithoutDataFlow(model, xDecl, xRef);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef[0]).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates()
{
var source =
@"using System;
class C
{
static void Main()
{
G(x => x > 0 && F(out var y) && y > 0);
}
static bool F(out int i)
{
i = 0;
return true;
}
static void G(Func<int, bool> f, object o) { }
static void G(C c, object o) { }
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (6,9): error CS1501: No overload for method 'G' takes 1 arguments
// G(x => x > 0 && F(out var y) && y > 0);
Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(6, 9));
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates_Expression()
{
var source =
@"using System;
using System.Linq.Expressions;
class C
{
static void Main()
{
G(x => x > 0 && F(out var y) && y > 0);
}
static bool F(out int i)
{
i = 0;
return true;
}
static void G(Expression<Func<int, bool>> f, object o) { }
static void G(C c, object o) { }
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (7,9): error CS1501: No overload for method 'G' takes 1 arguments
// G(x => x > 0 && F(out var y) && y > 0);
Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(7, 9));
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates_Query()
{
var source =
@"using System.Linq;
class C
{
static void M()
{
var c = from x in new[] { 1, 2, 3 }
group x > 1 && F(out var y) && y == null
by x;
}
static bool F(out object o)
{
o = null;
return true;
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")]
public void SpeculativeSemanticModelWithOutDiscard()
{
var source =
@"class C
{
static void F()
{
C.G(out _);
}
static void G(out object o)
{
o = null;
}
}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var identifierBefore = GetReferences(tree, "G").Single();
Assert.Equal(tree, identifierBefore.Location.SourceTree);
var statementBefore = identifierBefore.Ancestors().OfType<StatementSyntax>().First();
var statementAfter = SyntaxFactory.ParseStatement(@"G(out _);");
bool success = model.TryGetSpeculativeSemanticModel(statementBefore.SpanStart, statementAfter, out model);
Assert.True(success);
var identifierAfter = statementAfter.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "G");
Assert.Null(identifierAfter.Location.SourceTree);
var info = model.GetSymbolInfo(identifierAfter);
Assert.Equal("void C.G(out System.Object o)", info.Symbol.ToTestDisplayString());
}
[Fact]
[WorkItem(10604, "https://github.com/dotnet/roslyn/issues/10604")]
[WorkItem(16306, "https://github.com/dotnet/roslyn/issues/16306")]
public void GetForEachSymbolInfoWithOutVar()
{
var source =
@"using System.Collections.Generic;
public class C
{
void M()
{
foreach (var x in M2(out int i)) { }
}
IEnumerable<object> M2(out int j)
{
throw null;
}
}";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var foreachStatement = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single();
var info = model.GetForEachStatementInfo(foreachStatement);
Assert.Equal("System.Object", info.ElementType.ToTestDisplayString());
Assert.Equal("System.Collections.Generic.IEnumerator<System.Object> System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator()",
info.GetEnumeratorMethod.ToTestDisplayString());
}
[WorkItem(19382, "https://github.com/dotnet/roslyn/issues/19382")]
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void DiscardAndArgList()
{
var text = @"
using System;
public class C
{
static void Main()
{
M(out _, __arglist(2, 3, true));
}
static void M(out int x, __arglist)
{
x = 0;
DumpArgs(new ArgIterator(__arglist));
}
static void DumpArgs(ArgIterator args)
{
while(args.GetRemainingCount() > 0)
{
TypedReference tr = args.GetNextArg();
object arg = TypedReference.ToObject(tr);
Console.Write(arg);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "23True");
}
[Fact]
[WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")]
public void OutVarInArgList_01()
{
var text = @"
public class C
{
static void Main()
{
M(1, __arglist(out int y));
M(2, __arglist(out var z));
System.Console.WriteLine(z);
}
static void M(int x, __arglist)
{
x = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// M(1, __arglist(out int y));
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 28),
// (7,32): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'.
// M(2, __arglist(out var z));
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 32),
// (7,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// M(2, __arglist(out var z));
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 28)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVar(model, zDecl, zRef);
}
[Fact]
[WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")]
public void OutVarInArgList_02()
{
var text = @"
public class C
{
static void Main()
{
__arglist(out int y);
__arglist(out var z);
System.Console.WriteLine(z);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// __arglist(out int y);
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 23),
// (6,9): error CS0226: An __arglist expression may only appear inside of a call or new expression
// __arglist(out int y);
Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out int y)").WithLocation(6, 9),
// (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'.
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 27),
// (7,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 23),
// (7,9): error CS0226: An __arglist expression may only appear inside of a call or new expression
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out var z)").WithLocation(7, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVar(model, zDecl, zRef);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void OutVarInNewT_01()
{
var text = @"
public class C
{
static void M<T>() where T : new()
{
var x = new T(out var z);
System.Console.WriteLine(z);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
// var x = new T(out var z);
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z)").WithArguments("T").WithLocation(6, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef);
var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal("new T(out var z)", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out var z)')
Children(1):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z')
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void OutVarInNewT_02()
{
var text = @"
public class C
{
static void M<T>() where T : C, new()
{
var x = new T(out var z) {F1 = 1};
System.Console.WriteLine(z);
}
public int F1;
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
// var x = new T(out var z) {F1 = 1};
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z) {F1 = 1}").WithArguments("T").WithLocation(6, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef);
var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal("new T(out var z) {F1 = 1}", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out v ... z) {F1 = 1}')
Children(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z')
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: T, IsInvalid) (Syntax: '{F1 = 1}')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'F1 = 1')
Left:
IFieldReferenceOperation: System.Int32 C.F1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'F1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'F1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
");
}
[Fact]
public void EventInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1));
static System.Func<bool> GetDelegate(bool value) => () => value;
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,76): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1));
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 76)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ConstructorBodyOperation()
{
var text = @"
public class C
{
C() : this(out var x)
{ M(out var y); }
=> M(out var z);
C (out int x){x=1;}
void M (out int x){x=1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
Assert.Equal(": this(out var x)", initializerSyntax.ToString());
compilation.VerifyOperationTree(initializerSyntax, expectedOperationTree:
@"
IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation initializerOperation = model.GetOperation(initializerSyntax);
Assert.Equal(OperationKind.ExpressionStatement, initializerOperation.Parent.Kind);
var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
Assert.Equal("{ M(out var y); }", blockBodySyntax.ToString());
compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }')
Locals: Local_1: System.Int32 y
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation blockBodyOperation = model.GetOperation(blockBodySyntax);
Assert.Equal(OperationKind.ConstructorBody, blockBodyOperation.Parent.Kind);
Assert.Same(initializerOperation.Parent.Parent, blockBodyOperation.Parent);
Assert.Null(blockBodyOperation.Parent.Parent);
var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var z)", expressionBodySyntax.ToString());
compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
Assert.Same(blockBodyOperation.Parent, model.GetOperation(expressionBodySyntax).Parent);
var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
Assert.Same(blockBodyOperation.Parent, model.GetOperation(declarationSyntax));
compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'C() : this( ... out var z);')
Locals: Local_1: System.Int32 x
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Expression:
IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }')
Locals: Local_1: System.Int32 y
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ExpressionBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void MethodBodyOperation()
{
var text = @"
public class C
{
int P
{
get {return M(out var x);} => M(out var y);
} => M(out var z);
int M (out int x){x=1; return 1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var y)", expressionBodySyntax.ToString());
compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)')
Locals: Local_1: System.Int32 y
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation expressionBodyOperation = model.GetOperation(expressionBodySyntax);
Assert.Equal(OperationKind.MethodBody, expressionBodyOperation.Parent.Kind);
Assert.Null(expressionBodyOperation.Parent.Parent);
var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
Assert.Equal("{return M(out var x);}", blockBodySyntax.ToString());
compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}')
Locals: Local_1: System.Int32 x
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation blockBodyOperation = model.GetOperation(blockBodySyntax);
Assert.Same(expressionBodyOperation.Parent, blockBodyOperation.Parent);
var propertyExpressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().ElementAt(1);
Assert.Equal("=> M(out var z)", propertyExpressionBodySyntax.ToString());
Assert.Null(model.GetOperation(propertyExpressionBodySyntax)); // https://github.com/dotnet/roslyn/issues/24900
var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single();
Assert.Same(expressionBodyOperation.Parent, model.GetOperation(declarationSyntax));
compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree:
@"
IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'get {return ... out var y);')
BlockBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}')
Locals: Local_1: System.Int32 x
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ExpressionBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)')
Locals: Local_1: System.Int32 y
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void PropertyExpressionBodyOperation()
{
var text = @"
public class C
{
int P => M(out var z);
int M (out int x){x=1; return 1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node3 = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var z)", node3.ToString());
compilation.VerifyOperationTree(node3, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'M(out var z)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
Assert.Null(model.GetOperation(node3).Parent);
}
[Fact]
public void OutVarInConstructorUsedInObjectInitializer()
{
var source =
@"
public class C
{
public int Number { get; set; }
public C(out int n)
{
n = 1;
}
public static void Main()
{
C c = new C(out var i) { Number = i };
System.Console.WriteLine(c.Number);
}
}
";
CompileAndVerify(source, expectedOutput: @"1");
}
[Fact]
public void OutVarInConstructorUsedInCollectionInitializer()
{
var source =
@"
public class C : System.Collections.Generic.List<int>
{
public C(out int n)
{
n = 1;
}
public static void Main()
{
C c = new C(out var i) { i, i, i };
System.Console.WriteLine(c[0]);
}
}
";
CompileAndVerify(source, expectedOutput: @"1");
}
[Fact]
[WorkItem(49997, "https://github.com/dotnet/roslyn/issues/49997")]
public void Issue49997()
{
var text = @"
public class Cls
{
public static void Main()
{
if ()
.Test1().Test2(out var x1).Test3();
}
}
static class Ext
{
public static void Test3(this Cls x) {}
}
";
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test3").Last();
Assert.True(model.GetSymbolInfo(node).IsEmpty);
}
}
internal static class OutVarTestsExtensions
{
internal static SingleVariableDesignationSyntax VariableDesignation(this DeclarationExpressionSyntax self)
{
return (SingleVariableDesignationSyntax)self.Designation;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using static Roslyn.Test.Utilities.TestMetadata;
using ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[CompilerTrait(CompilerFeature.OutVar)]
public class OutVarTests : CompilingTestBase
{
[Fact]
public void OldVersion()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,29): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
[WorkItem(12182, "https://github.com/dotnet/roslyn/issues/12182")]
[WorkItem(16348, "https://github.com/dotnet/roslyn/issues/16348")]
public void DiagnosticsDifferenceBetweenLanguageVersions_01()
{
var text = @"
public class Cls
{
public static void Test1()
{
Test(out int x1);
}
public static void Test2()
{
var x = new Cls(out int x2);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,22): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// Test(out int x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 22),
// (11,33): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x2").WithArguments("out variable declaration", "7.0").WithLocation(11, 33),
// (6,9): error CS0103: The name 'Test' does not exist in the current context
// Test(out int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9),
// (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21),
// (11,29): error CS0165: Use of unassigned local variable 'x2'
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = GetOutVarDeclaration(tree, "x2");
//VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348
VerifyModelForOutVarWithoutDataFlow(model, x2Decl);
compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0103: The name 'Test' does not exist in the current context
// Test(out int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9),
// (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21),
// (11,29): error CS0165: Use of unassigned local variable 'x2'
// var x = new Cls(out int x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29)
);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
x2Decl = GetOutVarDeclaration(tree, "x2");
//VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348
VerifyModelForOutVarWithoutDataFlow(model, x2Decl);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var (x1, x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19),
// (6,24): error CS0103: The name 'x1' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24),
// (6,28): error CS0103: The name 'x2' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28),
// (6,19): error CS0103: The name 'var' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19),
// (7,34): error CS0103: The name 'x1' does not exist in the current context
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34),
// (8,34): error CS0103: The name 'x2' does not exist in the current context
// System.Console.WriteLine(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (var x1, var x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(6, 20),
// (6,28): error CS8185: A declaration is not allowed in this context.
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (var x1, var x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, var x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (int x1, long x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20),
// (6,28): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, long x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19),
// (6,20): error CS0165: Use of unassigned local variable 'x1'
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20),
// (6,28): error CS0165: Use of unassigned local variable 'x2'
// Test1(out (int x1, long x2));
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 28)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out (int x1, (long x2, byte x3)));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,20): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20),
// (6,29): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 29),
// (6,38): error CS8185: A declaration is not allowed in this context.
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "byte x3").WithLocation(6, 38),
// (6,28): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(long x2, byte x3)").WithArguments("System.ValueTuple`2").WithLocation(6, 28),
// (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, (long x2, byte x3))").WithArguments("System.ValueTuple`2").WithLocation(6, 19),
// (6,20): error CS0165: Use of unassigned local variable 'x1'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20),
// (6,29): error CS0165: Use of unassigned local variable 'x2'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 29),
// (6,38): error CS0165: Use of unassigned local variable 'x3'
// Test1(out (int x1, (long x2, byte x3)));
Diagnostic(ErrorCode.ERR_UseDefViolation, "byte x3").WithArguments("x3").WithLocation(6, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeclarationVarWithoutDataFlow(model, x3Decl, x3Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_05()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out var (x1, (x2, x3)));
System.Console.WriteLine(F1);
}
static ref int var(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (x2, x3)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2, x3))").WithLocation(11, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_06()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
Test1(out var (x1));
System.Console.WriteLine(F1);
}
static ref int var(object x)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1)").WithLocation(8, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_07()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (x1, x2: x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2: x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2: x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_08()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (ref x1, x2));
System.Console.WriteLine(F1);
}
static ref int var(ref object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (ref x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (ref x1, x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_09()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var (x1, (x2)));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (x2)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2))").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_10()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out var ((x1), x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var ((x1), x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var ((x1), x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_11()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var (x1, x2));
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
compilation.VerifyDiagnostics(
// (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19),
// (6,24): error CS0103: The name 'x1' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24),
// (6,28): error CS0103: The name 'x2' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28),
// (6,19): error CS0103: The name 'var' does not exist in the current context
// Test1(out var (x1, x2));
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19),
// (7,34): error CS0103: The name 'x1' does not exist in the current context
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34),
// (8,34): error CS0103: The name 'x2' does not exist in the current context
// System.Console.WriteLine(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_12()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(out M1 (x1, x2));
System.Console.WriteLine(F1);
}
static ref int M1(object x1, object x2)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_13()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(ref var (x1, x2));
System.Console.WriteLine(F1);
}
static ref int var(object x1, object x2)
{
return ref F1;
}
static object Test1(ref int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(ref var (x1, x2));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(9, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_14()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
Test1(var (x1, x2));
System.Console.WriteLine(F1);
}
static int var(object x1, object x2)
{
F1 = 123;
return 124;
}
static object Test1(int x)
{
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput:
@"124
123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_15()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out M1 (x1, (x2, x3)));
System.Console.WriteLine(F1);
}
static ref int M1(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "123");
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
[WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")]
public void OutVarDeconstruction_16()
{
var text = @"
public class Cls
{
private static int F1;
public static void Main()
{
object x1 = null;
object x2 = null;
object x3 = null;
Test1(out var (x1, (a: x2, b: x3)));
System.Console.WriteLine(F1);
}
static ref int var(object x, object y)
{
return ref F1;
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved.
// Test1(out var (x1, (a: x2, b: x3)));
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (a: x2, b: x3))").WithLocation(11, 19)
);
Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name)
{
return GetReferences(tree, name).Single();
}
private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count)
{
var nameRef = GetReferences(tree, name).ToArray();
Assert.Equal(count, nameRef.Length);
return nameRef;
}
internal static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name);
}
private static IEnumerable<DeclarationExpressionSyntax> GetDeclarations(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == name);
}
private static DeclarationExpressionSyntax GetDeclaration(SyntaxTree tree, string name)
{
return GetDeclarations(tree, name).Single();
}
internal static DeclarationExpressionSyntax GetOutVarDeclaration(SyntaxTree tree, string name)
{
return GetOutVarDeclarations(tree, name).Single();
}
private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.IsOutVarDeclaration() && p.Identifier().ValueText == name);
}
private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>();
}
private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken);
}
private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.IsOutVarDeclaration());
}
[Fact]
public void Simple_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1);
int x2;
Test3(out x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
static void Test3(out int y)
{
y = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVarWithoutDataFlow(model, decl, isShadowed: false, references: references);
}
private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isShadowed, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: isShadowed, verifyDataFlow: false, references: references);
}
private static void VerifyModelForDeclarationVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: false, expectedLocalKind: LocalDeclarationKind.DeclarationExpressionVariable, references: references);
}
internal static void VerifyModelForOutVar(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: references);
}
private static void VerifyModelForOutVarInNotExecutableCode(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: references);
}
private static void VerifyModelForOutVarInNotExecutableCode(
SemanticModel model,
DeclarationExpressionSyntax decl,
IdentifierNameSyntax reference)
{
VerifyModelForOutVar(
model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false,
verifyDataFlow: true, references: reference);
}
private static void VerifyModelForOutVar(
SemanticModel model,
DeclarationExpressionSyntax decl,
bool isDelegateCreation,
bool isExecutableCode,
bool isShadowed,
bool verifyDataFlow = true,
LocalDeclarationKind expectedLocalKind = LocalDeclarationKind.OutVariable,
params IdentifierNameSyntax[] references)
{
var variableDeclaratorSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDeclaratorSyntax);
Assert.NotNull(symbol);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(variableDeclaratorSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(expectedLocalKind, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
Assert.False(((ILocalSymbol)symbol).IsFixed);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax));
var other = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single();
if (isShadowed)
{
Assert.NotEqual(symbol, other);
}
else
{
Assert.Same(symbol, other);
}
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText));
var local = (ILocalSymbol)symbol;
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: local.Type);
foreach (var reference in references)
{
Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
}
if (verifyDataFlow)
{
VerifyDataFlow(model, decl, isDelegateCreation, isExecutableCode, references, symbol);
}
}
private static void AssertInfoForDeclarationExpressionSyntax(
SemanticModel model,
DeclarationExpressionSyntax decl,
ISymbol expectedSymbol = null,
ITypeSymbol expectedType = null
)
{
var symbolInfo = model.GetSymbolInfo(decl);
Assert.Equal(expectedSymbol, symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(symbolInfo, ((CSharpSemanticModel)model).GetSymbolInfo(decl));
var typeInfo = model.GetTypeInfo(decl);
Assert.Equal(expectedType, typeInfo.Type);
// skip cases where operation is not supported
AssertTypeFromOperation(model, expectedType, decl);
// Note: the following assertion is not, in general, correct for declaration expressions,
// even though this helper is used to handle declaration expressions.
// However, the tests that use this helper have been carefully crafted to avoid
// triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463
Assert.Equal(expectedType, typeInfo.ConvertedType);
Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(decl));
// Note: the following assertion is not, in general, correct for declaration expressions,
// even though this helper is used to handle declaration expressions.
// However, the tests that use this helper have been carefully crafted to avoid
// triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463
Assert.True(model.GetConversion(decl).IsIdentity);
var typeSyntax = decl.Type;
Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax));
Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax));
ITypeSymbol expected = expectedSymbol?.GetTypeOrReturnType();
if (expected?.IsErrorType() != false)
{
Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol);
}
else
{
Assert.Equal(expected, model.GetSymbolInfo(typeSyntax).Symbol);
}
typeInfo = model.GetTypeInfo(typeSyntax);
Assert.Equal(expected, typeInfo.Type);
Assert.Equal(expected, typeInfo.ConvertedType);
Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(typeSyntax));
Assert.True(model.GetConversion(typeSyntax).IsIdentity);
var conversion = model.ClassifyConversion(decl, model.Compilation.ObjectType, false);
Assert.False(conversion.Exists);
Assert.Equal(conversion, model.ClassifyConversion(decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false));
Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true));
Assert.Null(model.GetDeclaredSymbol(decl));
}
private static void AssertTypeFromOperation(SemanticModel model, ITypeSymbol expectedType, DeclarationExpressionSyntax decl)
{
// see https://github.com/dotnet/roslyn/issues/23006 and https://github.com/dotnet/roslyn/issues/23007 for more detail
// unlike GetSymbolInfo or GetTypeInfo, GetOperation doesn't use SemanticModel's recovery mode.
// what that means is that GetOperation might return null for ones GetSymbol/GetTypeInfo do return info from
// error recovery mode
var typeofExpression = decl.Ancestors().OfType<TypeOfExpressionSyntax>().FirstOrDefault();
if (typeofExpression?.Type?.FullSpan.Contains(decl.Span) == true)
{
// invalid syntax case where operation is not supported
return;
}
Assert.Equal(expectedType, model.GetOperation(decl)?.Type);
}
private static void VerifyDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, IdentifierNameSyntax[] references, ISymbol symbol)
{
var dataFlowParent = decl.Parent.Parent.Parent as ExpressionSyntax;
if (dataFlowParent == null)
{
if (isExecutableCode || !(decl.Parent.Parent.Parent is VariableDeclaratorSyntax))
{
Assert.IsAssignableFrom<ConstructorInitializerSyntax>(decl.Parent.Parent.Parent);
}
return;
}
if (model.IsSpeculativeSemanticModel)
{
Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent));
return;
}
var dataFlow = model.AnalyzeDataFlow(dataFlowParent);
if (isExecutableCode)
{
Assert.True(dataFlow.Succeeded);
Assert.True(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance));
if (!isDelegateCreation)
{
Assert.True(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.True(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance));
var flowsIn = FlowsIn(dataFlowParent, decl, references);
Assert.Equal(flowsIn,
dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(flowsIn,
dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(FlowsOut(dataFlowParent, decl, references),
dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(ReadOutside(dataFlowParent, references),
dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.Equal(WrittenOutside(dataFlowParent, references),
dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
}
}
}
private static void VerifyModelForOutVarDuplicateInSameScope(SemanticModel model, DeclarationExpressionSyntax decl)
{
var variableDesignationSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDesignationSyntax);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(LocalDeclarationKind.OutVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax));
Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single());
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText));
var local = (ILocalSymbol)symbol;
AssertInfoForDeclarationExpressionSyntax(model, decl, local, local.Type);
}
private static void VerifyNotInScope(SemanticModel model, IdentifierNameSyntax reference)
{
Assert.Null(model.GetSymbolInfo(reference).Symbol);
Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
Assert.False(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
private static void VerifyNotAnOutField(SemanticModel model, IdentifierNameSyntax reference)
{
var symbol = model.GetSymbolInfo(reference).Symbol;
Assert.NotEqual(SymbolKind.Field, symbol.Kind);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
internal static void VerifyNotAnOutLocal(SemanticModel model, IdentifierNameSyntax reference)
{
var symbol = model.GetSymbolInfo(reference).Symbol;
if (symbol.Kind == SymbolKind.Local)
{
var local = symbol.GetSymbol<SourceLocalSymbol>();
var parent = local.IdentifierToken.Parent;
Assert.Empty(parent.Ancestors().OfType<DeclarationExpressionSyntax>().Where(e => e.IsOutVarDeclaration()));
if (parent.Kind() == SyntaxKind.VariableDeclarator)
{
var parent1 = ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)parent).Parent).Parent;
switch (parent1.Kind())
{
case SyntaxKind.FixedStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.UsingStatement:
break;
default:
Assert.Equal(SyntaxKind.LocalDeclarationStatement, parent1.Kind());
break;
}
}
}
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
}
private static SingleVariableDesignationSyntax GetVariableDesignation(DeclarationExpressionSyntax decl)
{
return (SingleVariableDesignationSyntax)decl.Designation;
}
private static bool FlowsIn(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (dataFlowParent.Span.Contains(reference.Span) && reference.SpanStart > decl.SpanStart)
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool IsRead(IdentifierNameSyntax reference)
{
switch (reference.Parent.Kind())
{
case SyntaxKind.Argument:
if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword)
{
return true;
}
break;
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
if (((AssignmentExpressionSyntax)reference.Parent).Left != reference)
{
return true;
}
break;
default:
return true;
}
return false;
}
private static bool ReadOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span))
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool FlowsOut(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references)
{
ForStatementSyntax forStatement;
if ((forStatement = decl.Ancestors().OfType<ForStatementSyntax>().FirstOrDefault()) != null &&
forStatement.Incrementors.Span.Contains(decl.Position) &&
forStatement.Statement.DescendantNodes().OfType<ForStatementSyntax>().Any(f => f.Condition == null))
{
return false;
}
var containingStatement = decl.Ancestors().OfType<StatementSyntax>().FirstOrDefault();
var containingReturnOrThrow = containingStatement as ReturnStatementSyntax ?? (StatementSyntax)(containingStatement as ThrowStatementSyntax);
MethodDeclarationSyntax methodDeclParent;
if (containingReturnOrThrow != null && decl.Identifier().ValueText == "x1" &&
((methodDeclParent = containingReturnOrThrow.Parent.Parent as MethodDeclarationSyntax) == null ||
methodDeclParent.Body.Statements.First() != containingReturnOrThrow))
{
return false;
}
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span) &&
(containingReturnOrThrow == null || containingReturnOrThrow.Span.Contains(reference.SpanStart)) &&
(reference.SpanStart > decl.SpanStart ||
(containingReturnOrThrow == null &&
reference.Ancestors().OfType<DoStatementSyntax>().Join(
decl.Ancestors().OfType<DoStatementSyntax>(), d => d, d => d, (d1, d2) => true).Any())))
{
if (IsRead(reference))
{
return true;
}
}
}
return false;
}
private static bool WrittenOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
if (!dataFlowParent.Span.Contains(reference.Span))
{
if (IsWrite(reference))
{
return true;
}
}
}
return false;
}
private static bool IsWrite(IdentifierNameSyntax reference)
{
switch (reference.Parent.Kind())
{
case SyntaxKind.Argument:
if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.None)
{
return true;
}
break;
case SyntaxKind.SimpleAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
if (((AssignmentExpressionSyntax)reference.Parent).Left == reference)
{
return true;
}
break;
case SyntaxKind.PreIncrementExpression:
case SyntaxKind.PostIncrementExpression:
case SyntaxKind.PreDecrementExpression:
case SyntaxKind.PostDecrementExpression:
return true;
default:
return false;
}
return false;
}
[Fact]
public void Simple_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.Int32 x1), x1);
int x2 = 0;
Test3(x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
static void Test3(int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
[Fact]
public void Simple_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out (int, int) x1), x1);
}
static object Test1(out (int, int) x)
{
x = (123, 124);
return null;
}
static void Test2(object x, (int, int) y)
{
System.Console.WriteLine(y);
}
}
namespace System
{
// struct with two values
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
public override string ToString()
{
return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}';
}
}
}
" + TestResources.NetFX.ValueTuple.tupleattributes_cs;
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"{123, 124}").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.Collections.Generic.IEnumerable<System.Int32> x1), x1);
}
static object Test1(out System.Collections.Generic.IEnumerable<System.Int32> x)
{
x = new System.Collections.Generic.List<System.Int32>();
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"System.Collections.Generic.List`1[System.Int32]").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1, out x1), x1);
}
static object Test1(out int x, out int y)
{
x = 123;
y = 124;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1, x1 = 124), x1);
}
static object Test1(out int x, int y)
{
x = 123;
return null;
}
static void Test2(object x, int y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_07()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), x1, x1 = 124);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, int y, int z)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 2);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), ref x1);
int x2 = 0;
Test3(ref x2);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, ref int y)
{
System.Console.WriteLine(y);
}
static void Test3(ref int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Ref = GetReference(tree, "x2");
Assert.Null(model.GetDeclaredSymbol(x2Ref));
Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent));
}
[Fact]
public void Simple_09()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int x1), out x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, out int y)
{
y = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_10()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out dynamic x1), x1);
}
static object Test1(out dynamic x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
references: new MetadataReference[] { CSharpRef },
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Simple_11()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out int[] x1), x1);
}
static object Test1(out int[] x)
{
x = new [] {123};
return null;
}
static void Test2(object x, int[] y)
{
System.Console.WriteLine(y[0]);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_01()
{
var text = @"
public class Cls
{
public static void Main()
{
int x1 = 0;
Test1(out int x1);
Test2(Test1(out int x2),
out int x2);
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(object y, out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,23): error CS0128: A local variable named 'x1' is already defined in this scope
// Test1(out int x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 23),
// (9,29): error CS0128: A local variable named 'x2' is already defined in this scope
// out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(9, 29),
// (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used
// int x1 = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13)
);
}
[Fact]
public void Scope_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(x1,
Test1(out int x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(object y, object x)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,15): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 15)
);
}
[Fact]
public void Scope_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(out x1,
Test1(out int x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(out int y, object x)
{
y = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(out x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19)
);
}
[Fact]
public void Scope_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out int x1);
System.Console.WriteLine(x1);
}
static object Test1(out int x)
{
x = 1;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(out x1,
Test1(out var x1));
}
static object Test1(out int x)
{
x = 1;
return null;
}
static void Test2(out int y, object x)
{
y = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Test2(out x1,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19)
);
}
[Fact]
public void Scope_Attribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(p = TakeOutParam(out int x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out int x4))]
[Test(p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out int x6) && x6 > 0,
p2 = TakeOutParam(out int x6) && x6 > 0)]
[Test(p = TakeOutParam(out int x7) && x7 > 0)]
[Test(p = x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out int x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 15),
// (9,15): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15),
// (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40),
// (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithLocation(10, 15),
// (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37),
// (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p1 = TakeOutParam(out int x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 16),
// (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 16),
// (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out int x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 15),
// (16,15): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(TakeOutParam(out int x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out int x4))]
[Test(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(TakeOutParam(out int x6) && x6 > 0,
TakeOutParam(out int x6) && x6 > 0)]
[Test(TakeOutParam(out int x7) && x7 > 0)]
[Test(x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 11),
// (9,11): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11),
// (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36),
// (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithLocation(10, 11),
// (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32),
// (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 11),
// (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 11),
// (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out int x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 11),
// (16,11): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(p = TakeOutParam(out var x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out var x4))]
[Test(p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out var x6) && x6 > 0,
p2 = TakeOutParam(out var x6) && x6 > 0)]
[Test(p = TakeOutParam(out var x7) && x7 > 0)]
[Test(p = x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out var x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 15),
// (9,15): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15),
// (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40),
// (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithLocation(10, 15),
// (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37),
// (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p1 = TakeOutParam(out var x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 16),
// (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 16),
// (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(p = TakeOutParam(out var x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 15),
// (16,15): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_Attribute_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
[Test(TakeOutParam(out var x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out var x4))]
[Test(TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(TakeOutParam(out var x6) && x6 > 0,
TakeOutParam(out var x6) && x6 > 0)]
[Test(TakeOutParam(out var x7) && x7 > 0)]
[Test(x7 > 2)]
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x3) && x3 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 11),
// (9,11): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11),
// (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36),
// (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithLocation(10, 11),
// (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32),
// (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x6) && x6 > 0,
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 11),
// (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 11),
// (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [Test(TakeOutParam(out var x7) && x7 > 0)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 11),
// (16,11): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11),
// (17,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void AttributeArgument_01()
{
var source =
@"
public class X
{
[Test(out var x3)]
[Test(out int x4)]
[Test(p: out var x5)]
[Test(p: out int x6)]
public static void Main()
{
}
}
class Test : System.Attribute
{
public Test(out int p) { p = 100; }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
compilation.VerifyDiagnostics(
// (4,11): error CS1041: Identifier expected; 'out' is a keyword
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(4, 11),
// (4,19): error CS1003: Syntax error, ',' expected
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(4, 19),
// (5,11): error CS1041: Identifier expected; 'out' is a keyword
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(5, 11),
// (5,15): error CS1525: Invalid expression term 'int'
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(5, 15),
// (5,19): error CS1003: Syntax error, ',' expected
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x4").WithArguments(",", "").WithLocation(5, 19),
// (6,14): error CS1525: Invalid expression term 'out'
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 14),
// (6,14): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 14),
// (6,18): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "var").WithArguments(",", "").WithLocation(6, 18),
// (6,22): error CS1003: Syntax error, ',' expected
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x5").WithArguments(",", "").WithLocation(6, 22),
// (7,14): error CS1525: Invalid expression term 'out'
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(7, 14),
// (7,14): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(7, 14),
// (7,18): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(",", "int").WithLocation(7, 18),
// (7,18): error CS1525: Invalid expression term 'int'
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18),
// (7,22): error CS1003: Syntax error, ',' expected
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_SyntaxError, "x6").WithArguments(",", "").WithLocation(7, 22),
// (4,15): error CS0103: The name 'var' does not exist in the current context
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 15),
// (4,19): error CS0103: The name 'x3' does not exist in the current context
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(4, 19),
// (4,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments
// [Test(out var x3)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out var x3)").WithArguments("Test", "2").WithLocation(4, 6),
// (5,19): error CS0103: The name 'x4' does not exist in the current context
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(5, 19),
// (5,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments
// [Test(out int x4)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out int x4)").WithArguments("Test", "2").WithLocation(5, 6),
// (6,18): error CS0103: The name 'var' does not exist in the current context
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 18),
// (6,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "var").WithArguments("7.2").WithLocation(6, 18),
// (6,22): error CS0103: The name 'x5' does not exist in the current context
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(6, 22),
// (6,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments
// [Test(p: out var x5)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out var x5)").WithArguments("Test", "3").WithLocation(6, 6),
// (7,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "int").WithArguments("7.2").WithLocation(7, 18),
// (7,22): error CS0103: The name 'x6' does not exist in the current context
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(7, 22),
// (7,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments
// [Test(p: out int x6)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out int x6)").WithArguments("Test", "3").WithLocation(7, 6)
);
var tree = compilation.SyntaxTrees.Single();
Assert.False(GetOutVarDeclarations(tree, "x3").Any());
Assert.False(GetOutVarDeclarations(tree, "x4").Any());
Assert.False(GetOutVarDeclarations(tree, "x5").Any());
Assert.False(GetOutVarDeclarations(tree, "x6").Any());
}
[Fact]
public void Scope_Catch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
try {}
catch when (TakeOutParam(out var x1) && x1 > 0)
{
Dummy(x1);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out var x4) && x4 > 0)
{
Dummy(x4);
}
}
void Test6()
{
try {}
catch when (x6 && TakeOutParam(out var x6))
{
Dummy(x6);
}
}
void Test7()
{
try {}
catch when (TakeOutParam(out var x7) && x7 > 0)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
try {}
catch when (TakeOutParam(out var x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
}
void Test9()
{
try {}
catch when (TakeOutParam(out var x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
}
void Test10()
{
try {}
catch when (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// try {}
// catch when (TakeOutParam(y11, out var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test14()
{
try {}
catch when (Dummy(TakeOutParam(out var x14),
TakeOutParam(out var x14), // 2
x14))
{
Dummy(x14);
}
}
void Test15()
{
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out var x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42),
// (34,21): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21),
// (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17),
// (58,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34),
// (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46),
// (78,34): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34),
// (99,48): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48),
// (110,48): error CS0128: A local variable named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Scope_Catch_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
try {}
catch when (TakeOutParam(out int x1) && x1 > 0)
{
Dummy(x1);
}
}
void Test4()
{
int x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out int x4) && x4 > 0)
{
Dummy(x4);
}
}
void Test6()
{
try {}
catch when (x6 && TakeOutParam(out int x6))
{
Dummy(x6);
}
}
void Test7()
{
try {}
catch when (TakeOutParam(out int x7) && x7 > 0)
{
int x7 = 12;
Dummy(x7);
}
}
void Test8()
{
try {}
catch when (TakeOutParam(out int x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
}
void Test9()
{
try {}
catch when (TakeOutParam(out int x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out int x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
}
void Test10()
{
try {}
catch when (TakeOutParam(y10, out int x10))
{
int y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// try {}
// catch when (TakeOutParam(y11, out int x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test14()
{
try {}
catch when (Dummy(TakeOutParam(out int x14),
TakeOutParam(out int x14), // 2
x14))
{
Dummy(x14);
}
}
void Test15()
{
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out int x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out int x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42),
// (34,21): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out int x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21),
// (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17),
// (58,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34),
// (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out int x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46),
// (78,34): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out int x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34),
// (99,48): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(out int x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48),
// (110,48): error CS0128: A local variable named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out int x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Catch_01()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Catch_01_ExplicitType()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out System.Exception x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
}
[Fact]
public void Catch_02()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
System.Console.WriteLine(x1.GetType());
};
System.Console.WriteLine(x1.GetType());
d();
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.InvalidOperationException");
}
[Fact]
public void Catch_03()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
e = new System.NullReferenceException();
System.Console.WriteLine(x1.GetType());
};
System.Console.WriteLine(x1.GetType());
d();
System.Console.WriteLine(e.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.InvalidOperationException
System.NullReferenceException");
}
[Fact]
public void Catch_04()
{
var source =
@"
public class X
{
public static void Main()
{
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Action d = () =>
{
e = new System.NullReferenceException();
};
System.Console.WriteLine(x1.GetType());
d();
System.Console.WriteLine(e.GetType());
}
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException
System.NullReferenceException");
}
[Fact]
public void Scope_ConstructorInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
X(byte x)
: this(TakeOutParam(3, out int x3) && x3 > 0)
{}
X(sbyte x)
: this(x4 && TakeOutParam(4, out int x4))
{}
X(short x)
: this(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
X(ushort x)
: this(TakeOutParam(6, out int x6) && x6 > 0,
TakeOutParam(6, out int x6) && x6 > 0) // 2
{}
X(int x)
: this(TakeOutParam(7, out int x7) && x7 > 0)
{}
X(uint x)
: this(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
X(params object[] x) {}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : this(x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,41): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41),
// (24,40): error CS0128: A local variable named 'x6' is already defined in this scope
// TakeOutParam(6, out int x6) && x6 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : this(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_ConstructorInitializers_02()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x)
: base(TakeOutParam(3, out int x3) && x3 > 0)
{}
X(sbyte x)
: base(x4 && TakeOutParam(4, out int x4))
{}
X(short x)
: base(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
X(ushort x)
: base(TakeOutParam(6, out int x6) && x6 > 0,
TakeOutParam(6, out int x6) && x6 > 0) // 2
{}
X(int x)
: base(TakeOutParam(7, out int x7) && x7 > 0)
{}
X(uint x)
: base(x7, 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
public class Y
{
public Y(params object[] x) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0841: Cannot use local variable 'x4' before it is declared
// : base(x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16),
// (18,41): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41),
// (24,40): error CS0128: A local variable named 'x6' is already defined in this scope
// TakeOutParam(6, out int x6) && x6 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40),
// (30,16): error CS0103: The name 'x7' does not exist in the current context
// : base(x7, 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16),
// (32,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_ConstructorInitializers_03()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(12);
}
}
class D
{
public D(int o) : this(TakeOutParam(o, out int x1) && x1 >= 5)
{
Console.WriteLine(x1);
}
public D(bool b) { Console.WriteLine(b); }
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"False
1
True
10
True
12
").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_04()
{
var source =
@"using System;
public class X
{
public static void Main()
{
new D(1);
new D(10);
new D(12);
}
}
class D : C
{
public D(int o) : base(TakeOutParam(o, out int x1) && x1 >= 5)
{
Console.WriteLine(x1);
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
class C
{
public C(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"False
1
True
10
True
12
").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_05()
{
var source =
@"using System;
class D
{
public D(int o) : this(SpeculateHere)
{
}
public D(bool b) { Console.WriteLine(b); }
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)");
var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, arguments);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model);
Assert.True(success);
Assert.NotNull(model);
tree = initializer.SyntaxTree;
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_ConstructorInitializers_06()
{
var source =
@"using System;
class D : C
{
public D(int o) : base(SpeculateHere)
{
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
class C
{
public C(bool b) { Console.WriteLine(b); }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)");
var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, arguments);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model);
Assert.True(success);
Assert.NotNull(model);
tree = initializer.SyntaxTree;
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var initializerOperation = model.GetOperation(initializer);
Assert.Null(initializerOperation.Parent.Parent.Parent);
VerifyOperationTree(compilation, initializerOperation.Parent.Parent, @"
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)')
Expression:
IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(TakeOutPar ... && x1 >= 5)')
Children(1):
IInvocationOperation ( C..ctor(System.Boolean b)) (OperationKind.Invocation, Type: System.Void) (Syntax: ':base(TakeO ... && x1 >= 5)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'TakeOutPara ... && x1 >= 5')
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... && x1 >= 5')
Left:
IInvocationOperation (System.Boolean D.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'o')
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'o')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x1 >= 5')
Left:
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
public void Scope_ConstructorInitializers_07()
{
var source =
@"
public class X : Y
{
public static void Main()
{
}
X(byte x3)
: base(TakeOutParam(3, out var x3))
{}
X(sbyte x)
: base(TakeOutParam(4, out var x4))
{
int x4 = 1;
System.Console.WriteLine(x4);
}
X(ushort x)
: base(TakeOutParam(51, out var x5))
=> Dummy(TakeOutParam(52, out var x5), x5);
X(short x)
: base(out int x6, x6)
{}
X(uint x)
: base(out var x7, x7)
{}
X(int x)
: base(TakeOutParam(out int x8, x8))
{}
X(ulong x)
: base(TakeOutParam(out var x9, x9))
{}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(out int x, int y)
{
x = 123;
return true;
}
}
public class Y
{
public Y(params object[] x) {}
public Y(out int x, int y) { x = y; }
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// : base(TakeOutParam(3, out var x3))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(9, 40),
// (15,13): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x4 = 1;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 13),
// (21,39): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// => Dummy(TakeOutParam(52, out var x5), x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 39),
// (24,28): error CS0165: Use of unassigned local variable 'x6'
// : base(out int x6, x6)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x6").WithArguments("x6").WithLocation(24, 28),
// (28,28): error CS8196: Reference to an implicitly-typed out variable 'x7' is not permitted in the same argument list.
// : base(out var x7, x7)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x7").WithArguments("x7").WithLocation(28, 28),
// (28,20): error CS1615: Argument 1 may not be passed with the 'out' keyword
// : base(out var x7, x7)
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x7").WithArguments("1", "out").WithLocation(28, 20),
// (32,41): error CS0165: Use of unassigned local variable 'x8'
// : base(TakeOutParam(out int x8, x8))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(32, 41),
// (36,41): error CS8196: Reference to an implicitly-typed out variable 'x9' is not permitted in the same argument list.
// : base(TakeOutParam(out var x9, x9))
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x9").WithArguments("x9").WithLocation(36, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").Single();
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVarWithoutDataFlow(model, x9Decl, x9Ref);
}
[Fact]
public void Scope_Do_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
do
{
Dummy(x1);
}
while (TakeOutParam(true, out var x1) && x1);
}
void Test2()
{
do
Dummy(x2);
while (TakeOutParam(true, out var x2) && x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
do
Dummy(x4);
while (TakeOutParam(true, out var x4) && x4);
}
void Test6()
{
do
Dummy(x6);
while (x6 && TakeOutParam(true, out var x6));
}
void Test7()
{
do
{
var x7 = 12;
Dummy(x7);
}
while (TakeOutParam(true, out var x7) && x7);
}
void Test8()
{
do
Dummy(x8);
while (TakeOutParam(true, out var x8) && x8);
System.Console.WriteLine(x8);
}
void Test9()
{
do
{
Dummy(x9);
do
Dummy(x9);
while (TakeOutParam(true, out var x9) && x9); // 2
}
while (TakeOutParam(true, out var x9) && x9);
}
void Test10()
{
do
{
var y10 = 12;
Dummy(y10);
}
while (TakeOutParam(y10, out var x10));
}
//void Test11()
//{
// do
// {
// let y11 = 12;
// Dummy(y11);
// }
// while (TakeOutParam(y11, out var x11));
//}
void Test12()
{
do
var y12 = 12;
while (TakeOutParam(y12, out var x12));
}
//void Test13()
//{
// do
// let y13 = 12;
// while (TakeOutParam(y13, out var x13));
//}
void Test14()
{
do
{
Dummy(x14);
}
while (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14));
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (97,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(97, 13),
// (14,19): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(14, 19),
// (22,19): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(22, 19),
// (33,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x4) && x4);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(33, 43),
// (32,19): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy(x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(32, 19),
// (40,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(40, 16),
// (39,19): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(39, 19),
// (47,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(47, 17),
// (56,19): error CS0841: Cannot use local variable 'x8' before it is declared
// Dummy(x8);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x8").WithArguments("x8").WithLocation(56, 19),
// (59,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(59, 34),
// (66,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(66, 19),
// (69,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x9) && x9); // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(69, 47),
// (68,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(68, 23),
// (81,29): error CS0103: The name 'y10' does not exist in the current context
// while (TakeOutParam(y10, out var x10));
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(81, 29),
// (98,29): error CS0103: The name 'y12' does not exist in the current context
// while (TakeOutParam(y12, out var x12));
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(98, 29),
// (97,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(97, 17),
// (115,46): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(115, 46),
// (112,19): error CS0841: Cannot use local variable 'x14' before it is declared
// Dummy(x14);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x14").WithArguments("x14").WithLocation(112, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[1]);
VerifyNotAnOutLocal(model, x7Ref[0]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1], x9Ref[2]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[1]);
VerifyNotAnOutLocal(model, y10Ref[0]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Do_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
do
{
}
while (TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Do_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (DoStatementSyntax)SyntaxFactory.ParseStatement(@"
do {} while (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Do_01()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
do
{
;
}
while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1));
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Do_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f;
do
{
f = false;
}
while (Dummy(f, TakeOutParam((f ? 1 : 2), out int x1), x1));
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Do_03()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
do
;
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1) && false);
if (f)
{
do
;
while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1) && false);
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Do_04()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
do
{
;
}
while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1, l, () => System.Console.WriteLine(x1)));
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
2
3
--
1
2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_ExpressionBodiedFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3(object o) => TakeOutParam(o, out int x3) && x3 > 0;
bool Test4(object o) => x4 && TakeOutParam(o, out int x4);
bool Test5(object o1, object o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0;
bool Test61 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test62 (object o) => TakeOutParam(o, out int x6) && x6 > 0;
bool Test71(object o) => TakeOutParam(o, out int x7) && x7 > 0;
void Test72() => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test11(object x11) => TakeOutParam(1, out int x11) &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,29): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4(object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 29),
// (13,67): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 67),
// (19,28): error CS0103: The name 'x7' does not exist in the current context
// void Test72() => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 28),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,56): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool Test11(object x11) => TakeOutParam(1, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 56)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForOutVar(model, x11Decl, x11Ref);
}
[Fact]
public void ExpressionBodiedFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1() => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void ExpressionBodiedFunctions_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1() => TakeOutParam(1, out var x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
[WorkItem(14214, "https://github.com/dotnet/roslyn/issues/14214")]
public void Scope_ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test3()
{
bool f (object o) => TakeOutParam(o, out int x3) && x3 > 0;
f(null);
}
void Test4()
{
bool f (object o) => x4 && TakeOutParam(o, out int x4);
f(null);
}
void Test5()
{
bool f (object o1, object o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0;
f(null, null);
}
void Test6()
{
bool f1 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool f2 (object o) => TakeOutParam(o, out int x6) && x6 > 0;
f1(null);
f2(null);
}
void Test7()
{
Dummy(x7, 1);
bool f (object o) => TakeOutParam(o, out int x7) && x7 > 0;
Dummy(x7, 2);
f(null);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
bool f (object o) => TakeOutParam(o, out int x11) &&
x11 > 0;
f(null);
}
void Test12()
{
bool f (object o) => TakeOutParam(o, out int x12) &&
x12 > 0;
var x12 = 11;
Dummy(x12);
f(null);
}
System.Action Test13()
{
return () =>
{
bool f (object o) => TakeOutParam(o, out int x13) && x13 > 0;
f(null);
};
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30),
// (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67),
// (39,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15),
// (43,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (18,30): error CS0841: Cannot use local variable 'x4' before it is declared
// bool f (object o) => x4 && TakeOutParam(o, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30),
// (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67),
// (39,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15),
// (43,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15),
// (51,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => TakeOutParam(o, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(51, 54),
// (58,54): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool f (object o) => TakeOutParam(o, out int x12) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(58, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
// Data flow for the following disabled due to https://github.com/dotnet/roslyn/issues/14214
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarWithoutDataFlow(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x11Decl, x11Ref[1]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
var x13Decl = GetOutVarDeclarations(tree, "x13").Single();
var x13Ref = GetReferences(tree, "x13").Single();
VerifyModelForOutVarWithoutDataFlow(model, x13Decl, x13Ref);
}
[Fact]
public void ExpressionBodiedLocalFunctions_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
bool f() => TakeOutParam(1, out int x1) && Dummy(x1);
return f();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void ExpressionBodiedLocalFunctions_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
bool f() => TakeOutParam(1, out var x1) && Dummy(x1);
return f();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void Scope_ExpressionBodiedProperties_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 => TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 => x4 && TakeOutParam(4, out int x4);
bool Test5 => TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 => TakeOutParam(6, out int x6) && x6 > 0; bool Test62 => TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 => TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 => Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool this[object x11] => TakeOutParam(1, out int x11) &&
x11 > 0;
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,19): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 => x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 19),
// (13,44): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 44),
// (19,26): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 => Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 26),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// bool this[object x11] => TakeOutParam(1, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").Single();
VerifyModelForOutVar(model, x11Decl, x11Ref);
}
[Fact]
public void ExpressionBodiedProperties_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
System.Console.WriteLine(new X()[0]);
}
static bool Test1 => TakeOutParam(2, out int x1) && Dummy(x1);
bool this[object x] => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
True
1
True");
}
[Fact]
public void ExpressionBodiedProperties_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
System.Console.WriteLine(new X()[0]);
}
static bool Test1 => TakeOutParam(2, out var x1) && Dummy(x1);
bool this[object x] => TakeOutParam(1, out var x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2
True
1
True");
}
[Fact]
public void Scope_ExpressionStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
Dummy(TakeOutParam(true, out var x1), x1);
{
Dummy(TakeOutParam(true, out var x1), x1);
}
Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
// Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46),
// (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42),
// (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope
// Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ExpressionStatement_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
bool test = true;
if (test)
Test2(Test1(out int x1), x1);
if (test)
{
Test2(Test1(out int x1), x1);
}
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_ExpressionStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ExpressionStatement_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Scope_FieldInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 = x4 && TakeOutParam(4, out int x4);
bool Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0;
bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9);
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27),
// (22,57): error CS0103: The name 'x8' does not exist in the current context
// bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(22, 57),
// (23,19): error CS0103: The name 'x9' does not exist in the current context
// bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(23, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReference(tree, "x8");
VerifyModelForOutVar(model, x8Decl);
VerifyNotInScope(model, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReference(tree, "x9");
VerifyNotInScope(model, x9Ref);
VerifyModelForOutVar(model, x9Decl);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Scope_FieldInitializers_02()
{
var source =
@"using static Test;
public enum X
{
Test3 = TakeOutParam(3, out int x3) ? x3 : 0,
Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0,
Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0 ? 1 : 0,
Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0,
Test72 = x7,
}
class Test
{
public static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,13): error CS0841: Cannot use local variable 'x4' before it is declared
// Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 13),
// (9,38): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 38),
// (8,13): error CS0133: The expression being assigned to 'X.Test5' must be constant
// Test5 = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0 ? 1 : 0").WithArguments("X.Test5").WithLocation(8, 13),
// (12,14): error CS0133: The expression being assigned to 'X.Test61' must be constant
// Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test61").WithLocation(12, 14),
// (12,70): error CS0133: The expression being assigned to 'X.Test62' must be constant
// Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test62").WithLocation(12, 70),
// (14,14): error CS0133: The expression being assigned to 'X.Test71' must be constant
// Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0").WithArguments("X.Test71").WithLocation(14, 14),
// (15,14): error CS0103: The name 'x7' does not exist in the current context
// Test72 = x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 14),
// (4,13): error CS0133: The expression being assigned to 'X.Test3' must be constant
// Test3 = TakeOutParam(3, out int x3) ? x3 : 0,
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) ? x3 : 0").WithArguments("X.Test3").WithLocation(4, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IFieldInitializerOperation (Field: X.Test3) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... 3) ? x3 : 0')
Locals: Local_1: System.Int32 x3
IConditionalOperation (OperationKind.Conditional, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... 3) ? x3 : 0')
Condition:
IInvocationOperation (System.Boolean Test.TakeOutParam(System.Object y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '3')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
WhenTrue:
ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
WhenFalse:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
");
}
[Fact]
public void Scope_FieldInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
const bool Test4 = x4 && TakeOutParam(4, out int x4);
const bool Test5 = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
const bool Test72 = x7 > 2;
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,24): error CS0133: The expression being assigned to 'X.Test3' must be constant
// const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("X.Test3").WithLocation(8, 24),
// (10,24): error CS0841: Cannot use local variable 'x4' before it is declared
// const bool Test4 = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 24),
// (13,49): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 49),
// (12,24): error CS0133: The expression being assigned to 'X.Test5' must be constant
// const bool Test5 = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithArguments("X.Test5").WithLocation(12, 24),
// (16,25): error CS0133: The expression being assigned to 'X.Test61' must be constant
// const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test61").WithLocation(16, 25),
// (16,73): error CS0133: The expression being assigned to 'X.Test62' must be constant
// const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test62").WithLocation(16, 73),
// (18,25): error CS0133: The expression being assigned to 'X.Test71' must be constant
// const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0;
Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("X.Test71").WithLocation(18, 25),
// (19,25): error CS0103: The name 'x7' does not exist in the current context
// const bool Test72 = x7 > 2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_FieldInitializers_04()
{
var source =
@"
class X : Y
{
public static void Main()
{
}
bool Test3 = TakeOutParam(out int x3, x3);
bool Test4 = TakeOutParam(out var x4, x4);
bool Test5 = TakeOutParam(out int x5, 5);
X()
: this(x5)
{
System.Console.WriteLine(x5);
}
X(object x)
: base(x5)
=> System.Console.WriteLine(x5);
static bool Test6 = TakeOutParam(out int x6, 6);
static X()
{
System.Console.WriteLine(x6);
}
static bool TakeOutParam(out int x, int y)
{
x = 123;
return true;
}
}
class Y
{
public Y(object y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,43): error CS0165: Use of unassigned local variable 'x3'
// bool Test3 = TakeOutParam(out int x3, x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(8, 43),
// (10,43): error CS8196: Reference to an implicitly-typed out variable 'x4' is not permitted in the same argument list.
// bool Test4 = TakeOutParam(out var x4, x4);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x4").WithArguments("x4").WithLocation(10, 43),
// (15,12): error CS0103: The name 'x5' does not exist in the current context
// : this(x5)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(15, 12),
// (17,34): error CS0103: The name 'x5' does not exist in the current context
// System.Console.WriteLine(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(17, 34),
// (21,12): error CS0103: The name 'x5' does not exist in the current context
// : base(x5)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(21, 12),
// (22,33): error CS0103: The name 'x5' does not exist in the current context
// => System.Console.WriteLine(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(22, 33),
// (27,34): error CS0103: The name 'x6' does not exist in the current context
// System.Console.WriteLine(x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(27, 34)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(4, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
VerifyNotInScope(model, x5Ref[3]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void FieldInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,45): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IFieldInitializerOperation (Field: System.Boolean X.Test1) (OperationKind.FieldInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)')
Locals: Local_1: System.Int32 x1
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
[WorkItem(10487, "https://github.com/dotnet/roslyn/issues/10487")]
public void FieldInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 = TakeOutParam(1, out int x1) && Dummy(() => x1);
static bool Dummy(System.Func<int> x)
{
System.Console.WriteLine(x());
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void FieldInitializers_04()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static System.Func<bool> Test1 = () => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void FieldInitializers_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
static bool a = false;
bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0;
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,54): error CS0165: Use of unassigned local variable 'x1'
// bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void FieldInitializers_06()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static int Test1 = TakeOutParam(1, out var x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void Scope_Fixed_01()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
}
void Test6()
{
fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1 = Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p = Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p = Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p = Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p = Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63),
// (68,44): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p = Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44),
// (86,44): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p = Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,55): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Fixed_02()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* x1 =
Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2),
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p = Dummy(TakeOutParam(true, out var x3) && x3))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* p1 = Dummy(TakeOutParam(true, out var x4) && x4),
p2 = Dummy(TakeOutParam(true, out var x4) && x4))
{
Dummy(x4);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,59): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59),
// (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32),
// (14,66): error CS0165: Use of unassigned local variable 'x1'
// Dummy(TakeOutParam(true, out var x1) && x1))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 66),
// (23,21): error CS0128: A local variable named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,58): error CS0128: A local variable named 'x3' is already defined in this scope
// p = Dummy(TakeOutParam(true, out var x3) && x3))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58),
// (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// p = Dummy(TakeOutParam(true, out var x3) && x3))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31),
// (41,59): error CS0128: A local variable named 'x4' is already defined in this scope
// p2 = Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void Fixed_01()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
fixed (int* p = Dummy(TakeOutParam(""fixed"", out var x1), x1))
{
System.Console.WriteLine(x1);
}
}
static int[] Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new int[1];
}
static bool TakeOutParam(string y, out string x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput:
@"fixed
fixed");
}
[Fact]
public void Fixed_02()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
fixed (int* p = Dummy(TakeOutParam(""fixed"", out string x1), x1))
{
System.Console.WriteLine(x1);
}
}
static int[] Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new int[1];
}
static bool TakeOutParam(string y, out string x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput:
@"fixed
fixed");
}
[Fact]
public void Scope_For_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;
Dummy(TakeOutParam(true, out var x1) && x1)
;)
{
Dummy(x1);
}
}
void Test2()
{
for (;
Dummy(TakeOutParam(true, out var x2) && x2)
;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;
Dummy(TakeOutParam(true, out var x4) && x4)
;)
Dummy(x4);
}
void Test6()
{
for (;
Dummy(x6 && TakeOutParam(true, out var x6))
;)
Dummy(x6);
}
void Test7()
{
for (;
Dummy(TakeOutParam(true, out var x7) && x7)
;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;
Dummy(TakeOutParam(true, out var x8) && x8)
;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;
Dummy(TakeOutParam(true, out var x9) && x9)
;)
{
Dummy(x9);
for (;
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;)
Dummy(x9);
}
}
void Test10()
{
for (;
Dummy(TakeOutParam(y10, out var x10))
;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;
// Dummy(TakeOutParam(y11, out var x11))
// ;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;
Dummy(TakeOutParam(y12, out var x12))
;)
var y12 = 12;
}
//void Test13()
//{
// for (;
// Dummy(TakeOutParam(y13, out var x13))
// ;)
// let y13 = 12;
//}
void Test14()
{
for (;
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(TakeOutParam(true, out var x1) && x1)
)
{
Dummy(x1);
}
}
void Test2()
{
for (;;
Dummy(TakeOutParam(true, out var x2) && x2)
)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (;;
Dummy(TakeOutParam(true, out var x4) && x4)
)
Dummy(x4);
}
void Test6()
{
for (;;
Dummy(x6 && TakeOutParam(true, out var x6))
)
Dummy(x6);
}
void Test7()
{
for (;;
Dummy(TakeOutParam(true, out var x7) && x7)
)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (;;
Dummy(TakeOutParam(true, out var x8) && x8)
)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (;;
Dummy(TakeOutParam(true, out var x9) && x9)
)
{
Dummy(x9);
for (;;
Dummy(TakeOutParam(true, out var x9) && x9) // 2
)
Dummy(x9);
}
}
void Test10()
{
for (;;
Dummy(TakeOutParam(y10, out var x10))
)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (;;
// Dummy(TakeOutParam(y11, out var x11))
// )
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (;;
Dummy(TakeOutParam(y12, out var x12))
)
var y12 = 12;
}
//void Test13()
//{
// for (;;
// Dummy(TakeOutParam(y13, out var x13))
// )
// let y13 = 12;
//}
void Test14()
{
for (;;
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (16,19): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(16, 19),
// (25,19): error CS0103: The name 'x2' does not exist in the current context
// Dummy(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(25, 19),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (44,19): error CS0103: The name 'x6' does not exist in the current context
// Dummy(x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(44, 19),
// (63,19): error CS0103: The name 'x8' does not exist in the current context
// Dummy(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(63, 19),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (74,19): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(74, 19),
// (78,23): error CS0103: The name 'x9' does not exist in the current context
// Dummy(x9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(78, 23),
// (71,14): warning CS0162: Unreachable code detected
// Dummy(TakeOutParam(true, out var x9) && x9)
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(71, 14),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44),
// (128,19): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(128, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref[0]);
VerifyNotInScope(model, x2Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref[0]);
VerifyNotInScope(model, x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0]);
VerifyNotInScope(model, x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyNotInScope(model, x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]);
VerifyNotInScope(model, x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
VerifyNotInScope(model, x14Ref[1]);
}
[Fact]
public void Scope_For_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var b =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (var b =
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (var b =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (var b =
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (var b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (var b =
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (var b1 =
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (var b2 =
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (var b =
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (var b =
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (var b =
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (var b =
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (var b =
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool b =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool b =
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool b =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
}
void Test6()
{
for (bool b =
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
}
void Test7()
{
for (bool b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool b =
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool b1 =
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (bool b2 =
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
}
void Test10()
{
for (bool b =
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool b =
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool b =
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
}
//void Test13()
//{
// for (bool b =
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
//}
void Test14()
{
for (bool b =
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_For_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (var x1 =
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{}
}
void Test2()
{
for (var x2 = true;
Dummy(TakeOutParam(true, out var x2) && x2)
;)
{}
}
void Test3()
{
for (var x3 = true;;
Dummy(TakeOutParam(true, out var x3) && x3)
)
{}
}
void Test4()
{
for (bool x4 =
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
{}
}
void Test5()
{
for (bool x5 = true;
Dummy(TakeOutParam(true, out var x5) && x5)
;)
{}
}
void Test6()
{
for (bool x6 = true;;
Dummy(TakeOutParam(true, out var x6) && x6)
)
{}
}
void Test7()
{
for (bool x7 = true, b =
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{}
}
void Test8()
{
for (bool b1 = Dummy(TakeOutParam(true, out var x8) && x8),
b2 = Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2 = Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9))
{}
}
void Test10()
{
for (var b = x10;
Dummy(TakeOutParam(true, out var x10) && x10) &&
Dummy(TakeOutParam(true, out var x10) && x10);
Dummy(TakeOutParam(true, out var x10) && x10))
{}
}
void Test11()
{
for (bool b = x11;
Dummy(TakeOutParam(true, out var x11) && x11) &&
Dummy(TakeOutParam(true, out var x11) && x11);
Dummy(TakeOutParam(true, out var x11) && x11))
{}
}
void Test12()
{
for (Dummy(x12);
Dummy(x12) &&
Dummy(TakeOutParam(true, out var x12) && x12);
Dummy(TakeOutParam(true, out var x12) && x12))
{}
}
void Test13()
{
for (var b = x13;
Dummy(x13);
Dummy(TakeOutParam(true, out var x13) && x13),
Dummy(TakeOutParam(true, out var x13) && x13))
{}
}
void Test14()
{
for (bool b = x14;
Dummy(x14);
Dummy(TakeOutParam(true, out var x14) && x14),
Dummy(TakeOutParam(true, out var x14) && x14))
{}
}
void Test15()
{
for (Dummy(x15);
Dummy(x15);
Dummy(x15),
Dummy(TakeOutParam(true, out var x15) && x15))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,47): error CS0128: A local variable or function named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 47),
// (13,54): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(TakeOutParam(true, out var x1) && x1)
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 54),
// (21,47): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x2) && x2)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 47),
// (20,18): warning CS0219: The variable 'x2' is assigned but its value is never used
// for (var x2 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(20, 18),
// (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x3) && x3)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// (28,18): warning CS0219: The variable 'x3' is assigned but its value is never used
// for (var x3 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(28, 18),
// (37,47): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(37, 47),
// (37,54): error CS0165: Use of unassigned local variable 'x4'
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(37, 54),
// (45,47): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x5) && x5)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(45, 47),
// (44,19): warning CS0219: The variable 'x5' is assigned but its value is never used
// for (bool x5 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(44, 19),
// (53,47): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x6) && x6)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(53, 47),
// (52,19): warning CS0219: The variable 'x6' is assigned but its value is never used
// for (bool x6 = true;;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(52, 19),
// (61,47): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(TakeOutParam(true, out var x7) && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(61, 47),
// (69,52): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2 = Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(69, 52),
// (70,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(70, 47),
// (71,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(71, 47),
// (77,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(77, 23),
// (79,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(79, 47),
// (80,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(80, 47),
// (86,22): error CS0103: The name 'x10' does not exist in the current context
// for (var b = x10;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x10").WithArguments("x10").WithLocation(86, 22),
// (88,47): error CS0128: A local variable or function named 'x10' is already defined in this scope
// Dummy(TakeOutParam(true, out var x10) && x10);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x10").WithArguments("x10").WithLocation(88, 47),
// (89,47): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x10) && x10))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(89, 47),
// (95,23): error CS0103: The name 'x11' does not exist in the current context
// for (bool b = x11;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(95, 23),
// (97,47): error CS0128: A local variable or function named 'x11' is already defined in this scope
// Dummy(TakeOutParam(true, out var x11) && x11);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(97, 47),
// (98,47): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x11) && x11))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(98, 47),
// (104,20): error CS0103: The name 'x12' does not exist in the current context
// for (Dummy(x12);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(104, 20),
// (105,20): error CS0841: Cannot use local variable 'x12' before it is declared
// Dummy(x12) &&
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(105, 20),
// (107,47): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x12) && x12))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(107, 47),
// (113,22): error CS0103: The name 'x13' does not exist in the current context
// for (var b = x13;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(113, 22),
// (114,20): error CS0103: The name 'x13' does not exist in the current context
// Dummy(x13);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(114, 20),
// (116,47): error CS0128: A local variable or function named 'x13' is already defined in this scope
// Dummy(TakeOutParam(true, out var x13) && x13))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x13").WithArguments("x13").WithLocation(116, 47),
// (122,23): error CS0103: The name 'x14' does not exist in the current context
// for (bool b = x14;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(122, 23),
// (123,20): error CS0103: The name 'x14' does not exist in the current context
// Dummy(x14);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(123, 20),
// (125,47): error CS0128: A local variable or function named 'x14' is already defined in this scope
// Dummy(TakeOutParam(true, out var x14) && x14))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(125, 47),
// (131,20): error CS0103: The name 'x15' does not exist in the current context
// for (Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(131, 20),
// (132,20): error CS0103: The name 'x15' does not exist in the current context
// Dummy(x15);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(132, 20),
// (133,20): error CS0841: Cannot use local variable 'x15' before it is declared
// Dummy(x15),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x15").WithArguments("x15").WithLocation(133, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x7Decl);
VerifyNotAnOutLocal(model, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]);
VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(3, x10Decl.Length);
Assert.Equal(4, x10Ref.Length);
VerifyNotInScope(model, x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[1], x10Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x10Decl[1]);
VerifyModelForOutVar(model, x10Decl[2], x10Ref[3]);
var x11Decl = GetOutVarDeclarations(tree, "x11").ToArray();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Decl.Length);
Assert.Equal(4, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl[0], x11Ref[1], x11Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x11Decl[1]);
VerifyModelForOutVar(model, x11Decl[2], x11Ref[3]);
var x12Decl = GetOutVarDeclarations(tree, "x12").ToArray();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Decl.Length);
Assert.Equal(4, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForOutVar(model, x12Decl[0], x12Ref[1], x12Ref[2]);
VerifyModelForOutVar(model, x12Decl[1], x12Ref[3]);
var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(4, x13Ref.Length);
VerifyNotInScope(model, x13Ref[0]);
VerifyNotInScope(model, x13Ref[1]);
VerifyModelForOutVar(model, x13Decl[0], x13Ref[2], x13Ref[3]);
VerifyModelForOutVarDuplicateInSameScope(model, x13Decl[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyNotInScope(model, x14Ref[0]);
VerifyNotInScope(model, x14Ref[1]);
VerifyModelForOutVar(model, x14Decl[0], x14Ref[2], x14Ref[3]);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(4, x15Ref.Length);
VerifyNotInScope(model, x15Ref[0]);
VerifyNotInScope(model, x15Ref[1]);
VerifyModelForOutVar(model, x15Decl, x15Ref[2], x15Ref[3]);
}
[Fact]
public void Scope_For_07()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (;;
Dummy(x1),
Dummy(TakeOutParam(true, out var x1) && x1))
{}
}
void Test2()
{
for (;;
Dummy(TakeOutParam(true, out var x2) && x2),
Dummy(TakeOutParam(true, out var x2) && x2))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,20): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(x1),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 20),
// (22,47): error CS0128: A local variable or function named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2) && x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
}
[Fact]
public void For_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void For_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
f = false, Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void For_03()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1); x0++)
{
l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1));
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 20
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(4, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_04()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++)
{
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 20
3 30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(4, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_05()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++)
{
l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1));
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
30
--
3 10
3 10
3 20
3 20
3 30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(1, x0Decl.Length);
Assert.Equal(5, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl[0], x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_06()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)))
{
x0++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"20
30
--
20
30
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void For_07()
{
var source =
@"
public class X
{
public static void Main()
{
var l = new System.Collections.Generic.List<System.Action>();
for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)), x0++)
{
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"10
20
--
10
20
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_Foreach_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Collections.IEnumerable Dummy(params object[] x) {return null;}
void Test1()
{
foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
}
void Test6()
{
foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// foreach (var i in Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// foreach (var i in Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
foreach (var i in Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
void Test15()
{
foreach (var x15 in
Dummy(TakeOutParam(1, out var x15), x15))
{
Dummy(x15);
}
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,60): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 60),
// (35,33): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 33),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,65): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 65),
// (68,46): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 46),
// (86,46): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 46),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,57): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 57),
// (108,22): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(108, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
[Fact]
public void Foreach_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
foreach (var i in Dummy(TakeOutParam(3, out var x1), x1))
{
System.Console.WriteLine(x1);
}
}
static System.Collections.IEnumerable Dummy(object y, object z)
{
System.Console.WriteLine(z);
return ""a"";
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"3
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_If_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (TakeOutParam(true, out var x1))
{
Dummy(x1);
}
else
{
System.Console.WriteLine(x1);
}
}
void Test2()
{
if (TakeOutParam(true, out var x2))
Dummy(x2);
else
System.Console.WriteLine(x2);
}
void Test3()
{
if (TakeOutParam(true, out var x3))
Dummy(x3);
else
{
var x3 = 12;
System.Console.WriteLine(x3);
}
}
void Test4()
{
var x4 = 11;
Dummy(x4);
if (TakeOutParam(true, out var x4))
Dummy(x4);
}
void Test5(int x5)
{
if (TakeOutParam(true, out var x5))
Dummy(x5);
}
void Test6()
{
if (x6 && TakeOutParam(true, out var x6))
Dummy(x6);
}
void Test7()
{
if (TakeOutParam(true, out var x7) && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
if (TakeOutParam(true, out var x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
if (TakeOutParam(true, out var x9))
{
Dummy(x9);
if (TakeOutParam(true, out var x9)) // 2
Dummy(x9);
}
}
void Test10()
{
if (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
void Test12()
{
if (TakeOutParam(y12, out var x12))
var y12 = 12;
}
//void Test13()
//{
// if (TakeOutParam(y13, out var x13))
// let y13 = 12;
//}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (101,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(101, 13),
// (36,17): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x3 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(36, 17),
// (46,40): error CS0128: A local variable named 'x4' is already defined in this scope
// if (TakeOutParam(true, out var x4))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(46, 40),
// (52,40): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (TakeOutParam(true, out var x5))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(52, 40),
// (58,13): error CS0841: Cannot use local variable 'x6' before it is declared
// if (x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(58, 13),
// (66,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(66, 17),
// (83,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(83, 19),
// (84,44): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// if (TakeOutParam(true, out var x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(84, 44),
// (91,26): error CS0103: The name 'y10' does not exist in the current context
// if (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(91, 26),
// (100,26): error CS0103: The name 'y12' does not exist in the current context
// if (TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(100, 26),
// (101,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(101, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
}
[Fact]
public void Scope_If_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
if (TakeOutParam(true, out var x1))
{
}
else
{
}
x1++;
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_If_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (IfStatementSyntax)SyntaxFactory.ParseStatement(@"
if (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void If_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
Test(2);
}
public static void Test(int val)
{
if (Dummy(val == 1, TakeOutParam(val, out var x1), x1))
{
System.Console.WriteLine(""true"");
System.Console.WriteLine(x1);
}
else
{
System.Console.WriteLine(""false"");
System.Console.WriteLine(x1);
}
System.Console.WriteLine(x1);
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
true
1
1
2
false
2
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void If_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
if (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
;
if (f)
{
if (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_Lambda_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
System.Action<object> Test1()
{
return (o) => let x1 = o;
}
System.Action<object> Test2()
{
return (o) => let var x2 = o;
}
void Test3()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x3) && x3 > 0));
}
void Test4()
{
Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
}
void Test5()
{
Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out int x5) &&
TakeOutParam(o2, out int x5) &&
x5 > 0));
}
void Test6()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0));
}
void Test7()
{
Dummy(x7, 1);
Dummy(x7,
(System.Func<object, bool>) (o => TakeOutParam(o, out int x7) && x7 > 0),
x7);
Dummy(x7, 2);
}
void Test8()
{
Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out int y8) && x8));
}
void Test9()
{
Dummy(TakeOutParam(true, out var x9),
(System.Func<object, bool>) (o => TakeOutParam(o, out int x9) &&
x9 > 0), x9);
}
void Test10()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) &&
x10 > 0),
TakeOutParam(true, out var x10), x10);
}
void Test11()
{
var x11 = 11;
Dummy(x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) &&
x11 > 0), x11);
}
void Test12()
{
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) &&
x12 > 0),
x12);
var x12 = 11;
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,89): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (12,27): error CS1002: ; expected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27),
// (17,27): error CS1002: ; expected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27),
// (12,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23),
// (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23),
// (12,27): error CS0103: The name 'x1' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27),
// (12,32): error CS0103: The name 'o' does not exist in the current context
// return (o) => let x1 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32),
// (12,27): warning CS0162: Unreachable code detected
// return (o) => let x1 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27),
// (17,23): error CS0103: The name 'let' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23),
// (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23),
// (17,36): error CS0103: The name 'o' does not exist in the current context
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36),
// (17,27): warning CS0162: Unreachable code detected
// return (o) => let var x2 = o;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27),
// (27,49): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49),
// (33,89): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(o2, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89),
// (44,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15),
// (45,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15),
// (47,15): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15),
// (48,15): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15),
// (59,73): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(59, 73),
// (65,73): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(65, 73),
// (74,73): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(74, 73),
// (80,73): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) &&
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(80, 73),
// (82,15): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
[Fact]
public void Lambda_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static bool Test1()
{
System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1);
return l();
}
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Scope_LocalDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d = Dummy(TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var d = Dummy(TakeOutParam(true, out var x4), x4);
}
void Test6()
{
var d = Dummy(x6 && TakeOutParam(true, out var x6));
}
void Test8()
{
var d = Dummy(TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,50): error CS0128: A local variable named 'x4' is already defined in this scope
// var d = Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// var d = Dummy(x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_LocalDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
object d = Dummy(TakeOutParam(true, out var x4), x4);
}
void Test6()
{
object d = Dummy(x6 && TakeOutParam(true, out var x6));
}
void Test8()
{
object d = Dummy(TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
object d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,53): error CS0128: A local variable named 'x4' is already defined in this scope
// object d = Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 53),
// (24,26): error CS0841: Cannot use local variable 'x6' before it is declared
// object d = Dummy(x6 && TakeOutParam(true, out var x6));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 26),
// (36,50): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 50)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_LocalDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var x1 =
Dummy(TakeOutParam(true, out var x1), x1);
Dummy(x1);
}
void Test2()
{
object x2 =
Dummy(TakeOutParam(true, out var x2), x2);
Dummy(x2);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (13,56): error CS0841: Cannot use local variable 'x1' before it is declared
// Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
}
[Fact]
public void Scope_LocalDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d = Dummy(TakeOutParam(true, out var x1), x1),
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1 = Dummy(TakeOutParam(true, out var x2), x2),
d2 = Dummy(TakeOutParam(true, out var x2), x2);
}
void Test3()
{
object d1 = Dummy(TakeOutParam(true, out var x3), x3),
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 = Dummy(TakeOutParam(true, out var x4), x4);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_LocalDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y1 = Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Int64 y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
public void Scope_LocalDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d =TakeOutParam(true, out var x1) && x1 != null;
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d =TakeOutParam(true, out var x1) && x1 != null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d =TakeOutParam(true, out var x1) && x1 != null;").WithLocation(11, 13),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var d = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
public void LocalDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2);
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x1);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
a
c
b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void LocalDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
if (true)
{
object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1);
}
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (d, dd) = (TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
var (d, dd) = (TakeOutParam(true, out var x4), x4);
}
void Test6()
{
var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1);
}
void Test8()
{
var (d, dd) = (TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
var (d, dd, ddd) = (TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,51): error CS0128: A local variable named 'x4' is already defined in this scope
// var (d, dd) = (TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 51),
// (24,24): error CS0841: Cannot use local variable 'x6' before it is declared
// var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 24),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object dd) = (TakeOutParam(true, out var x1), x1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
(object d, object dd) = (TakeOutParam(true, out var x4), x4);
}
void Test6()
{
(object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1);
}
void Test8()
{
(object d, object dd) = (TakeOutParam(true, out var x8), x8);
System.Console.WriteLine(x8);
}
void Test14()
{
(object d, object dd, object ddd) = (TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,61): error CS0128: A local variable named 'x4' is already defined in this scope
// (object d, object dd) = (TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 61),
// (24,34): error CS0841: Cannot use local variable 'x6' before it is declared
// (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 34),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var (x1, dd) =
(TakeOutParam(true, out var x1), x1);
Dummy(x1);
}
void Test2()
{
(object x2, object dd) =
(TakeOutParam(true, out var x2), x2);
Dummy(x2);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// (TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (13,56): error CS0841: Cannot use local variable 'x1' before it is declared
// (TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// (TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// (TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
(object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Dummy(x1));
Dummy(x1);
}
void Test2()
{
(object d1, object d2) = (Dummy(TakeOutParam(true, out var x2), x2),
Dummy(TakeOutParam(true, out var x2), x2));
}
void Test3()
{
(object d1, object d2) = (Dummy(TakeOutParam(true, out var x3), x3),
Dummy(x3));
}
void Test4()
{
(object d1, object d2) = (Dummy(x4),
Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,67): error CS0128: A local variable named 'x1' is already defined in this scope
// (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 67),
// (12,72): error CS0165: Use of unassigned local variable 'x1'
// (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1),
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(12, 72),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,41): error CS0841: Cannot use local variable 'x4' before it is declared
// (object d1, object d2) = (Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyNotAnOutLocal(model, x1Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@"
var (y1, dd) = (TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
Assert.Equal("System.Boolean y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_DeconstructionDeclarationStmt_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var (d, dd) = (TakeOutParam(true, out var x1), x1);
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var d = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(id => id.Identifier.ValueText == "d").Single();
Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_01()
{
var source =
@"
public class X
{
public static void Main()
{
(object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x1);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
a
c
b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_02()
{
var source =
@"
public class X
{
public static void Main()
{
if (true)
{
(object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), x1);
}
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_03()
{
var source =
@"
public class X
{
public static void Main()
{
var (d1, (d2, d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
(Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2),
Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3)));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(d3);
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
f
a
c
e
b
d
f");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Decl.Length);
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl[0], x3Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void DeconstructionDeclarationStmt_04()
{
var source =
@"
public class X
{
public static void Main()
{
(var d1, (var d2, var d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1),
(Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2),
Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3)));
System.Console.WriteLine(d1);
System.Console.WriteLine(d2);
System.Console.WriteLine(d3);
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
System.Console.WriteLine(x3);
}
static object Dummy(object x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"b
d
f
a
c
e
b
d
f");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Decl.Length);
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl[0], x3Ref);
}
[Fact]
public void Scope_Lock_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
lock (Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
}
void Test2()
{
lock (Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0))
Dummy(x4);
}
void Test6()
{
lock (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
lock (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
lock (Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
lock (Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
}
void Test10()
{
lock (Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// lock (Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
lock (Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
}
//void Test13()
//{
// lock (Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
//}
void Test14()
{
lock (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,48): error CS0128: A local variable named 'x4' is already defined in this scope
// lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(29, 48),
// (35,21): error CS0841: Cannot use local variable 'x6' before it is declared
// lock (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 21),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (60,19): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(60, 19),
// (61,52): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 52),
// (68,34): error CS0103: The name 'y10' does not exist in the current context
// lock (Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 34),
// (86,34): error CS0103: The name 'y12' does not exist in the current context
// lock (Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 34),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,45): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 45)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Lock_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
if (true)
lock (Dummy(TakeOutParam(true, out var x1)))
{
}
x1++;
}
static object TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (17,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Lock_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LockStatementSyntax)SyntaxFactory.ParseStatement(@"
lock (Dummy(TakeOutParam(true, out var x1), x1)) ;
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Lock_01()
{
var source =
@"
public class X
{
public static void Main()
{
lock (Dummy(TakeOutParam(""lock"", out var x1), x1))
{
System.Console.WriteLine(x1);
}
System.Console.WriteLine(x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"lock
lock
lock");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Lock_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
lock (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{}
if (f)
{
lock (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
{}
}
}
static object Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Scope_ParameterDefault_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0)
{}
void Test4(bool p = x4 && TakeOutParam(4, out int x4))
{}
void Test5(bool p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)
{}
void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
{}
void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0)
{
}
void Test72(bool p = x7 > 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("p").WithLocation(8, 25),
// (11,25): error CS0841: Cannot use local variable 'x4' before it is declared
// void Test4(bool p = x4 && TakeOutParam(4, out int x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25),
// (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50),
// (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test5(bool p = TakeOutParam(51, out int x5) &&
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0").WithArguments("p").WithLocation(14, 25),
// (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27),
// (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76),
// (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("p").WithLocation(22, 26),
// (26,26): error CS0103: The name 'x7' does not exist in the current context
// void Test72(bool p = x7 > 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26),
// (29,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IParameterInitializerOperation (Parameter: [System.Boolean p = default(System.Boolean)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... ) && x3 > 0')
Locals: Local_1: System.Int32 x3
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... ) && x3 > 0')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'x3 > 0')
Left:
ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0')
");
}
[Fact]
public void Scope_ParameterDefault_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0)
{}
void Test4(bool p = x4 && TakeOutParam(4, out var x4))
{}
void Test5(bool p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)
{}
void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
{}
void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0)
{
}
void Test72(bool p = x7 > 2)
{}
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out var x3) && x3 > 0").WithArguments("p").WithLocation(8, 25),
// (11,25): error CS0841: Cannot use local variable 'x4' before it is declared
// void Test4(bool p = x4 && TakeOutParam(4, out var x4))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25),
// (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50),
// (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test5(bool p = TakeOutParam(51, out var x5) &&
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0").WithArguments("p").WithLocation(14, 25),
// (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27),
// (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant
// void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76),
// (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant
// void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0)
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out var x7) && x7 > 0").WithArguments("p").WithLocation(22, 26),
// (26,26): error CS0103: The name 'x7' does not exist in the current context
// void Test72(bool p = x7 > 2)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26),
// (29,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_PropertyInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 {get;} = TakeOutParam(3, out int x3) && x3 > 0;
bool Test4 {get;} = x4 && TakeOutParam(4, out int x4);
bool Test5 {get;} = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0;
bool Test61 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test62 {get;} = TakeOutParam(6, out int x6) && x6 > 0;
bool Test71 {get;} = TakeOutParam(7, out int x7) && x7 > 0;
bool Test72 {get;} = Dummy(x7, 2);
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,25): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 {get;} = x4 && TakeOutParam(4, out int x4);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 25),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (19,32): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 {get;} = Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 32),
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void PropertyInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1);
}
static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 52)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IPropertyInitializerOperation (Property: System.Boolean X.Test1 { get; }) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)')
Locals: Local_1: System.Int32 x1
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)')
Left:
IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void PropertyInitializers_02()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static System.Func<bool> Test1 {get;} = () => TakeOutParam(1, out int x1) && Dummy(x1);
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
}
[Fact]
public void PropertyInitializers_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
static bool a = false;
bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0;
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,63): error CS0165: Use of unassigned local variable 'x1'
// bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 63)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void PropertyInitializers_04()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(new X().Test1);
}
int Test1 { get; } = TakeOutParam(1, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")]
public void Scope_Query_01()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1}
select x + y1;
Dummy(y1);
}
void Test2()
{
var res = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0}
from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2}
select x1 + x2 + y2 +
z2;
Dummy(z2);
}
void Test3()
{
var res = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0}
let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0
select new { x1, x2, y3,
z3};
Dummy(z3);
}
void Test4()
{
var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
void Test6()
{
var res = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0}
where x > y6 && TakeOutParam(1, out var z6) && z6 == 1
select x + y6 +
z6;
Dummy(z6);
}
void Test7()
{
var res = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0}
orderby x > y7 && TakeOutParam(1, out var z7) && z7 ==
u7,
x > y7 && TakeOutParam(1, out var u7) && u7 ==
z7
select x + y7 +
z7 + u7;
Dummy(z7);
Dummy(u7);
}
void Test8()
{
var res = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0}
select x > y8 && TakeOutParam(1, out var z8) && z8 == 1;
Dummy(z8);
}
void Test9()
{
var res = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0}
group x > y9 && TakeOutParam(1, out var z9) && z9 ==
u9
by
x > y9 && TakeOutParam(1, out var u9) && u9 ==
z9;
Dummy(z9);
Dummy(u9);
}
void Test10()
{
var res = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0}
from y10 in new[] { 1 }
select x1 + y10;
}
void Test11()
{
var res = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0}
let y11 = x1 + 1
select x1 + y11;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (25,26): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(25, 26),
// (27,15): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(27, 15),
// (35,32): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(35, 32),
// (37,15): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(37, 15),
// (45,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(45, 35),
// (47,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(47, 35),
// (49,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(49, 32),
// (49,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(49, 36),
// (52,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(52, 15),
// (53,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(53, 15),
// (61,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(61, 35),
// (63,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(63, 35),
// (66,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(66, 32),
// (66,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(66, 36),
// (69,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(69, 15),
// (70,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(70, 15),
// (78,26): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(78, 26),
// (80,15): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(80, 15),
// (87,27): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(87, 27),
// (89,27): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(89, 27),
// (91,26): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(91, 26),
// (91,31): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(91, 31),
// (93,15): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(93, 15),
// (94,15): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(94, 15),
// (102,15): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(102, 15),
// (112,25): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(112, 25),
// (109,25): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(109, 25),
// (114,15): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(114, 15),
// (115,15): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(115, 15),
// (121,24): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10'
// from y10 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(121, 24),
// (128,23): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11'
// let y11 = x1 + 1
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(128, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutVar(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutVar(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutVar(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutVar(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutVar(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutVar(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutVar(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutVar(model, y10Decl, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutVar(model, y11Decl, y11Ref[0]);
VerifyNotAnOutLocal(model, y11Ref[1]);
}
[Fact]
public void Scope_Query_03()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
select x1 into x1
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
}
void Test5()
{
var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
select x1 into x1
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4 , out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,35): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(18, 35),
// (20,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(20, 35),
// (22,32): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(22, 32),
// (22,36): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(22, 36),
// (25,15): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(25, 15),
// (26,15): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(26, 15),
// (35,35): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(35, 35),
// (37,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(37, 35),
// (40,32): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(40, 32),
// (40,36): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(40, 36),
// (43,15): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(43, 15),
// (44,15): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(44, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_05()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
int y1 = 0, y2 = 0, y3 = 0, y4 = 0, y5 = 0, y6 = 0, y7 = 0, y8 = 0, y9 = 0, y10 = 0, y11 = 0, y12 = 0;
var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on TakeOutParam(4, out var y4) ? y4 : 0
equals TakeOutParam(5, out var y5) ? y5 : 0
where TakeOutParam(6, out var y6) && y6 == 1
orderby TakeOutParam(7, out var y7) && y7 > 0,
TakeOutParam(8, out var y8) && y8 > 0
group TakeOutParam(9, out var y9) && y9 > 0
by TakeOutParam(10, out var y10) && y10 > 0
into g
let x11 = TakeOutParam(11, out var y11) && y11 > 0
select TakeOutParam(12, out var y12) && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12 + (TakeOutParam(13, out var y13) ? y13 : 0);
Dummy(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62),
// (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62),
// (17,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(17, 62),
// (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62),
// (19,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(4, out var y4) ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(19, 51),
// (20,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(5, out var y5) ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(20, 58),
// (21,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(6, out var y6) && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(21, 49),
// (22,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(7, out var y7) && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(22, 51),
// (23,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(8, out var y8) && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(23, 51),
// (25,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(10, out var y10) && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(25, 47),
// (24,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(9, out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(24, 49),
// (27,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = TakeOutParam(11, out var y11) && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(27, 54),
// (28,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(12, out var y12) && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(28, 51)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(3, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForOutVarDuplicateInSameScope(model, yDecl);
VerifyNotAnOutLocal(model, yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl, yRef[0]);
break;
}
VerifyNotAnOutLocal(model, yRef[2]);
switch (i)
{
case 12:
VerifyNotAnOutLocal(model, yRef[1]);
break;
default:
VerifyNotAnOutLocal(model, yRef[1]);
break;
}
}
var y13Decl = GetOutVarDeclarations(tree, "y13").Single();
var y13Ref = GetReference(tree, "y13");
VerifyModelForOutVar(model, y13Decl, y13Ref);
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_06()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(TakeOutParam(out int y1),
TakeOutParam(out int y2),
TakeOutParam(out int y3),
TakeOutParam(out int y4),
TakeOutParam(out int y5),
TakeOutParam(out int y6),
TakeOutParam(out int y7),
TakeOutParam(out int y8),
TakeOutParam(out int y9),
TakeOutParam(out int y10),
TakeOutParam(out int y11),
TakeOutParam(out int y12),
from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on TakeOutParam(4, out var y4) ? y4 : 0
equals TakeOutParam(5, out var y5) ? y5 : 0
where TakeOutParam(6, out var y6) && y6 == 1
orderby TakeOutParam(7, out var y7) && y7 > 0,
TakeOutParam(8, out var y8) && y8 > 0
group TakeOutParam(9, out var y9) && y9 > 0
by TakeOutParam(10, out var y10) && y10 > 0
into g
let x11 = TakeOutParam(11, out var y11) && y11 > 0
select TakeOutParam(12, out var y12) && y12 > 0
into s
select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62),
// (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope
// from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62),
// (27,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(27, 62),
// (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62),
// (29,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(4, out var y4) ? y4 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(29, 51),
// (30,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(5, out var y5) ? y5 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(30, 58),
// (31,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(6, out var y6) && y6 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(31, 49),
// (32,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(7, out var y7) && y7 > 0,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(32, 51),
// (33,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(8, out var y8) && y8 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(33, 51),
// (35,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(10, out var y10) && y10 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(35, 47),
// (34,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(9, out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(34, 49),
// (37,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x11 = TakeOutParam(11, out var y11) && y11 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(37, 54),
// (38,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(12, out var y12) && y12 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(38, 51)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).ToArray();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
switch (i)
{
case 1:
case 3:
VerifyModelForOutVar(model, yDecl[0], yRef);
VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]);
break;
case 12:
VerifyModelForOutVar(model, yDecl[0], yRef[1]);
VerifyModelForOutVar(model, yDecl[1], yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl[0], yRef[1]);
VerifyModelForOutVar(model, yDecl[1], yRef[0]);
break;
}
}
}
[Fact]
public void Scope_Query_07()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
Dummy(TakeOutParam(out int y3),
from x1 in new[] { 0 }
select x1
into x1
join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
on x1 equals x3
select y3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,62): error CS0128: A local variable named 'y3' is already defined in this scope
// join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
const string id = "y3";
var yDecl = GetOutVarDeclarations(tree, id).ToArray();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(2, yDecl.Length);
Assert.Equal(2, yRef.Length);
// Since the name is declared twice in the same scope,
// both references are to the same declaration.
VerifyModelForOutVar(model, yDecl[0], yRef);
VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]);
}
[Fact]
public void Scope_Query_08()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new[] { Dummy(TakeOutParam(out var y1),
TakeOutParam(out var y2),
TakeOutParam(out var y3),
TakeOutParam(out var y4)
) ? 1 : 0}
from y1 in new[] { 1 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by x1
into y4
select y4;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// from y1 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(19, 24),
// (20,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(20, 24),
// (22,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(22, 23),
// (25,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(25, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 5; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
public void Scope_Query_09()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
join y2 in new[] { 0 }
on y1 equals y2
let y3 = 0
group y3
by 1
into y4
select y4 == null ? 1 : 0
into x2
join y5 in new[] { Dummy(TakeOutParam(out var y1),
TakeOutParam(out var y2),
TakeOutParam(out var y3),
TakeOutParam(out var y4),
TakeOutParam(out var y5)
) ? 1 : 0 }
on x2 equals y5
select x2;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1'
// var res = from y1 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(14, 24),
// (15,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2'
// join y2 in new[] { 0 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(15, 24),
// (17,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3'
// let y3 = 0
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(17, 23),
// (20,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4'
// into y4
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(20, 24),
// (23,24): error CS1931: The range variable 'y5' conflicts with a previous declaration of 'y5'
// join y5 in new[] { Dummy(TakeOutParam(out var y1),
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y5").WithArguments("y5").WithLocation(23, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 6; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
switch (i)
{
case 4:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
case 5:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
default:
VerifyModelForOutVar(model, yDecl);
VerifyNotAnOutLocal(model, yRef);
break;
}
}
}
[Fact]
[WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")]
[WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void Scope_Query_10()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from y1 in new[] { 0 }
from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 }
select y1;
}
void Test2()
{
var res = from y2 in new[] { 0 }
join x3 in new[] { 1 }
on TakeOutParam(out var y2) ? y2 : 0
equals x3
select y2;
}
void Test3()
{
var res = from x3 in new[] { 0 }
join y3 in new[] { 1 }
on x3
equals TakeOutParam(out var y3) ? y3 : 0
select y3;
}
void Test4()
{
var res = from y4 in new[] { 0 }
where TakeOutParam(out var y4) && y4 == 1
select y4;
}
void Test5()
{
var res = from y5 in new[] { 0 }
orderby TakeOutParam(out var y5) && y5 > 1,
1
select y5;
}
void Test6()
{
var res = from y6 in new[] { 0 }
orderby 1,
TakeOutParam(out var y6) && y6 > 1
select y6;
}
void Test7()
{
var res = from y7 in new[] { 0 }
group TakeOutParam(out var y7) && y7 == 3
by y7;
}
void Test8()
{
var res = from y8 in new[] { 0 }
group y8
by TakeOutParam(out var y8) && y8 == 3;
}
void Test9()
{
var res = from y9 in new[] { 0 }
let x4 = TakeOutParam(out var y9) && y9 > 0
select y9;
}
void Test10()
{
var res = from y10 in new[] { 0 }
select TakeOutParam(out var y10) && y10 > 0;
}
static bool TakeOutParam(out int x)
{
x = 0;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// error CS0412 is misleading and reported due to preexisting bug https://github.com/dotnet/roslyn/issues/12052
compilation.VerifyDiagnostics(
// (15,59): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(15, 59),
// (23,48): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// on TakeOutParam(out var y2) ? y2 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(23, 48),
// (33,52): error CS0136: A local or parameter named 'y3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// equals TakeOutParam(out var y3) ? y3 : 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y3").WithArguments("y3").WithLocation(33, 52),
// (40,46): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(out var y4) && y4 == 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(40, 46),
// (47,48): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// orderby TakeOutParam(out var y5) && y5 > 1,
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(47, 48),
// (56,48): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// TakeOutParam(out var y6) && y6 > 1
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(56, 48),
// (63,46): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// group TakeOutParam(out var y7) && y7 == 3
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(63, 46),
// (71,43): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// by TakeOutParam(out var y8) && y8 == 3;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(71, 43),
// (77,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// let x4 = TakeOutParam(out var y9) && y9 > 0
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(77, 49),
// (84,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select TakeOutParam(out var y10) && y10 > 0;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(84, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 11; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).ToArray();
Assert.Equal(i == 10 ? 1 : 2, yRef.Length);
switch (i)
{
case 4:
case 6:
VerifyModelForOutVar(model, yDecl, yRef[0]);
VerifyNotAnOutLocal(model, yRef[1]);
break;
case 8:
VerifyModelForOutVar(model, yDecl, yRef[1]);
VerifyNotAnOutLocal(model, yRef[0]);
break;
case 10:
VerifyModelForOutVar(model, yDecl, yRef[0]);
break;
default:
VerifyModelForOutVar(model, yDecl, yRef[0]);
VerifyNotAnOutLocal(model, yRef[1]);
break;
}
}
}
[Fact]
public void Scope_Query_11()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
var res = from x1 in new [] { 1 }
where Dummy(TakeOutParam(x1, out var y1),
from x2 in new [] { y1 }
where TakeOutParam(x1, out var y1)
select x2)
select x1;
}
void Test2()
{
var res = from x1 in new [] { 1 }
where Dummy(TakeOutParam(x1, out var y2),
TakeOutParam(x1 + 1, out var y2))
select x1;
}
void Test3()
{
var res = from x1 in new [] { 1 }
where TakeOutParam(out int y3, y3)
select x1;
}
void Test4()
{
var res = from x1 in new [] { 1 }
where TakeOutParam(out var y4, y4)
select x1;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool TakeOutParam(out int x, int y)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope
// TakeOutParam(x1 + 1, out var y2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60),
// (33,50): error CS0165: Use of unassigned local variable 'y3'
// where TakeOutParam(out int y3, y3)
Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50),
// (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list.
// where TakeOutParam(out var y4, y4)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50)
);
compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3);
compilation.VerifyDiagnostics(
// (17,62): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// where TakeOutParam(x1, out var y1)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(17, 62),
// (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope
// TakeOutParam(x1 + 1, out var y2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60),
// (33,50): error CS0165: Use of unassigned local variable 'y3'
// where TakeOutParam(out int y3, y3)
Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50),
// (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list.
// where TakeOutParam(out var y4, y4)
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").ToArray();
var y1Ref = GetReferences(tree, "y1").Single();
Assert.Equal(2, y1Decl.Length);
VerifyModelForOutVar(model, y1Decl[0], y1Ref);
VerifyModelForOutVar(model, y1Decl[1]);
var y2Decl = GetOutVarDeclarations(tree, "y2").ToArray();
Assert.Equal(2, y2Decl.Length);
VerifyModelForOutVar(model, y2Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, y2Decl[1]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").Single();
VerifyModelForOutVarWithoutDataFlow(model, y3Decl, y3Ref);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").Single();
VerifyModelForOutVarWithoutDataFlow(model, y4Decl, y4Ref);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")]
public void Query_01()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
Test1();
}
static void Test1()
{
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 1 : 0}
from x2 in new[] { TakeOutParam(2, out var y2) && Print(y2) ? 1 : 0}
join x3 in new[] { TakeOutParam(3, out var y3) && Print(y3) ? 1 : 0}
on TakeOutParam(4, out var y4) && Print(y4) ? 1 : 0
equals TakeOutParam(5, out var y5) && Print(y5) ? 1 : 0
where TakeOutParam(6, out var y6) && Print(y6)
orderby TakeOutParam(7, out var y7) && Print(y7),
TakeOutParam(8, out var y8) && Print(y8)
group TakeOutParam(9, out var y9) && Print(y9)
by TakeOutParam(10, out var y10) && Print(y10)
into g
let x11 = TakeOutParam(11, out var y11) && Print(y11)
select TakeOutParam(12, out var y12) && Print(y12);
res.ToArray();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput:
@"1
3
5
2
4
6
7
8
10
9
11
12
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i < 13; i++)
{
var id = "y" + i;
var yDecl = GetOutVarDeclarations(tree, id).Single();
var yRef = GetReferences(tree, id).Single();
VerifyModelForOutVar(model, yDecl, yRef);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(yDecl))).Type.ToTestDisplayString());
}
}
[Fact]
public void Query_02()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
Test1();
}
static void Test1()
{
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0}
select Print(x1);
res.ToArray();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetOutVarDeclarations(tree, "y1").Single();
var yRef = GetReferences(tree, "y1").Single();
VerifyModelForOutVar(model, yDecl, yRef);
}
[Fact]
public void Query_03()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
static void Test1()
{
var res = from a in new[] { true }
select a && TakeOutParam(3, out int x1) || x1 > 0;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,62): error CS0165: Use of unassigned local variable 'x1'
// select a && TakeOutParam(3, out int x1) || x1 > 0;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 62)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
compilation.VerifyOperationTree(x1Decl, expectedOperationTree:
@"
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
");
}
[Fact]
public void Query_04()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static int Test1()
{
var res = from a in new[] { 1 }
select TakeOutParam(a, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1;
return res.Single();
}
static int Test2(object a, ref int x)
{
System.Console.WriteLine(x);
x++;
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"2
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void Query_05()
{
var source =
@"
using System.Linq;
public class X
{
public static void Main()
{
}
static void Test1()
{
var res = from a in (new[] { 1 }).AsQueryable()
select TakeOutParam(a, out int x1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,46): error CS8198: An expression tree may not contain an out argument variable declaration.
// select TakeOutParam(a, out int x1);
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x1").WithLocation(13, 46)
);
}
[Fact]
public void Scope_ReturnStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null; }
object Test1()
{
return Dummy(TakeOutParam(true, out var x1), x1);
{
return Dummy(TakeOutParam(true, out var x1), x1);
}
return Dummy(TakeOutParam(true, out var x1), x1);
}
object Test2()
{
return Dummy(x2, TakeOutParam(true, out var x2));
}
object Test3(int x3)
{
return Dummy(TakeOutParam(true, out var x3), x3);
}
object Test4()
{
var x4 = 11;
Dummy(x4);
return Dummy(TakeOutParam(true, out var x4), x4);
}
object Test5()
{
return Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//object Test6()
//{
// let x6 = 11;
// Dummy(x6);
// return Dummy(TakeOutParam(true, out var x6), x6);
//}
//object Test7()
//{
// return Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
object Test8()
{
return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
object Test9(bool y9)
{
if (y9)
return Dummy(TakeOutParam(true, out var x9), x9);
return null;
}
System.Func<object> Test10(bool y10)
{
return () =>
{
if (y10)
return Dummy(TakeOutParam(true, out var x10), x10);
return null;};
}
object Test11()
{
Dummy(x11);
return Dummy(TakeOutParam(true, out var x11), x11);
}
object Test12()
{
return Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,53): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 53),
// (16,49): error CS0128: A local variable or function named 'x1' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 49),
// (14,13): warning CS0162: Unreachable code detected
// return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(14, 13),
// (21,22): error CS0841: Cannot use local variable 'x2' before it is declared
// return Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 22),
// (26,49): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// return Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 49),
// (33,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 49),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,86): error CS0128: A local variable or function named 'x8' is already defined in this scope
// return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 86),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ReturnStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
int Dummy(params object[] x) { return 0;}
int Test1(bool val)
{
if (val)
return Dummy(TakeOutParam(true, out var x1));
x1++;
return 0;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ReturnStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ReturnStatementSyntax)SyntaxFactory.ParseStatement(@"
return Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Return_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test();
}
static object Test()
{
return Dummy(TakeOutParam(""return"", out var x1), x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"return");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Return_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(true);
Test(false);
}
static object Test(bool val)
{
if (val)
return Dummy(TakeOutParam(""return 1"", out var x2), x2);
if (!val)
{
return Dummy(TakeOutParam(""return 2"", out var x2), x2);
}
return null;
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"return 1
return 2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]);
VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]);
}
[Fact]
public void Scope_Switch_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
switch (TakeOutParam(1, out var x1) ? x1 : 0)
{
case 0:
Dummy(x1, 0);
break;
}
Dummy(x1, 1);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
switch (TakeOutParam(4, out var x4) ? x4 : 0)
{
case 4:
Dummy(x4);
break;
}
}
void Test5(int x5)
{
switch (TakeOutParam(5, out var x5) ? x5 : 0)
{
case 5:
Dummy(x5);
break;
}
}
void Test6()
{
switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0))
{
case 6:
Dummy(x6);
break;
}
}
void Test7()
{
switch (TakeOutParam(7, out var x7) ? x7 : 0)
{
case 7:
var x7 = 12;
Dummy(x7);
break;
}
}
void Test9()
{
switch (TakeOutParam(9, out var x9) ? x9 : 0)
{
case 9:
Dummy(x9, 0);
switch (TakeOutParam(9, out var x9) ? x9 : 0)
{
case 9:
Dummy(x9, 1);
break;
}
break;
}
}
void Test10()
{
switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0))
{
case 10:
var y10 = 12;
Dummy(y10);
break;
}
}
//void Test11()
//{
// switch (y11 + (TakeOutParam(11, out var x11) ? x11 : 0))
// {
// case 11:
// let y11 = 12;
// Dummy(y11);
// break;
// }
//}
void Test14()
{
switch (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14) ? 1 : 0)
{
case 0:
Dummy(x14);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (27,41): error CS0128: A local variable named 'x4' is already defined in this scope
// switch (TakeOutParam(4, out var x4) ? x4 : 0)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(27, 41),
// (37,41): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (TakeOutParam(5, out var x5) ? x5 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(37, 41),
// (47,17): error CS0841: Cannot use local variable 'x6' before it is declared
// switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(47, 17),
// (60,21): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(60, 21),
// (71,23): error CS0841: Cannot use local variable 'x9' before it is declared
// Dummy(x9, 0);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(71, 23),
// (72,49): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// switch (TakeOutParam(9, out var x9) ? x9 : 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(72, 49),
// (85,17): error CS0103: The name 'y10' does not exist in the current context
// switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 17),
// (108,43): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(108, 43)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(3, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Switch_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
switch (TakeOutParam(1, out var x1) ? 1 : 0)
{
case 0:
break;
}
Dummy(x1, 1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,15): error CS0103: The name 'x1' does not exist in the current context
// Dummy(x1, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(19, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Switch_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@"
switch (Dummy(TakeOutParam(true, out var x1), x1)) {}
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Switch_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test1(0);
Test1(1);
}
static bool Dummy1(bool val, params object[] x) {return val;}
static T Dummy2<T>(T val, params object[] x) {return val;}
static void Test1(int val)
{
switch (Dummy2(val, TakeOutParam(""Test1 {0}"", out var x1)))
{
case 0 when Dummy1(true, TakeOutParam(""case 0"", out var y1)):
System.Console.WriteLine(x1, y1);
break;
case int z1:
System.Console.WriteLine(x1, z1);
break;
}
System.Console.WriteLine(x1);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"Test1 case 0
Test1 {0}
Test1 1
Test1 {0}");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Switch_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
switch (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{}
if (f)
{
switch (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
{}
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_SwitchLabelGuard_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test1(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
case 1 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
case 2 when Dummy(TakeOutParam(true, out var x1), x1):
Dummy(x1);
break;
}
}
void Test2(int val)
{
switch (val)
{
case 0 when Dummy(x2, TakeOutParam(true, out var x2)):
Dummy(x2);
break;
}
}
void Test3(int x3, int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x3), x3):
Dummy(x3);
break;
}
}
void Test4(int val)
{
var x4 = 11;
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x4), x4):
Dummy(x4);
break;
case 1 when Dummy(x4): Dummy(x4); break;
}
}
void Test5(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x5), x5):
Dummy(x5);
break;
}
var x5 = 11;
Dummy(x5);
}
//void Test6(int val)
//{
// let x6 = 11;
// switch (val)
// {
// case 0 when Dummy(x6):
// Dummy(x6);
// break;
// case 1 when Dummy(TakeOutParam(true, out var x6), x6):
// Dummy(x6);
// break;
// }
//}
//void Test7(int val)
//{
// switch (val)
// {
// case 0 when Dummy(TakeOutParam(true, out var x7), x7):
// Dummy(x7);
// break;
// }
// let x7 = 11;
// Dummy(x7);
//}
void Test8(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8):
Dummy(x8);
break;
}
}
void Test9(int val)
{
switch (val)
{
case 0 when Dummy(x9):
int x9 = 9;
Dummy(x9);
break;
case 2 when Dummy(x9 = 9):
Dummy(x9);
break;
case 1 when Dummy(TakeOutParam(true, out var x9), x9):
Dummy(x9);
break;
}
}
//void Test10(int val)
//{
// switch (val)
// {
// case 1 when Dummy(TakeOutParam(true, out var x10), x10):
// Dummy(x10);
// break;
// case 0 when Dummy(x10):
// let x10 = 10;
// Dummy(x10);
// break;
// case 2 when Dummy(x10 = 10, x10):
// Dummy(x10);
// break;
// }
//}
void Test11(int val)
{
switch (x11 ? val : 0)
{
case 0 when Dummy(x11):
Dummy(x11, 0);
break;
case 1 when Dummy(TakeOutParam(true, out var x11), x11):
Dummy(x11, 1);
break;
}
}
void Test12(int val)
{
switch (x12 ? val : 0)
{
case 0 when Dummy(TakeOutParam(true, out var x12), x12):
Dummy(x12, 0);
break;
case 1 when Dummy(x12):
Dummy(x12, 1);
break;
}
}
void Test13()
{
switch (TakeOutParam(1, out var x13) ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case 1 when Dummy(TakeOutParam(true, out var x13), x13):
Dummy(x13);
break;
}
}
void Test14(int val)
{
switch (val)
{
case 1 when Dummy(TakeOutParam(true, out var x14), x14):
Dummy(x14);
Dummy(TakeOutParam(true, out var x14), x14);
Dummy(x14);
break;
}
}
void Test15(int val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x15), x15):
case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Dummy(x15);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (30,31): error CS0841: Cannot use local variable 'x2' before it is declared
// case 0 when Dummy(x2, TakeOutParam(true, out var x2)):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31),
// (40,58): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x3), x3):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(40, 58),
// (51,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x4), x4):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(51, 58),
// (62,58): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 0 when Dummy(TakeOutParam(true, out var x5), x5):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(62, 58),
// (102,95): error CS0128: A local variable named 'x8' is already defined in this scope
// case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(102, 95),
// (112,31): error CS0841: Cannot use local variable 'x9' before it is declared
// case 0 when Dummy(x9):
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(112, 31),
// (119,58): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x9), x9):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(119, 58),
// (144,17): error CS0103: The name 'x11' does not exist in the current context
// switch (x11 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(144, 17),
// (146,31): error CS0103: The name 'x11' does not exist in the current context
// case 0 when Dummy(x11):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 31),
// (147,23): error CS0103: The name 'x11' does not exist in the current context
// Dummy(x11, 0);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(147, 23),
// (157,17): error CS0103: The name 'x12' does not exist in the current context
// switch (x12 ? val : 0)
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(157, 17),
// (162,31): error CS0103: The name 'x12' does not exist in the current context
// case 1 when Dummy(x12):
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(162, 31),
// (163,23): error CS0103: The name 'x12' does not exist in the current context
// Dummy(x12, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(163, 23),
// (175,58): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x13), x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(175, 58),
// (185,58): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case 1 when Dummy(TakeOutParam(true, out var x14), x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(185, 58),
// (198,58): error CS0128: A local variable named 'x15' is already defined in this scope
// case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(198, 58),
// (198,64): error CS0165: Use of unassigned local variable 'x15'
// case 1 when Dummy(TakeOutParam(true, out var x15), x15):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(198, 64)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(6, x1Ref.Length);
for (int i = 0; i < x1Decl.Length; i++)
{
VerifyModelForOutVar(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]);
}
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(4, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref[0], x4Ref[1]);
VerifyNotAnOutLocal(model, x4Ref[2]);
VerifyNotAnOutLocal(model, x4Ref[3]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref[0], x5Ref[1]);
VerifyNotAnOutLocal(model, x5Ref[2]);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(6, x9Ref.Length);
VerifyNotAnOutLocal(model, x9Ref[0]);
VerifyNotAnOutLocal(model, x9Ref[1]);
VerifyNotAnOutLocal(model, x9Ref[2]);
VerifyNotAnOutLocal(model, x9Ref[3]);
VerifyModelForOutVar(model, x9Decl, x9Ref[4], x9Ref[5]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(5, x11Ref.Length);
VerifyNotInScope(model, x11Ref[0]);
VerifyNotInScope(model, x11Ref[1]);
VerifyNotInScope(model, x11Ref[2]);
VerifyModelForOutVar(model, x11Decl, x11Ref[3], x11Ref[4]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(5, x12Ref.Length);
VerifyNotInScope(model, x12Ref[0]);
VerifyModelForOutVar(model, x12Decl, x12Ref[1], x12Ref[2]);
VerifyNotInScope(model, x12Ref[3]);
VerifyNotInScope(model, x12Ref[4]);
var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(2, x13Decl.Length);
Assert.Equal(5, x13Ref.Length);
VerifyModelForOutVar(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyModelForOutVar(model, x13Decl[1], x13Ref[3], x13Ref[4]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(4, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVar(model, x14Decl[1], isDelegateCreation: false, isExecutableCode: true, isShadowed: true);
var x15Decl = GetOutVarDeclarations(tree, "x15").ToArray();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Decl.Length);
Assert.Equal(3, x15Ref.Length);
for (int i = 0; i < x15Ref.Length; i++)
{
VerifyModelForOutVar(model, x15Decl[0], x15Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl[1]);
}
[Fact]
public void Scope_SwitchLabelGuard_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_03()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
while (TakeOutParam(x1, out var y1) && Print(y1)) break;
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return false;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_04()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
do
val = 0;
while (TakeOutParam(x1, out var y1) && Print(y1));
break;
}
}
static bool Print(int x)
{
System.Console.WriteLine(x);
return false;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_05()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
lock ((object)TakeOutParam(x1, out var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_06()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
if (TakeOutParam(x1, out var y1)) {}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_07()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
switch (TakeOutParam(x1, out var y1))
{
default: break;
}
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_08()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var x in Test(1)) {}
}
static System.Collections.IEnumerable Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
yield return TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_09()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var z1 = x1 > 0 & TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_10()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
a: TakeOutParam(x1, out var y1);
System.Console.WriteLine(y1);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (14,1): warning CS0164: This label has not been referenced
// a: TakeOutParam(x1, out var y1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(14, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_11()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static bool Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
return TakeOutParam(x1, out var y1) && Print(y1);
System.Console.WriteLine(y1);
break;
}
return false;
}
static bool Print<T>(T x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (15,17): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(15, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelGuard_12()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static bool Test(int val)
{
try
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
throw Dummy(TakeOutParam(x1, out var y1), y1);
System.Console.WriteLine(y1);
break;
}
}
catch
{}
return false;
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(
// (17,21): warning CS0162: Unreachable code detected
// System.Console.WriteLine(y1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(17, 21)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y1").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_13()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var (z0, z1) = (x1 > 0, TakeOutParam(x1, out var y1));
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void Scope_SwitchLabelGuard_14()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var (z0, (z1, z2)) = (x1 > 0, (TakeOutParam(x1, out var y1), true));
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"123
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString());
}
[Fact]
public void Scope_SwitchLabelPattern_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) { return true; }
void Test8(object val)
{
switch (val)
{
case int x8
when Dummy(x8, TakeOutParam(false, out var x8), x8):
Dummy(x8);
break;
}
}
void Test13()
{
switch (TakeOutParam(1, out var x13) ? x13 : 0)
{
case 0 when Dummy(x13):
Dummy(x13);
break;
case int x13 when Dummy(x13):
Dummy(x13);
break;
}
}
void Test14(object val)
{
switch (val)
{
case int x14 when Dummy(x14):
Dummy(x14);
Dummy(TakeOutParam(true, out var x14), x14);
Dummy(x14);
break;
}
}
void Test16(object val)
{
switch (val)
{
case int x16 when Dummy(x16):
case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Dummy(x16);
break;
}
}
void Test17(object val)
{
switch (val)
{
case 0 when Dummy(TakeOutParam(true, out var x17), x17):
case int x17 when Dummy(x17):
Dummy(x17);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,64): error CS0128: A local variable named 'x8' is already defined in this scope
// when Dummy(x8, TakeOutParam(false, out var x8), x8):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(15, 64),
// (28,22): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x13 when Dummy(x13):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(28, 22),
// (38,22): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// case int x14 when Dummy(x14):
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(38, 22),
// (51,58): error CS0128: A local variable named 'x16' is already defined in this scope
// case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x16").WithArguments("x16").WithLocation(51, 58),
// (51,64): error CS0165: Use of unassigned local variable 'x16'
// case 1 when Dummy(TakeOutParam(true, out var x16), x16):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x16").WithArguments("x16").WithLocation(51, 64),
// (62,22): error CS0128: A local variable named 'x17' is already defined in this scope
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x17").WithArguments("x17").WithLocation(62, 22),
// (62,37): error CS0165: Use of unassigned local variable 'x17'
// case int x17 when Dummy(x17):
Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(62, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
for (int i = 0; i < x8Ref.Length; i++)
{
VerifyNotAnOutLocal(model, x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl);
var x13Decl = GetOutVarDeclarations(tree, "x13").Single();
var x13Ref = GetReferences(tree, "x13").ToArray();
Assert.Equal(5, x13Ref.Length);
VerifyModelForOutVar(model, x13Decl, x13Ref[0], x13Ref[1], x13Ref[2]);
VerifyNotAnOutLocal(model, x13Ref[3]);
VerifyNotAnOutLocal(model, x13Ref[4]);
var x14Decl = GetOutVarDeclarations(tree, "x14").Single();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(4, x14Ref.Length);
VerifyNotAnOutLocal(model, x14Ref[0]);
VerifyNotAnOutLocal(model, x14Ref[1]);
VerifyNotAnOutLocal(model, x14Ref[2]);
VerifyNotAnOutLocal(model, x14Ref[3]);
VerifyModelForOutVar(model, x14Decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: true);
var x16Decl = GetOutVarDeclarations(tree, "x16").Single();
var x16Ref = GetReferences(tree, "x16").ToArray();
Assert.Equal(3, x16Ref.Length);
for (int i = 0; i < x16Ref.Length; i++)
{
VerifyNotAnOutLocal(model, x16Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x16Decl);
var x17Decl = GetOutVarDeclarations(tree, "x17").Single();
var x17Ref = GetReferences(tree, "x17").ToArray();
Assert.Equal(3, x17Ref.Length);
VerifyModelForOutVar(model, x17Decl, x17Ref);
}
[Fact]
public void Scope_ThrowStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1()
{
throw Dummy(TakeOutParam(true, out var x1), x1);
{
throw Dummy(TakeOutParam(true, out var x1), x1);
}
throw Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
throw Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
throw Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
throw Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
throw Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
// throw Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
// throw Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
throw Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
throw Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
throw Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
throw Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,52): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 52),
// (16,48): error CS0128: A local variable or function named 'x1' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 48),
// (21,21): error CS0841: Cannot use local variable 'x2' before it is declared
// throw Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 21),
// (26,48): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// throw Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 48),
// (33,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 48),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (39,9): warning CS0162: Unreachable code detected
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,85): error CS0128: A local variable or function named 'x8' is already defined in this scope
// throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 85),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (86,9): warning CS0162: Unreachable code detected
// Dummy(x12);
Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl[0], x8Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_ThrowStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.Exception Dummy(params object[] x) { return null;}
void Test1(bool val)
{
if (val)
throw Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_ThrowStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (ThrowStatementSyntax)SyntaxFactory.ParseStatement(@"
throw Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Throw_01()
{
var source =
@"
public class X
{
public static void Main()
{
Test();
}
static void Test()
{
try
{
throw Dummy(TakeOutParam(""throw"", out var x2), x2);
}
catch
{
}
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"throw");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Decl.Length);
Assert.Equal(1, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
}
[Fact]
public void Throw_02()
{
var source =
@"
public class X
{
public static void Main()
{
Test(true);
Test(false);
}
static void Test(bool val)
{
try
{
if (val)
throw Dummy(TakeOutParam(""throw 1"", out var x2), x2);
if (!val)
{
throw Dummy(TakeOutParam(""throw 2"", out var x2), x2);
}
}
catch
{
}
}
static System.Exception Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new System.ArgumentException();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"throw 1
throw 2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]);
VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]);
}
[Fact]
public void Scope_Using_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,49): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 49),
// (35,22): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 22),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,53): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 53),
// (68,35): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 35),
// (86,35): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 35),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,46): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (var d = Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d = Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (var d = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (var d = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d = Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d = Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d = Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d = Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d = Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (var d = Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (var d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d = Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61),
// (68,43): error CS0103: The name 'y10' does not exist in the current context
// using (var d = Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43),
// (86,43): error CS0103: The name 'y12' does not exist in the current context
// using (var d = Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,54): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
}
void Test6()
{
using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
}
void Test7()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
}
void Test10()
{
using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (System.IDisposable d = Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
}
//void Test13()
//{
// using (System.IDisposable d = Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
//}
void Test14()
{
using (System.IDisposable d = Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,72): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 72),
// (35,45): error CS0841: Cannot use local variable 'x6' before it is declared
// using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 45),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,76): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 76),
// (68,58): error CS0103: The name 'y10' does not exist in the current context
// using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 58),
// (86,58): error CS0103: The name 'y12' does not exist in the current context
// using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 58),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,69): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 69)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_Using_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
{
Dummy(x2);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,58): error CS0128: A local variable named 'x1' is already defined in this scope
// using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58),
// (12,63): error CS0841: Cannot use local variable 'x1' before it is declared
// using (var x1 = Dummy(TakeOutParam(true, out var x1), x1))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(12, 63),
// (20,73): error CS0128: A local variable named 'x2' is already defined in this scope
// using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73),
// (20,78): error CS0165: Use of unassigned local variable 'x2'
// using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 78)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
}
[Fact]
public void Scope_Using_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1),
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x2), x2),
d2 = Dummy(TakeOutParam(true, out var x2), x2))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x3), x3),
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2 = Dummy(TakeOutParam(true, out var x4), x4))
{
Dummy(x4);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,35): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,73): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
}
[Fact]
public void Using_01()
{
var source =
@"
public class X
{
public static void Main()
{
using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2)))
{
System.Console.WriteLine(d1);
System.Console.WriteLine(x1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x2);
}
using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1)))
{
System.Console.WriteLine(x1);
}
}
static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
class C : System.IDisposable
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public void Dispose()
{
System.Console.WriteLine(""Disposing {0}"", _val);
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"a
b
c
d
Disposing c
Disposing a
f
Disposing e");
}
[Fact]
public void Scope_While_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
while (TakeOutParam(true, out var x1) && x1)
{
Dummy(x1);
}
}
void Test2()
{
while (TakeOutParam(true, out var x2) && x2)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
while (TakeOutParam(true, out var x4) && x4)
Dummy(x4);
}
void Test6()
{
while (x6 && TakeOutParam(true, out var x6))
Dummy(x6);
}
void Test7()
{
while (TakeOutParam(true, out var x7) && x7)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
while (TakeOutParam(true, out var x8) && x8)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
while (TakeOutParam(true, out var x9) && x9)
{
Dummy(x9);
while (TakeOutParam(true, out var x9) && x9) // 2
Dummy(x9);
}
}
void Test10()
{
while (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// while (TakeOutParam(y11, out var x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
while (TakeOutParam(y12, out var x12))
var y12 = 12;
}
//void Test13()
//{
// while (TakeOutParam(y13, out var x13))
// let y13 = 12;
//}
void Test14()
{
while (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43),
// (35,16): error CS0841: Cannot use local variable 'x6' before it is declared
// while (x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 16),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 47),
// (68,29): error CS0103: The name 'y10' does not exist in the current context
// while (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 29),
// (86,29): error CS0103: The name 'y12' does not exist in the current context
// while (TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 29),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,46): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_While_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
if (true)
while (TakeOutParam(true, out var x1))
{
;
}
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (18,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_While_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (WhileStatementSyntax)SyntaxFactory.ParseStatement(@"
while (Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void While_01()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
{
System.Console.WriteLine(x1);
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
1
2
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_02()
{
var source =
@"
public class X
{
public static void Main()
{
bool f = true;
if (f)
while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1))
f = false;
f = true;
if (f)
{
while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1))
f = false;
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
4");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void While_03()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1))
{
l.Add(() => System.Console.WriteLine(x1));
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
2
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_04()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1)))
{
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
2
3
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void While_05()
{
var source =
@"
public class X
{
public static void Main()
{
int f = 1;
var l = new System.Collections.Generic.List<System.Action>();
while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1)))
{
l.Add(() => System.Console.WriteLine(x1));
f++;
}
System.Console.WriteLine(""--"");
foreach (var d in l)
{
d();
}
}
static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d)
{
l.Add(d);
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3
--
1
1
2
2
3
");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Scope_Yield_01()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) { return null;}
IEnumerable Test1()
{
yield return Dummy(TakeOutParam(true, out var x1), x1);
{
yield return Dummy(TakeOutParam(true, out var x1), x1);
}
yield return Dummy(TakeOutParam(true, out var x1), x1);
}
IEnumerable Test2()
{
yield return Dummy(x2, TakeOutParam(true, out var x2));
}
IEnumerable Test3(int x3)
{
yield return Dummy(TakeOutParam(true, out var x3), x3);
}
IEnumerable Test4()
{
var x4 = 11;
Dummy(x4);
yield return Dummy(TakeOutParam(true, out var x4), x4);
}
IEnumerable Test5()
{
yield return Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//IEnumerable Test6()
//{
// let x6 = 11;
// Dummy(x6);
// yield return Dummy(TakeOutParam(true, out var x6), x6);
//}
//IEnumerable Test7()
//{
// yield return Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
IEnumerable Test8()
{
yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
IEnumerable Test9(bool y9)
{
if (y9)
yield return Dummy(TakeOutParam(true, out var x9), x9);
}
IEnumerable Test11()
{
Dummy(x11);
yield return Dummy(TakeOutParam(true, out var x11), x11);
}
IEnumerable Test12()
{
yield return Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (16,59): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(16, 59),
// (18,55): error CS0128: A local variable or function named 'x1' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(18, 55),
// (23,28): error CS0841: Cannot use local variable 'x2' before it is declared
// yield return Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(23, 28),
// (28,55): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// yield return Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(28, 55),
// (35,55): error CS0128: A local variable or function named 'x4' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(35, 55),
// (41,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(41, 13),
// (41,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(41, 13),
// (61,92): error CS0128: A local variable or function named 'x8' is already defined in this scope
// yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(61, 92),
// (72,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(72, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_Yield_02()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
IEnumerable Test1()
{
if (true)
yield return TakeOutParam(true, out var x1);
x1++;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref);
}
[Fact]
public void Scope_Yield_03()
{
var source =
@"
using System.Collections;
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
IEnumerable Test1()
{
yield return 0;
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (YieldStatementSyntax)SyntaxFactory.ParseStatement(@"
yield return Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Yield_01()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var o in Test())
{}
}
static System.Collections.IEnumerable Test()
{
yield return Dummy(TakeOutParam(""yield1"", out var x1), x1);
yield return Dummy(TakeOutParam(""yield2"", out var x2), x2);
System.Console.WriteLine(x1);
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"yield1
yield2
yield1");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Yield_02()
{
var source =
@"
public class X
{
public static void Main()
{
foreach (var o in Test())
{}
}
static System.Collections.IEnumerable Test()
{
bool f = true;
if (f)
yield return Dummy(TakeOutParam(""yield1"", out var x1), x1);
if (f)
{
yield return Dummy(TakeOutParam(""yield2"", out var x1), x1);
}
}
static object Dummy(object y, object z)
{
System.Console.WriteLine(z);
return new object();
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"yield1
yield2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void Scope_LabeledStatement_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
a: Dummy(TakeOutParam(true, out var x1), x1);
{
b: Dummy(TakeOutParam(true, out var x1), x1);
}
c: Dummy(TakeOutParam(true, out var x1), x1);
}
void Test2()
{
a: Dummy(x2, TakeOutParam(true, out var x2));
}
void Test3(int x3)
{
a: Dummy(TakeOutParam(true, out var x3), x3);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
a: Dummy(TakeOutParam(true, out var x4), x4);
}
void Test5()
{
a: Dummy(TakeOutParam(true, out var x5), x5);
var x5 = 11;
Dummy(x5);
}
//void Test6()
//{
// let x6 = 11;
// Dummy(x6);
//a: Dummy(TakeOutParam(true, out var x6), x6);
//}
//void Test7()
//{
//a: Dummy(TakeOutParam(true, out var x7), x7);
// let x7 = 11;
// Dummy(x7);
//}
void Test8()
{
a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
}
void Test9(bool y9)
{
if (y9)
a: Dummy(TakeOutParam(true, out var x9), x9);
}
System.Action Test10(bool y10)
{
return () =>
{
if (y10)
a: Dummy(TakeOutParam(true, out var x10), x10);
};
}
void Test11()
{
Dummy(x11);
a: Dummy(TakeOutParam(true, out var x11), x11);
}
void Test12()
{
a: Dummy(TakeOutParam(true, out var x12), x12);
Dummy(x12);
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// b: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46),
// (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope
// c: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42),
// (12,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(12, 1),
// (14,1): warning CS0164: This label has not been referenced
// b: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(14, 1),
// (16,1): warning CS0164: This label has not been referenced
// c: Dummy(TakeOutParam(true, out var x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(16, 1),
// (21,15): error CS0841: Cannot use local variable 'x2' before it is declared
// a: Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15),
// (21,1): warning CS0164: This label has not been referenced
// a: Dummy(x2, TakeOutParam(true, out var x2));
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(21, 1),
// (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// a: Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42),
// (26,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x3), x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(26, 1),
// (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// a: Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42),
// (33,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x4), x4);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(33, 1),
// (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope
// var x5 = 11;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13),
// (38,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x5), x5);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(38, 1),
// (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used
// var x5 = 11;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13),
// (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope
// a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79),
// (59,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(59, 1),
// (65,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x9), x9);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x9), x9);").WithLocation(65, 1),
// (65,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x9), x9);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(65, 1),
// (73,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x10), x10);
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x10), x10);").WithLocation(73, 1),
// (73,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x10), x10);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(73, 1),
// (79,15): error CS0841: Cannot use local variable 'x11' before it is declared
// Dummy(x11);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15),
// (80,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x11), x11);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(80, 1),
// (85,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x12), x12);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(85, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl, x5Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Decl.Length);
Assert.Equal(2, x8Ref.Length);
for (int i = 0; i < x8Decl.Length; i++)
{
VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]);
}
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
var x9Decl = GetOutVarDeclarations(tree, "x9").Single();
var x9Ref = GetReferences(tree, "x9").Single();
VerifyModelForOutVar(model, x9Decl, x9Ref);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(2, x11Ref.Length);
VerifyModelForOutVar(model, x11Decl, x11Ref);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(2, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref);
}
[Fact]
public void Scope_LabeledStatement_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
if (true)
a: Dummy(TakeOutParam(true, out var x1));
x1++;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (13,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: Dummy(TakeOutParam(true, out var x1));
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x1));").WithLocation(13, 1),
// (15,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9),
// (13,1): warning CS0164: This label has not been referenced
// a: Dummy(TakeOutParam(true, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0]);
VerifyNotInScope(model, x1Ref[0]);
}
[Fact]
public void Scope_LabeledStatement_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LabeledStatementSyntax)SyntaxFactory.ParseStatement(@"
a: b: Dummy(TakeOutParam(true, out var x1), x1);
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
}
[Fact]
public void Labeled_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
a: b: c:Test2(Test1(out int x1), x1);
System.Console.Write(x1);
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics(
// (11,1): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(11, 1),
// (11,4): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(11, 4),
// (11,7): warning CS0164: This label has not been referenced
// a: b: c:Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(11, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void Labeled_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test0();
}
static object Test0()
{
bool test = true;
if (test)
{
a: Test2(Test1(out int x1), x1);
}
return null;
}
static object Test1(out int x)
{
x = 1;
return null;
}
static object Test2(object x, object y)
{
System.Console.Write(y);
return x;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics(
// (15,1): warning CS0164: This label has not been referenced
// a: Test2(Test1(out int x1), x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(15, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void DataFlow_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1,
x1);
}
static void Test(out int x, int y)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,22): error CS0165: Use of unassigned local variable 'x1'
// x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void DataFlow_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1,
ref x1);
}
static void Test(out int x, ref int y)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,22): error CS0165: Use of unassigned local variable 'x1'
// ref x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void DataFlow_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1);
var x2 = 1;
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,13): warning CS0219: The variable 'x2' is assigned but its value is never used
// var x2 = 1;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(7, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single();
var dataFlow = model.AnalyzeDataFlow(x2Decl);
Assert.True(dataFlow.Succeeded);
Assert.Equal("System.Int32 x2", dataFlow.VariablesDeclared.Single().ToTestDisplayString());
Assert.Equal("System.Int32 x1", dataFlow.WrittenOutside.Single().ToTestDisplayString());
}
[Fact]
public void TypeMismatch_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1);
}
static void Test(out short x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,18): error CS1503: Argument 1: cannot convert from 'out int' to 'out short'
// Test(out int x1);
Diagnostic(ErrorCode.ERR_BadArgType, "int x1").WithArguments("1", "out int", "out short").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[Fact]
public void Parse_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(int x1);
Test(ref int x2);
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,14): error CS1525: Invalid expression term 'int'
// Test(int x1);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 14),
// (6,18): error CS1003: Syntax error, ',' expected
// Test(int x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 18),
// (7,18): error CS1525: Invalid expression term 'int'
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18),
// (7,22): error CS1003: Syntax error, ',' expected
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_SyntaxError, "x2").WithArguments(",", "").WithLocation(7, 22),
// (6,18): error CS0103: The name 'x1' does not exist in the current context
// Test(int x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 18),
// (7,22): error CS0103: The name 'x2' does not exist in the current context
// Test(ref int x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(7, 22)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree).Any());
}
[Fact]
public void Parse_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out int x1.);
}
static void Test(out int x)
{
x = 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,24): error CS1003: Syntax error, ',' expected
// Test(out int x1.);
Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",", ".").WithLocation(6, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[Fact]
public void Parse_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test(out System.Collections.Generic.IEnumerable<System.Int32>);
}
static void Test(out System.Collections.Generic.IEnumerable<System.Int32> x)
{
x = null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,18): error CS0118: 'IEnumerable<int>' is a type but is used like a variable
// Test(out System.Collections.Generic.IEnumerable<System.Int32>);
Diagnostic(ErrorCode.ERR_BadSKknown, "System.Collections.Generic.IEnumerable<System.Int32>").WithArguments("System.Collections.Generic.IEnumerable<int>", "type", "variable").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree).Any());
}
[Fact]
public void GetAliasInfo_01()
{
var text = @"
using a = System.Int32;
public class Cls
{
public static void Main()
{
Test1(out a x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GetAliasInfo_02()
{
var text = @"
using var = System.Int32;
public class Cls
{
public static void Main()
{
Test1(out var x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void VarIsNotVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out var x)
{
x = new var() {val = 123};
return null;
}
static void Test2(object x, var y)
{
System.Console.WriteLine(y.val);
}
struct var
{
public int val;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void VarIsNotVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1);
}
struct var
{
public int val;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0103: The name 'Test1' does not exist in the current context
// Test1(out var x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 9),
// (11,20): warning CS0649: Field 'Cls.var.val' is never assigned to, and will always have its default value 0
// public int val;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "val").WithArguments("Cls.var.val", "0").WithLocation(11, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
Assert.Equal("Cls.var", ((ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void SimpleVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void SimpleVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static void Test2(object x, object y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,15): error CS0103: The name 'Test1' does not exist in the current context
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void SimpleVar_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1,
out x1);
}
static object Test1(out int x, out int x2)
{
x = 123;
x2 = 124;
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,23): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list.
// out x1);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1,
Test1(out x1,
3));
}
static object Test1(out int x, int x2)
{
x = 123;
x2 = 124;
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,25): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list.
// Test1(out x1,
Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(ref int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,25): error CS1620: Argument 1 must be passed with the 'ref' keyword
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadArgRef, "var x1").WithArguments("1", "ref").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(int x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,25): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_07()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic x = null;
Test2(x.Test1(out var x1),
x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,31): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(x.Test1(out var x1),
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 31)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new Test1(out var x1), x1);
}
class Test1
{
public Test1(out int x)
{
x = 123;
}
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void SimpleVar_09()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new System.Action(out var x1),
x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,37): error CS0149: Method name expected
// Test2(new System.Action(out var x1),
Diagnostic(ErrorCode.ERR_MethodNameExpected, "var x1").WithLocation(6, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, isDelegateCreation: true, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void ConstructorInitializers_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x, object y)
{
System.Console.WriteLine(y);
}
public Test2()
: this(Test1(out var x1), x1)
{}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (25,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// : this(Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(25, 26)
);
var initializer = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
var typeInfo = model.GetTypeInfo(initializer);
var symbolInfo = model.GetSymbolInfo(initializer);
var group = model.GetMemberGroup(initializer);
Assert.Equal("System.Void", typeInfo.Type.ToTestDisplayString());
Assert.Equal("Cls.Test2..ctor(System.Object x, System.Object y)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Empty(group); // https://github.com/dotnet/roslyn/issues/24936
}
[Fact]
public void ConstructorInitializers_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test3());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
public Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}
class Test3 : Test2
{
public Test3()
: base(Test1(out var x1), x1)
{}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (29,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// : base(Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(29, 26)
);
}
[Fact]
public void ConstructorInitializers_03()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
class Test2
{
Test2(out int x)
{
x = 2;
}
public Test2()
: this(out var x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
public void ConstructorInitializers_04()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test3());
}
static void Do(object x){}
class Test2
{
public Test2(out int x)
{
x = 1;
}
}
class Test3 : Test2
{
public Test3()
: base(out var x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void ConstructorInitializers_05()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(System.Func<object> x)
{
System.Console.WriteLine(x());
}
public Test2()
: this(() =>
{
Test1(out var x1);
return x1;
})
{}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_07()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_08()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object x)
{
}
public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (23,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2()
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2()
: this(Test1(out var x1))
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(23, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var analyzer = new ConstructorInitializers_08_SyntaxAnalyzer();
CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular)
.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.True(analyzer.ActionFired);
}
private class ConstructorInitializers_08_SyntaxAnalyzer : DiagnosticAnalyzer
{
public bool ActionFired { get; private set; }
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Handle, SyntaxKind.ThisConstructorInitializer);
}
private void Handle(SyntaxNodeAnalysisContext context)
{
ActionFired = true;
var tree = context.Node.SyntaxTree;
var model = context.SemanticModel;
var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node.Parent;
SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model);
Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(constructorDeclaration));
MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[constructorDeclaration];
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Initializer).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Body).IsDefaultOrEmpty);
Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.ExpressionBody).IsDefaultOrEmpty);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Decl));
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[0]));
Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[1]));
}
}
[Fact]
public void ConstructorInitializers_09()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_10()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (22,38): error CS0165: Use of unassigned local variable 'x1'
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_11()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (21,37): error CS0165: Use of unassigned local variable 'x1'
// => System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(21, 37)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_12()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2(bool a)
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a)
: this(a && Test1(out var x1), 1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(19, 9),
// (22,38): error CS0165: Use of unassigned local variable 'x1'
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_13()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_14()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_15()
{
var text = @"
public class Cls
{
public static void Main()
{
}
public static bool Test1(out int x)
{
throw null;
}
class Test2
{
Test2(bool x, int y)
{
}
public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (19,9): error CS8057: Block bodies and expression bodies cannot both be provided.
// public Test2(bool a)
Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a)
: this(a && Test1(out var x1), x1)
{
System.Console.WriteLine(x1);
}
=> System.Console.WriteLine(x1);").WithLocation(19, 9),
// (20,40): error CS0165: Use of unassigned local variable 'x1'
// : this(a && Test1(out var x1), x1)
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_16()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object a, object b, ref int x)
{
System.Console.WriteLine(x);
x++;
}
public Test2()
: this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1)
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ConstructorInitializers_17()
{
var text = @"
public class Cls
{
public static void Main()
{
Do(new Test2());
}
static void Do(object x){}
public static object Test1(out int x)
{
x = 123;
return null;
}
class Test2
{
Test2(object a, object b, ref int x)
{
System.Console.WriteLine(x);
x++;
}
public Test2()
: this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1)
=> System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void SimpleVar_14()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out dynamic x)
{
x = 123;
return null;
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
references: new MetadataReference[] { CSharpRef },
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
Assert.Equal("dynamic x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString());
}
[Fact]
public void SimpleVar_15()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(new Test1(out var var), var);
}
class Test1
{
public Test1(out int x)
{
x = 123;
}
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var varDecl = GetOutVarDeclaration(tree, "var");
var varRef = GetReferences(tree, "var").Skip(1).Single();
VerifyModelForOutVar(model, varDecl, varRef);
}
[Fact]
public void SimpleVar_16()
{
var text = @"
public class Cls
{
public static void Main()
{
if (Test1(out var x1))
{
System.Console.WriteLine(x1);
}
}
static bool Test1(out int x)
{
x = 123;
return true;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString());
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void VarAndBetterness_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1, null);
Test2(out var x2, null);
}
static object Test1(out int x, object y)
{
x = 123;
System.Console.WriteLine(x);
return null;
}
static object Test1(out short x, string y)
{
x = 124;
System.Console.WriteLine(x);
return null;
}
static object Test2(out int x, string y)
{
x = 125;
System.Console.WriteLine(x);
return null;
}
static object Test2(out short x, object y)
{
x = 126;
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"124
125").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
var x2Decl = GetOutVarDeclaration(tree, "x2");
VerifyModelForOutVar(model, x2Decl);
}
[Fact]
public void VarAndBetterness_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out var x1, null);
}
static object Test1(out int x, object y)
{
x = 123;
System.Console.WriteLine(x);
return null;
}
static object Test1(out short x, object y)
{
x = 124;
System.Console.WriteLine(x);
return null;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Cls.Test1(out int, object)' and 'Cls.Test1(out short, object)'
// Test1(out var x1, null);
Diagnostic(ErrorCode.ERR_AmbigCall, "Test1").WithArguments("Cls.Test1(out int, object)", "Cls.Test1(out short, object)").WithLocation(6, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVar(model, x1Decl);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_01()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_02()
{
var text = @"
public class Cls
{
public static void Main()
{
Test2(Test1(out System.ArgIterator x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void RestrictedTypes_03()
{
var text = @"
public class Cls
{
public static void Main() {}
async void Test()
{
Test2(Test1(out var x1), x1);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (11,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(11, 25),
// (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// Test2(Test1(out var x1), x1);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(8, 25),
// (6,16): 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 Test()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void RestrictedTypes_04()
{
var text = @"
public class Cls
{
public static void Main() {}
async void Test()
{
Test2(Test1(out System.ArgIterator x1), x1);
var x = default(System.ArgIterator);
}
static object Test1(out System.ArgIterator x)
{
x = default(System.ArgIterator);
return null;
}
static void Test2(object x, System.ArgIterator y)
{
}
}";
var compilation = CreateCompilation(text,
targetFramework: TargetFramework.Mscorlib45,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,25): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// static object Test1(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(12, 25),
// (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// Test2(Test1(out System.ArgIterator x1), x1);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 25),
// (9,9): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// var x = default(System.ArgIterator);
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(9, 9),
// (6,16): 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 Test()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void ElementAccess_01()
{
var text = @"
public class Cls
{
public static void Main()
{
var x = new [] {1};
Test2(x[out var x1]);
Test2(x1);
Test2(x[out var _]);
}
static void Test2(object x) { }
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var model = compilation.GetSemanticModel(tree);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out var x1]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(x[out var x1]);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25),
// (9,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out var _]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(9, 21),
// (9,21): error CS8183: Cannot infer the type of implicitly-typed discard.
// Test2(x[out var _]);
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(9, 21)
);
}
[Fact]
public void PointerAccess_01()
{
var text = @"
public class Cls
{
public static unsafe void Main()
{
int* p = (int*)0;
Test2(p[out var x1]);
Test2(x1);
}
static void Test2(object x) { }
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe.WithAllowUnsafe(true),
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var model = compilation.GetSemanticModel(tree);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(p[out var x1]);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// Test2(p[out var x1]);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25)
);
}
[Fact]
public void ElementAccess_02()
{
var text = @"
public class Cls
{
public static void Main()
{
var x = new [] {1};
Test2(x[out int x1], x1);
}
static void Test2(object x, object y)
{
System.Console.WriteLine(y);
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword
// Test2(x[out int x1], x1);
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int x1").WithArguments("1", "out").WithLocation(7, 21),
// (7,21): error CS0165: Use of unassigned local variable 'x1'
// Test2(x[out int x1], x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(7, 21)
);
}
[Fact]
[WorkItem(12058, "https://github.com/dotnet/roslyn/issues/12058")]
public void MissingArgumentAndNamedOutVarArgument()
{
var source =
@"class Program
{
public static void Main(string[] args)
{
if (M(s: out var s))
{
string s2 = s;
}
}
public static bool M(int i, out string s)
{
s = i.ToString();
return true;
}
}
";
var compilation = CreateCompilation(source,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (5,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Program.M(int, out string)'
// if (M(s: out var s))
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("i", "Program.M(int, out string)").WithLocation(5, 13)
);
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_01()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out var x);
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_02()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out int x) + x;
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_03()
{
var text = @"
public class Cls
{
public static void Main()
{
var y = Test1(out var x) + x;
System.Console.WriteLine(y);
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_04()
{
var text = @"
public class Cls
{
public static void Main()
{
for (var y = Test1(out var x) + x; y != 0 ; y = 0)
{
System.Console.WriteLine(y);
}
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")]
public void LocalVariableTypeInferenceAndOutVar_05()
{
var text = @"
public class Cls
{
public static void Main()
{
foreach (var y in new [] {Test1(out var x) + x})
{
System.Console.WriteLine(y);
}
}
static int Test1(out int x)
{
x = 123;
return 124;
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yRef = GetReferences(tree, "y").Last();
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")]
public void LocalVariableTypeInferenceAndOutVar_06()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(x: 1, out var y);
System.Console.WriteLine(y);
}
static void Test1(int x, ref int y)
{
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular7_1);
compilation.VerifyDiagnostics(
// (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// Test1(x: 1, out var y);
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "out var y").WithArguments("7.2").WithLocation(6, 21),
// (6,25): error CS1620: Argument 2 must be passed with the 'ref' keyword
// Test1(x: 1, out var y);
Diagnostic(ErrorCode.ERR_BadArgRef, "var y").WithArguments("2", "ref").WithLocation(6, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetDeclaration(tree, "y");
VerifyModelForOutVar(model, yDecl, GetReferences(tree, "y").ToArray());
}
[Fact]
[WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")]
public void LocalVariableTypeInferenceAndOutVar_07()
{
var text = @"
public class Cls
{
public static void Main()
{
int x = 0;
Test1(y: ref x, y: out var y);
System.Console.WriteLine(y);
}
static void Test1(int x, ref int y)
{
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Cls.Test1(int, ref int)'
// Test1(y: ref x, y: out var y);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Test1").WithArguments("x", "Cls.Test1(int, ref int)").WithLocation(7, 9));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetDeclaration(tree, "y");
var yRef = GetReferences(tree, "y").ToArray();
Assert.Equal(3, yRef.Length);
Assert.Equal("System.Console.WriteLine(y)", yRef[2].Parent.Parent.Parent.ToString());
VerifyModelForOutVar(model, yDecl, yRef[2]);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamic()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int z];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()",
@"{
// Code size 87 (0x57)
.maxstack 7
.locals init (object V_0, //d
int V_1) //z
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0007: brtrue.s IL_003e
IL_0009: ldc.i4.0
IL_000a: ldtoken ""Cls""
IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0014: ldc.i4.2
IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001a: dup
IL_001b: ldc.i4.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0023: stelem.ref
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: ldc.i4.s 17
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target""
IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_004d: ldloc.0
IL_004e: ldloca.s V_1
IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)""
IL_0055: pop
IL_0056: ret
}");
}
[Fact]
public void IndexingDynamicWithDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int _];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()",
@"
{
// Code size 87 (0x57)
.maxstack 7
.locals init (object V_0, //d
int V_1)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0007: brtrue.s IL_003e
IL_0009: ldc.i4.0
IL_000a: ldtoken ""Cls""
IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0014: ldc.i4.2
IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_001a: dup
IL_001b: ldc.i4.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0023: stelem.ref
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: ldc.i4.s 17
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target""
IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0""
IL_004d: ldloc.0
IL_004e: ldloca.s V_1
IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)""
IL_0055: pop
IL_0056: ret
}
");
}
[Fact]
public void IndexingDynamicWithVarDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out var _];
}
}";
// the C# dynamic binder does not support ref or out indexers, so we don't run this
var comp = CreateCompilation(text, options: TestOptions.DebugDll, references: new[] { CSharpRef });
comp.VerifyDiagnostics(
// (7,23): error CS8183: Cannot infer the type of implicitly-typed discard.
// var x = d[out var _];
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 23)
);
}
[Fact]
public void IndexingDynamicWithShortDiscard()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out _];
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,23): error CS8183: Cannot infer the type of implicitly-typed discard.
// var x = d[out _];
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 23)
);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamicWithOutVar()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out var x1] + x1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl));
Assert.True(x1.Type.IsErrorType());
VerifyModelForOutVar(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// var x = d[out var x1] + x1;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 27)
);
}
[Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void IndexingDynamicWithOutInt()
{
var text = @"
public class Cls
{
public static void Main()
{
dynamic d = null;
var x = d[out int x1] + x1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl));
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
compilation.VerifyDiagnostics();
}
[ClrOnlyFact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")]
public void OutVariableDeclarationInIndex()
{
var source1 =
@".class interface public abstract import IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 )
.method public abstract virtual instance int32 get_Item([out] int32& i) { }
.method public abstract virtual instance void set_Item([out] int32& i, int32 v) { }
.property instance int32 Item([out] int32&)
{
.get instance int32 IA::get_Item([out] int32&)
.set instance void IA::set_Item([out] int32&, int32)
}
.method public abstract virtual instance int32 get_P([out] int32& i) { }
.method public abstract virtual instance void set_P([out] int32& i, int32 v) { }
.property instance int32 P([out] int32&)
{
.get instance int32 IA::get_P([out] int32&)
.set instance void IA::set_P([out] int32&, int32)
}
}
.class public A implements IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ret
}
// i = 1; return 2;
.method public virtual instance int32 get_P([out] int32& i)
{
ldarg.1
ldc.i4.1
stind.i4
ldc.i4.2
ret
}
// i = 3; return;
.method public virtual instance void set_P([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.3
stind.i4
ret
}
.property instance int32 P([out] int32&)
{
.get instance int32 A::get_P([out] int32&)
.set instance void A::set_P([out] int32&, int32)
}
// i = 4; return 5;
.method public virtual instance int32 get_Item([out] int32& i)
{
ldarg.1
ldc.i4.4
stind.i4
ldc.i4.5
ret
}
// i = 6; return;
.method public virtual instance void set_Item([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.6
stind.i4
ret
}
.property instance int32 Item([out] int32&)
{
.get instance int32 A::get_Item([out] int32&)
.set instance void A::set_Item([out] int32&, int32)
}
}";
var reference1 = CompileIL(source1);
var source2Template =
@"using System;
class B
{{
public static void Main()
{{
A a = new A();
IA ia = a;
Console.WriteLine(ia.P[out {0} x1] + "" "" + x1);
ia.P[out {0} x2] = 4;
Console.WriteLine(x2);
Console.WriteLine(ia[out {0} x3] + "" "" + x3);
ia[out {0} x4] = 4;
Console.WriteLine(x4);
}}
}}";
string[] fillIns = new[] { "int", "var" };
foreach (var fillIn in fillIns)
{
var source2 = string.Format(source2Template, fillIn);
var compilation = CreateCompilation(source2, references: new[] { reference1 });
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(1, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x2Ref[0]).Type.ToTestDisplayString());
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(1, x3Ref.Length);
VerifyModelForOutVar(model, x3Decl, x3Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x3Ref[0]).Type.ToTestDisplayString());
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(1, x4Ref.Length);
VerifyModelForOutVar(model, x4Decl, x4Ref);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref[0]).Type.ToTestDisplayString());
CompileAndVerify(source2, references: new[] { reference1 }, expectedOutput:
@"2 1
3
5 4
6")
.VerifyIL("B.Main()",
@"{
// Code size 113 (0x71)
.maxstack 4
.locals init (int V_0, //x1
int V_1, //x2
int V_2, //x3
int V_3, //x4
int V_4)
IL_0000: newobj ""A..ctor()""
IL_0005: dup
IL_0006: ldloca.s V_0
IL_0008: callvirt ""int IA.P[out int].get""
IL_000d: stloc.s V_4
IL_000f: ldloca.s V_4
IL_0011: call ""string int.ToString()""
IL_0016: ldstr "" ""
IL_001b: ldloca.s V_0
IL_001d: call ""string int.ToString()""
IL_0022: call ""string string.Concat(string, string, string)""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: dup
IL_002d: ldloca.s V_1
IL_002f: ldc.i4.4
IL_0030: callvirt ""void IA.P[out int].set""
IL_0035: ldloc.1
IL_0036: call ""void System.Console.WriteLine(int)""
IL_003b: dup
IL_003c: ldloca.s V_2
IL_003e: callvirt ""int IA.this[out int].get""
IL_0043: stloc.s V_4
IL_0045: ldloca.s V_4
IL_0047: call ""string int.ToString()""
IL_004c: ldstr "" ""
IL_0051: ldloca.s V_2
IL_0053: call ""string int.ToString()""
IL_0058: call ""string string.Concat(string, string, string)""
IL_005d: call ""void System.Console.WriteLine(string)""
IL_0062: ldloca.s V_3
IL_0064: ldc.i4.4
IL_0065: callvirt ""void IA.this[out int].set""
IL_006a: ldloc.3
IL_006b: call ""void System.Console.WriteLine(int)""
IL_0070: ret
}");
}
}
[ClrOnlyFact]
public void OutVariableDiscardInIndex()
{
var source1 =
@".class interface public abstract import IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 )
.method public abstract virtual instance int32 get_Item([out] int32& i) { }
.method public abstract virtual instance void set_Item([out] int32& i, int32 v) { }
.property instance int32 Item([out] int32&)
{
.get instance int32 IA::get_Item([out] int32&)
.set instance void IA::set_Item([out] int32&, int32)
}
.method public abstract virtual instance int32 get_P([out] int32& i) { }
.method public abstract virtual instance void set_P([out] int32& i, int32 v) { }
.property instance int32 P([out] int32&)
{
.get instance int32 IA::get_P([out] int32&)
.set instance void IA::set_P([out] int32&, int32)
}
}
.class public A implements IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item..
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ret
}
// i = 1; System.Console.WriteLine(11); return 111;
.method public virtual instance int32 get_P([out] int32& i)
{
ldarg.1
ldc.i4.1
stind.i4
ldc.i4.s 11
call void [mscorlib]System.Console::WriteLine(int32)
ldc.i4 0x06F
ret
}
// i = 2; System.Console.Write(22); return;
.method public virtual instance void set_P([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.2
stind.i4
ldc.i4.s 22
call void [mscorlib]System.Console::WriteLine(int32)
ret
}
.property instance int32 P([out] int32&)
{
.get instance int32 A::get_P([out] int32&)
.set instance void A::set_P([out] int32&, int32)
}
// i = 3; System.Console.WriteLine(33) return 333;
.method public virtual instance int32 get_Item([out] int32& i)
{
ldarg.1
ldc.i4.3
stind.i4
ldc.i4.s 33
call void [mscorlib]System.Console::WriteLine(int32)
ldc.i4 0x14D
ret
}
// i = 4; System.Console.WriteLine(44); return;
.method public virtual instance void set_Item([out] int32& i, int32 v)
{
ldarg.1
ldc.i4.4
stind.i4
ldc.i4.s 44
call void [mscorlib]System.Console::WriteLine(int32)
ret
}
.property instance int32 Item([out] int32&)
{
.get instance int32 A::get_Item([out] int32&)
.set instance void A::set_Item([out] int32&, int32)
}
}";
var reference1 = CompileIL(source1);
var source2Template =
@"using System;
class B
{{
public static void Main()
{{
A a = new A();
IA ia = a;
Console.WriteLine(ia.P[out {0} _]);
ia.P[out {0} _] = 4;
Console.WriteLine(ia[out {0} _]);
ia[out {0} _] = 4;
}}
}}";
string[] fillIns = new[] { "int", "var", "" };
foreach (var fillIn in fillIns)
{
var source2 = string.Format(source2Template, fillIn);
var compilation = CreateCompilation(source2, references: new[] { reference1 }, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput:
@"11
111
22
33
333
44")
.VerifyIL("B.Main()",
@"
{
// Code size 58 (0x3a)
.maxstack 3
.locals init (A V_0, //a
IA V_1, //ia
int V_2)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloca.s V_2
IL_000c: callvirt ""int IA.P[out int].get""
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: nop
IL_0017: ldloc.1
IL_0018: ldloca.s V_2
IL_001a: ldc.i4.4
IL_001b: callvirt ""void IA.P[out int].set""
IL_0020: nop
IL_0021: ldloc.1
IL_0022: ldloca.s V_2
IL_0024: callvirt ""int IA.this[out int].get""
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ldloc.1
IL_0030: ldloca.s V_2
IL_0032: ldc.i4.4
IL_0033: callvirt ""void IA.this[out int].set""
IL_0038: nop
IL_0039: ret
}");
}
}
[Fact]
public void ElementAccess_04()
{
var text = @"
using System.Collections.Generic;
public class Cls
{
public static void Main()
{
var list = new Dictionary<int, long>
{
[out var x1] = 3,
[out var _] = 4,
[out _] = 5
};
System.Console.Write(x1);
System.Console.Write(_);
{
int _ = 1;
var list2 = new Dictionary<int, long> { [out _] = 6 };
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.ToTestDisplayString());
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (9,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out var x1] = 3,
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(9, 18),
// (10,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out var _] = 4,
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(10, 18),
// (11,18): error CS1615: Argument 1 may not be passed with the 'out' keyword
// [out _] = 5
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(11, 18),
// (14,30): error CS0103: The name '_' does not exist in the current context
// System.Console.Write(_);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 30),
// (18,58): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var list2 = new Dictionary<int, long> { [out _] = 6 };
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(18, 58)
);
}
[Fact]
public void ElementAccess_05()
{
var text = @"
public class Cls
{
public static void Main()
{
int[out var x1] a = null; // fatal syntax error - 'out' is skipped
int b(out var x2) = null; // parsed as a local function with syntax error
int c[out var x3] = null; // fatal syntax error - 'out' is skipped
int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
x4 = 0;
}
}";
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.Equal(1, compilation.SyntaxTrees[0].GetRoot().DescendantNodesAndSelf().OfType<DeclarationExpressionSyntax>().Count());
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
compilation.VerifyDiagnostics(
// (6,13): error CS1003: Syntax error, ',' expected
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 13),
// (6,21): error CS1003: Syntax error, ',' expected
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 21),
// (7,27): error CS1002: ; expected
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(7, 27),
// (7,27): error CS1525: Invalid expression term '='
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 27),
// (8,14): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_CStyleArray, "[out var x3]").WithLocation(8, 14),
// (8,15): error CS1003: Syntax error, ',' expected
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 15),
// (8,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "var").WithLocation(8, 19),
// (8,23): error CS1003: Syntax error, ',' expected
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 23),
// (8,23): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "x3").WithLocation(8, 23),
// (10,17): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x4").WithLocation(10, 17),
// (10,17): error CS1003: Syntax error, '[' expected
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(10, 17),
// (10,28): error CS1003: Syntax error, ']' expected
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(10, 28),
// (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[out var x1]").WithLocation(6, 12),
// (6,17): error CS0103: The name 'var' does not exist in the current context
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 17),
// (6,21): error CS0103: The name 'x1' does not exist in the current context
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 21),
// (7,13): error CS8112: 'b(out var)' is a local function and must therefore always have a body.
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "b").WithArguments("b(out var)").WithLocation(7, 13),
// (7,19): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 19),
// (8,29): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 29),
// (8,19): error CS0103: The name 'var' does not exist in the current context
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19),
// (8,23): error CS0103: The name 'x3' does not exist in the current context
// int c[out var x3] = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(8, 23),
// (7,13): error CS0177: The out parameter 'x2' must be assigned to before control leaves the current method
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.ERR_ParamUnassigned, "b").WithArguments("x2").WithLocation(7, 13),
// (6,25): warning CS0219: The variable 'a' is assigned but its value is never used
// int[out var x1] a = null; // fatal syntax error - 'out' is skipped
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(6, 25),
// (10,13): warning CS0168: The variable 'd' is declared but never used
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.WRN_UnreferencedVar, "d").WithArguments("d").WithLocation(10, 13),
// (10,16): warning CS0168: The variable 'e' is declared but never used
// int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator
Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(10, 16),
// (7,13): warning CS8321: The local function 'b' is declared but never used
// int b(out var x2) = null; // parsed as a local function with syntax error
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "b").WithArguments("b").WithLocation(7, 13)
);
}
[Fact]
public void ElementAccess_06()
{
var text = @"
public class Cls
{
public static void Main()
{
{
int[] e = null;
var z1 = e?[out var x1];
x1 = 1;
}
{
int[][] e = null;
var z2 = e?[out var x2]?[out var x3];
x2 = 1;
x3 = 2;
}
{
int[][] e = null;
var z3 = e?[0]?[out var x4];
x4 = 1;
}
}
}";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.True(model.GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error);
var x2Decl = GetOutVarDeclaration(tree, "x2");
var x2Ref = GetReference(tree, "x2");
Assert.True(model.GetTypeInfo(x2Ref).Type.TypeKind == TypeKind.Error);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
Assert.True(model.GetTypeInfo(x3Ref).Type.TypeKind == TypeKind.Error);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
Assert.True(model.GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error);
VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref);
compilation.VerifyDiagnostics(
// (8,29): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z1 = e?[out var x1];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(8, 29),
// (8,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// var z1 = e?[out var x1];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(8, 33),
// (13,29): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z2 = e?[out var x2]?[out var x3];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x2").WithArguments("1", "out").WithLocation(13, 29),
// (13,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x2'.
// var z2 = e?[out var x2]?[out var x3];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x2").WithArguments("x2").WithLocation(13, 33),
// (19,33): error CS1615: Argument 1 may not be passed with the 'out' keyword
// var z3 = e?[0]?[out var x4];
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x4").WithArguments("1", "out").WithLocation(19, 33),
// (19,37): error CS8197: Cannot infer the type of implicitly-typed out variable 'x4'.
// var z3 = e?[0]?[out var x4];
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x4").WithArguments("x4").WithLocation(19, 37)
);
}
[Fact]
public void FixedFieldSize()
{
var text = @"
unsafe struct S
{
fixed int F1[out var x1, x1];
//fixed int F2[3 is int x2 ? x2 : 3];
//fixed int F2[3 is int x3 ? 3 : 3, x3];
}
";
var compilation = CreateCompilation(text,
options: TestOptions.ReleaseDebugDll.WithAllowUnsafe(true),
parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.Empty(GetOutVarDeclarations(tree, "x1"));
compilation.VerifyDiagnostics(
// (4,18): error CS1003: Syntax error, ',' expected
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(4, 18),
// (4,26): error CS1003: Syntax error, ',' expected
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(4, 26),
// (4,17): error CS7092: A fixed buffer may only have one dimension.
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x1, x1]").WithLocation(4, 17),
// (4,22): error CS0103: The name 'var' does not exist in the current context
// fixed int F1[out var x1, x1];
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 22)
);
}
[Fact]
public void Scope_DeclaratorArguments_01()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
int d,e(Dummy(TakeOutParam(true, out var x1), x1));
}
void Test4()
{
var x4 = 11;
Dummy(x4);
int d,e(Dummy(TakeOutParam(true, out var x4), x4));
}
void Test6()
{
int d,e(Dummy(x6 && TakeOutParam(true, out var x6)));
}
void Test8()
{
int d,e(Dummy(TakeOutParam(true, out var x8), x8));
System.Console.WriteLine(x8);
}
void Test14()
{
int d,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (19,50): error CS0128: A local variable named 'x4' is already defined in this scope
// int d,e(Dummy(TakeOutParam(true, out var x4), x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50),
// (24,23): error CS0841: Cannot use local variable 'x6' before it is declared
// int d,e(Dummy(x6 && TakeOutParam(true, out var x6)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23),
// (30,34): error CS0165: Use of unassigned local variable 'x8'
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(30, 34),
// (36,47): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyNotAnOutLocal(model, x4Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").Single();
Assert.Equal(2, x14Decl.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
private static void AssertContainedInDeclaratorArguments(DeclarationExpressionSyntax decl)
{
Assert.True(decl.Ancestors().OfType<VariableDeclaratorSyntax>().First().ArgumentList.Contains(decl));
}
private static void AssertContainedInDeclaratorArguments(params DeclarationExpressionSyntax[] decls)
{
foreach (var decl in decls)
{
AssertContainedInDeclaratorArguments(decl);
}
}
[Fact]
public void Scope_DeclaratorArguments_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
var d, x1(
Dummy(TakeOutParam(true, out var x1), x1));
Dummy(x1);
}
void Test2()
{
object d, x2(
Dummy(TakeOutParam(true, out var x2), x2));
Dummy(x2);
}
void Test3()
{
object x3, d(
Dummy(TakeOutParam(true, out var x3), x3));
Dummy(x3);
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,13): error CS0818: Implicitly-typed variables must be initialized
// var d, x1(
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(12, 13),
// (13,51): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1), x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (21,15): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 15),
// (27,54): error CS0128: A local variable named 'x3' is already defined in this scope
// Dummy(TakeOutParam(true, out var x3), x3));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(27, 54),
// (28,15): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(28, 15)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1( Dummy(x1));
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2(Dummy(TakeOutParam(true, out var x2), x2));
}
void Test3()
{
object d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2(Dummy(x3));
}
void Test4()
{
object d1,e(Dummy(x4)],
d2(Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1( Dummy(x1));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (14,15): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 15),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2(Dummy(TakeOutParam(true, out var x2), x2));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1,e(Dummy(x4)],
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
object Dummy(params object[] x) {return null;}
void Test1()
{
object d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1 = Dummy(x1);
Dummy(x1);
}
void Test2()
{
object d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2 = Dummy(TakeOutParam(true, out var x2), x2);
}
void Test3()
{
object d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2 = Dummy(x3);
}
void Test4()
{
object d1 = Dummy(x4),
d2 (Dummy(TakeOutParam(true, out var x4), x4));
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,16): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16),
// (13,27): error CS0165: Use of unassigned local variable 'x1'
// x1 = Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 27),
// (20,54): error CS0128: A local variable named 'x2' is already defined in this scope
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54),
// (20,59): error CS0165: Use of unassigned local variable 'x2'
// d2 = Dummy(TakeOutParam(true, out var x2), x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59),
// (26,27): error CS0165: Use of unassigned local variable 'x3'
// d2 = Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(26, 27),
// (31,27): error CS0841: Cannot use local variable 'x4' before it is declared
// object d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl[0]);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
long Dummy(params object[] x) {}
void Test1()
{
SpeculateHere();
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@"
var y, y1(Dummy(TakeOutParam(true, out var x1), x1));
");
bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model);
Assert.True(success);
Assert.NotNull(model);
tree = statement.SyntaxTree;
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString());
var y1 = model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single();
Assert.Equal("var y1", y1.ToTestDisplayString());
Assert.True(((ILocalSymbol)y1).Type.IsErrorType());
}
[Fact]
public void Scope_DeclaratorArguments_06()
{
var source =
@"
public class X
{
public static void Main()
{
}
void Test1()
{
if (true)
var d,e(TakeOutParam(true, out var x1) && x1 != null);
x1++;
}
static bool TakeOutParam(object y, out object x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var d =TakeOutParam(true, out var x1) && x1 != null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d,e(TakeOutParam(true, out var x1) && x1 != null);").WithLocation(11, 13),
// (11,17): error CS0818: Implicitly-typed variables must be initialized
// var d,e(TakeOutParam(true, out var x1) && x1 != null);
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(11, 17),
// (13,9): error CS0103: The name 'x1' does not exist in the current context
// x1++;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var e = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "e").Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(e);
Assert.Equal("var e", symbol.ToTestDisplayString());
Assert.True(symbol.Type.IsErrorType());
}
[Fact]
[WorkItem(13460, "https://github.com/dotnet/roslyn/issues/13460")]
public void Scope_DeclaratorArguments_07()
{
var source =
@"
public class X
{
public static void Main()
{
Test(1);
}
static void Test(int val)
{
switch (val)
{
case 1 when TakeOutParam(123, out var x1):
var z, z1(x1, out var u1, x1 > 0 & TakeOutParam(x1, out var y1)];
System.Console.WriteLine(y1);
System.Console.WriteLine(z1 ? 1 : 0);
break;
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
AssertContainedInDeclaratorArguments(y1Decl);
var yRef = GetReference(tree, "y1");
Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString());
model = compilation.GetSemanticModel(tree);
var zRef = GetReference(tree, "z1");
Assert.True(((ITypeSymbol)model.GetTypeInfo(zRef).Type).IsErrorType());
}
[Fact]
[WorkItem(13459, "https://github.com/dotnet/roslyn/issues/13459")]
public void Scope_DeclaratorArguments_08()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test1()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x1) && x1)
);;)
{
Dummy(x1);
}
}
void Test2()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x2) && x2)
);;)
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
for (bool a, b(
Dummy(TakeOutParam(true, out var x4) && x4)
);;)
Dummy(x4);
}
void Test6()
{
for (bool a, b(
Dummy(x6 && TakeOutParam(true, out var x6))
);;)
Dummy(x6);
}
void Test7()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x7) && x7)
);;)
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
for (bool a, b(
Dummy(TakeOutParam(true, out var x8) && x8)
);;)
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
for (bool a1, b1(
Dummy(TakeOutParam(true, out var x9) && x9)
);;)
{
Dummy(x9);
for (bool a2, b2(
Dummy(TakeOutParam(true, out var x9) && x9) // 2
);;)
Dummy(x9);
}
}
void Test10()
{
for (bool a, b(
Dummy(TakeOutParam(y10, out var x10))
);;)
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// for (bool a, b(
// Dummy(TakeOutParam(y11, out var x11))
// );;)
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
for (bool a, b(
Dummy(TakeOutParam(y12, out var x12))
);;)
var y12 = 12;
}
//void Test13()
//{
// for (bool a, b(
// Dummy(TakeOutParam(y13, out var x13))
// );;)
// let y13 = 12;
//}
void Test14()
{
for (bool a, b(
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
);;)
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13),
// (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47),
// (42,20): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20),
// (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17),
// (65,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34),
// (65,9): warning CS0162: Unreachable code detected
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9),
// (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51),
// (85,33): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33),
// (107,33): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33),
// (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17),
// (124,44): error CS0128: A local variable named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_09()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(params object[] x) {return true;}
void Test4()
{
for (bool d, x4(
Dummy(TakeOutParam(true, out var x4) && x4)
);;)
{}
}
void Test7()
{
for (bool x7 = true, b(
Dummy(TakeOutParam(true, out var x7) && x7)
);;)
{}
}
void Test8()
{
for (bool d,b1(Dummy(TakeOutParam(true, out var x8) && x8)],
b2(Dummy(TakeOutParam(true, out var x8) && x8));
Dummy(TakeOutParam(true, out var x8) && x8);
Dummy(TakeOutParam(true, out var x8) && x8))
{}
}
void Test9()
{
for (bool b = x9,
b2(Dummy(TakeOutParam(true, out var x9) && x9));
Dummy(TakeOutParam(true, out var x9) && x9);
Dummy(TakeOutParam(true, out var x9) && x9))
{}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,47): error CS0128: A local variable or function named 'x4' is already defined in this scope
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 47),
// (21,47): error CS0128: A local variable or function named 'x7' is already defined in this scope
// Dummy(TakeOutParam(true, out var x7) && x7)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(21, 47),
// (20,19): warning CS0219: The variable 'x7' is assigned but its value is never used
// for (bool x7 = true, b(
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x7").WithArguments("x7").WithLocation(20, 19),
// (29,52): error CS0128: A local variable or function named 'x8' is already defined in this scope
// b2(Dummy(TakeOutParam(true, out var x8) && x8));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(29, 52),
// (30,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(30, 47),
// (31,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x8) && x8))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(31, 47),
// (37,23): error CS0841: Cannot use local variable 'x9' before it is declared
// for (bool b = x9,
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(37, 23),
// (39,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(39, 47),
// (40,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(40, 47)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl);
VerifyNotAnOutLocal(model, x4Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").Single();
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x7Decl);
VerifyNotAnOutLocal(model, x7Ref);
var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(4, x8Decl.Length);
Assert.Equal(4, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl[0]);
AssertContainedInDeclaratorArguments(x8Decl[1]);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl[0], x8Ref[0], x8Ref[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]);
VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]);
VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(3, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl[0]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]);
VerifyModelForOutVar(model, x9Decl[2], x9Ref[3]);
}
[Fact]
public void Scope_DeclaratorArguments_10()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,e(Dummy(TakeOutParam(true, out var x1), x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (var d,e(Dummy(TakeOutParam(true, out var x2), x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
using (var d,e(Dummy(TakeOutParam(true, out var x4), x4)))
Dummy(x4);
}
void Test6()
{
using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Dummy(x6);
}
void Test7()
{
using (var d,e(Dummy(TakeOutParam(true, out var x7) && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
using (var d,e(Dummy(TakeOutParam(true, out var x8), x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
using (var d,a(Dummy(TakeOutParam(true, out var x9), x9)))
{
Dummy(x9);
using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2
Dummy(x9);
}
}
void Test10()
{
using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10)))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// using (var d,e(Dummy(TakeOutParam(y11, out var x11), x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12)))
var y12 = 12;
}
//void Test13()
//{
// using (var d,e(Dummy(TakeOutParam(y13, out var x13), x13)))
// let y13 = 12;
//}
void Test14()
{
using (var d,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)))
{
Dummy(x14);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var d,e(Dummy(TakeOutParam(true, out var x4), x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57),
// (35,30): error CS0841: Cannot use local variable 'x6' before it is declared
// using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61),
// (68,43): error CS0103: The name 'y10' does not exist in the current context
// using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43),
// (86,43): error CS0103: The name 'y12' does not exist in the current context
// using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,54): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
AssertContainedInDeclaratorArguments(x10Decl);
VerifyModelForOutVarWithoutDataFlow(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_11()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1)))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2)))
{
Dummy(x2);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (12,58): error CS0128: A local variable or function named 'x1' is already defined in this scope
// using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58),
// (20,73): error CS0128: A local variable or function named 'x2' is already defined in this scope
// using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
AssertContainedInDeclaratorArguments(x2Decl);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
}
[Fact]
public void Scope_DeclaratorArguments_12()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(params object[] x) {return null;}
void Test1()
{
using (System.IDisposable d,e(Dummy(TakeOutParam(true, out var x1), x1)],
x1 = Dummy(x1))
{
Dummy(x1);
}
}
void Test2()
{
using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x2), x2)],
d2(Dummy(TakeOutParam(true, out var x2), x2)))
{
Dummy(x2);
}
}
void Test3()
{
using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x3), x3)],
d2 = Dummy(x3))
{
Dummy(x3);
}
}
void Test4()
{
using (System.IDisposable d1 = Dummy(x4),
d2(Dummy(TakeOutParam(true, out var x4), x4)))
{
Dummy(x4);
}
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (13,35): error CS0128: A local variable named 'x1' is already defined in this scope
// x1 = Dummy(x1))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35),
// (22,73): error CS0128: A local variable named 'x2' is already defined in this scope
// d2(Dummy(TakeOutParam(true, out var x2), x2)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73),
// (39,46): error CS0841: Cannot use local variable 'x4' before it is declared
// using (System.IDisposable d1 = Dummy(x4),
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(3, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref);
}
[Fact]
public void Scope_DeclaratorArguments_13()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
void Test1()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x1) && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x2) && x2)))
Dummy(x2);
}
void Test4()
{
var x4 = 11;
Dummy(x4);
fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4)))
Dummy(x4);
}
void Test6()
{
fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Dummy(x6);
}
void Test7()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x7) && x7)))
{
var x7 = 12;
Dummy(x7);
}
}
void Test8()
{
fixed (int* p,e(Dummy(TakeOutParam(true, out var x8) && x8)))
Dummy(x8);
System.Console.WriteLine(x8);
}
void Test9()
{
fixed (int* p1,a(Dummy(TakeOutParam(true, out var x9) && x9)))
{
Dummy(x9);
fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2
Dummy(x9);
}
}
void Test10()
{
fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10))))
{
var y10 = 12;
Dummy(y10);
}
}
//void Test11()
//{
// fixed (int* p,e(Dummy(TakeOutParam(y11, out var x11))))
// {
// let y11 = 12;
// Dummy(y11);
// }
//}
void Test12()
{
fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12))))
var y12 = 12;
}
//void Test13()
//{
// fixed (int* p,e(Dummy(TakeOutParam(y13, out var x13))))
// let y13 = 12;
//}
void Test14()
{
fixed (int* p,e(Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)))
{
Dummy(x14);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13),
// (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4)))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58),
// (35,31): error CS0841: Cannot use local variable 'x6' before it is declared
// fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6))))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31),
// (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17),
// (53,34): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34),
// (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63),
// (68,44): error CS0103: The name 'y10' does not exist in the current context
// fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10))))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44),
// (86,44): error CS0103: The name 'y12' does not exist in the current context
// fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12))))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44),
// (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17),
// (99,55): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
AssertContainedInDeclaratorArguments(x8Decl);
VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
AssertContainedInDeclaratorArguments(x9Decl);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
AssertContainedInDeclaratorArguments(x14Decl);
VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_14()
{
var source =
@"
public unsafe class X
{
public static void Main()
{
}
int[] Dummy(params object[] x) {return null;}
int[] Dummy(int* x) {return null;}
void Test1()
{
fixed (int* d,x1(
Dummy(TakeOutParam(true, out var x1) && x1)))
{
Dummy(x1);
}
}
void Test2()
{
fixed (int* d,p(Dummy(TakeOutParam(true, out var x2) && x2)],
x2 = Dummy())
{
Dummy(x2);
}
}
void Test3()
{
fixed (int* x3 = Dummy(),
p(Dummy(TakeOutParam(true, out var x3) && x3)))
{
Dummy(x3);
}
}
void Test4()
{
fixed (int* d,p1(Dummy(TakeOutParam(true, out var x4) && x4)],
p2(Dummy(TakeOutParam(true, out var x4) && x4)))
{
Dummy(x4);
}
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
(int)ErrorCode.ERR_SyntaxError,
(int)ErrorCode.ERR_UnexpectedToken,
(int)ErrorCode.WRN_UnreferencedVar,
(int)ErrorCode.ERR_FixedMustInit,
(int)ErrorCode.ERR_UseDefViolation,
(int)ErrorCode.ERR_CloseParenExpected
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (14,59): error CS0128: A local variable named 'x1' is already defined in this scope
// Dummy(TakeOutParam(true, out var x1) && x1)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59),
// (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// Dummy(TakeOutParam(true, out var x1) && x1)))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32),
// (23,21): error CS0128: A local variable named 'x2' is already defined in this scope
// x2 = Dummy())
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21),
// (32,58): error CS0128: A local variable named 'x3' is already defined in this scope
// p(Dummy(TakeOutParam(true, out var x3) && x3)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58),
// (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*'
// p(Dummy(TakeOutParam(true, out var x3) && x3)))
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31),
// (41,59): error CS0128: A local variable named 'x4' is already defined in this scope
// p2(Dummy(TakeOutParam(true, out var x4) && x4)))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
VerifyNotAnOutLocal(model, x1Ref[0]);
VerifyNotAnOutLocal(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
AssertContainedInDeclaratorArguments(x2Decl);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(2, x3Ref.Length);
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelForOutVarDuplicateInSameScope(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyNotAnOutLocal(model, x3Ref[1]);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(2, x4Decl.Length);
Assert.Equal(3, x4Ref.Length);
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelForOutVarWithoutDataFlow(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
[Fact]
public void Scope_DeclaratorArguments_15()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
bool Test4 [x4 && TakeOutParam(4, out var x4)];
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (20,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
private static void VerifyModelNotSupported(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
var variableDeclaratorSyntax = GetVariableDesignation(decl);
Assert.Null(model.GetDeclaredSymbol(variableDeclaratorSyntax));
Assert.Null(model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax));
var identifierText = decl.Identifier().ValueText;
Assert.False(model.LookupSymbols(decl.SpanStart, name: identifierText).Any());
Assert.False(model.LookupNames(decl.SpanStart).Contains(identifierText));
Assert.Null(model.GetSymbolInfo(decl.Type).Symbol);
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: null, expectedType: null);
VerifyModelNotSupported(model, references);
}
private static void VerifyModelNotSupported(SemanticModel model, params IdentifierNameSyntax[] references)
{
foreach (var reference in references)
{
Assert.Null(model.GetSymbolInfo(reference).Symbol);
Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
Assert.DoesNotContain(reference.Identifier.ValueText, model.LookupNames(reference.SpanStart));
Assert.True(((ITypeSymbol)model.GetTypeInfo(reference).Type).IsErrorType());
}
}
[Fact]
public void Scope_DeclaratorArguments_16()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
fixed
bool Test4 [x4 && TakeOutParam(4, out var x4)];
fixed
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
fixed
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
fixed
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
fixed
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.WRN_UnreferencedField,
(int)ErrorCode.ERR_NoImplicitConv
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (10,18): error CS0841: Cannot use local variable 'x4' before it is declared
// bool Test4 [x4 && TakeOutParam(4, out var x4)];
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18),
// (13,43): error CS0128: A local variable named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43),
// (20,25): error CS0103: The name 'x7' does not exist in the current context
// bool Test72 [Dummy(x7, 2)];
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 25),
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_17()
{
var source =
@"
public class X
{
public static void Main()
{
}
const
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
const
bool Test4 [x4 && TakeOutParam(4, out var x4)];
const
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
const
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
const
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
const
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_18()
{
var source =
@"
public class X
{
public static void Main()
{
}
event
bool Test3 [TakeOutParam(3, out var x3) && x3 > 0];
event
bool Test4 [x4 && TakeOutParam(4, out var x4)];
event
bool Test5 [TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0];
event
bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0];
event
bool Test71 [TakeOutParam(7, out var x7) && x7 > 0];
event
bool Test72 [Dummy(x7, 2)];
void Test73() { Dummy(x7, 3); }
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray,
(int)ErrorCode.ERR_ArraySizeInDeclaration,
(int)ErrorCode.ERR_EventNotDelegate,
(int)ErrorCode.WRN_UnreferencedEvent
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (21,27): error CS0103: The name 'x7' does not exist in the current context
// void Test73() { Dummy(x7, 3); }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
AssertContainedInDeclaratorArguments(x4Decl);
VerifyModelNotSupported(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
AssertContainedInDeclaratorArguments(x5Decl);
VerifyModelNotSupported(model, x5Decl[0], x5Ref);
VerifyModelNotSupported(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
AssertContainedInDeclaratorArguments(x6Decl);
VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]);
VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
AssertContainedInDeclaratorArguments(x7Decl);
VerifyModelNotSupported(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_DeclaratorArguments_19()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool d[2], Test3 (out var x3);
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl,
};
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (8,28): error CS1003: Syntax error, '[' expected
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(8, 28),
// (8,39): error CS1003: Syntax error, ']' expected
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(8, 39),
// (8,33): error CS8185: A declaration is not allowed in this context.
// fixed bool d[2], Test3 (out var x3);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x3").WithLocation(8, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
AssertContainedInDeclaratorArguments(x3Decl);
VerifyModelNotSupported(model, x3Decl);
}
[Fact]
public void Scope_DeclaratorArguments_20()
{
var source =
@"
public unsafe struct X
{
public static void Main()
{
}
fixed bool Test3[out var x3];
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (8,22): error CS1003: Syntax error, ',' expected
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 22),
// (8,30): error CS1003: Syntax error, ',' expected
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 30),
// (8,21): error CS7092: A fixed buffer may only have one dimension.
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x3]").WithLocation(8, 21),
// (8,26): error CS0103: The name 'var' does not exist in the current context
// fixed bool Test3[out var x3];
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 26)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
Assert.False(GetOutVarDeclarations(tree, "x3").Any());
}
[Fact]
public void StaticType()
{
var text = @"
public class Cls
{
public static void Main()
{
Test1(out StaticType x1);
}
static object Test1(out StaticType x)
{
throw new System.NotSupportedException();
}
static class StaticType {}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (9,19): error CS0721: 'Cls.StaticType': static types cannot be used as parameters
// static object Test1(out StaticType x)
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "Test1").WithArguments("Cls.StaticType").WithLocation(9, 19),
// (6,19): error CS0723: Cannot declare a variable of static type 'Cls.StaticType'
// Test1(out StaticType x1);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "StaticType").WithArguments("Cls.StaticType").WithLocation(6, 19)
);
}
[Fact]
public void GlobalCode_Catch_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
try {}
catch when (TakeOutParam(out var x1) && x1 > 0)
{
Dummy(x1);
}
var x4 = 11;
Dummy(x4);
try {}
catch when (TakeOutParam(out var x4) && x4 > 0)
{
Dummy(x4);
}
try {}
catch when (x6 && TakeOutParam(out var x6))
{
Dummy(x6);
}
try {}
catch when (TakeOutParam(out var x7) && x7 > 0)
{
var x7 = 12;
Dummy(x7);
}
try {}
catch when (TakeOutParam(out var x8) && x8 > 0)
{
Dummy(x8);
}
System.Console.WriteLine(x8);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0)
{
Dummy(x9);
try {}
catch when (TakeOutParam(out var x9) && x9 > 0) // 2
{
Dummy(x9);
}
}
try {}
catch when (TakeOutParam(y10, out var x10))
{
var y10 = 12;
Dummy(y10);
}
// try {}
// catch when (TakeOutParam(y11, out var x11)
// {
// let y11 = 12;
// Dummy(y11);
// }
try {}
catch when (Dummy(TakeOutParam(out var x14),
TakeOutParam(out var x14), // 2
x14))
{
Dummy(x14);
}
try {}
catch (System.Exception x15)
when (Dummy(TakeOutParam(out var x15), x15))
{
Dummy(x15);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (20,13): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13),
// (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9),
// (38,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26),
// (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38),
// (52,26): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26),
// (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42),
// (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (14,34): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x4) && x4 > 0)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(14, 34),
// (20,13): error CS0841: Cannot use local variable 'x6' before it is declared
// catch when (x6 && TakeOutParam(out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13),
// (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9),
// (38,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26),
// (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// catch when (TakeOutParam(out var x9) && x9 > 0) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38),
// (52,26): error CS0103: The name 'y10' does not exist in the current context
// catch when (TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26),
// (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(out var x14), // 2
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42),
// (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope
// when (Dummy(TakeOutParam(out var x15), x15))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42),
// (85,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope
// static bool TakeOutParam(object y, out int x)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13),
// (85,13): warning CS8321: The local function 'TakeOutParam' is declared but never used
// static bool TakeOutParam(object y, out int x)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclaration(tree, "x6");
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclaration(tree, "x8");
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclaration(tree, "x15");
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x15Decl);
VerifyNotAnOutLocal(model, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
}
[Fact]
public void GlobalCode_Catch_02()
{
var source =
@"
try
{
throw new System.InvalidOperationException();
}
catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1))
{
System.Console.WriteLine(x1.GetType());
}
static bool Dummy(object y, object z)
{
System.Console.WriteLine(z.GetType());
return true;
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"System.InvalidOperationException
System.InvalidOperationException");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Block_01()
{
string source =
@"
{
H.TakeOutParam(1, out var x1);
H.Dummy(x1);
}
object x2;
{
H.TakeOutParam(2, out var x2);
H.Dummy(x2);
}
{
H.TakeOutParam(3, out var x3);
}
H.Dummy(x3);
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (15,9): error CS0103: The name 'x3' does not exist in the current context
// H.Dummy(x3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotInScope(model, x3Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,8): warning CS0168: The variable 'x2' is declared but never used
// object x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(7, 8),
// (9,31): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(9, 31),
// (15,9): error CS0103: The name 'x3' does not exist in the current context
// H.Dummy(x3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotInScope(model, x3Ref);
}
}
[Fact]
public void GlobalCode_Block_02()
{
string source =
@"
{
H.TakeOutParam(1, out var x1);
System.Console.WriteLine(x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_For_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
for (
Dummy(TakeOutParam(true, out var x1) && x1)
;;)
{
Dummy(x1);
}
for ( // 2
Dummy(TakeOutParam(true, out var x2) && x2)
;;)
Dummy(x2);
var x4 = 11;
Dummy(x4);
for (
Dummy(TakeOutParam(true, out var x4) && x4)
;;)
Dummy(x4);
for (
Dummy(x6 && TakeOutParam(true, out var x6))
;;)
Dummy(x6);
for (
Dummy(TakeOutParam(true, out var x7) && x7)
;;)
{
var x7 = 12;
Dummy(x7);
}
for (
Dummy(TakeOutParam(true, out var x8) && x8)
;;)
Dummy(x8);
System.Console.WriteLine(x8);
for (
Dummy(TakeOutParam(true, out var x9) && x9)
;;)
{
Dummy(x9);
for (
Dummy(TakeOutParam(true, out var x9) && x9) // 2
;;)
Dummy(x9);
}
for (
Dummy(TakeOutParam(y10, out var x10))
;;)
{
var y10 = 12;
Dummy(y10);
}
// for (
// Dummy(TakeOutParam(y11, out var x11))
// ;;)
// {
// let y11 = 12;
// Dummy(y11);
// }
for (
Dummy(TakeOutParam(y12, out var x12))
;;)
var y12 = 12;
// for (
// Dummy(TakeOutParam(y13, out var x13))
// ;;)
// let y13 = 12;
for (
Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14)
;;)
{
Dummy(x14);
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5),
// (25,15): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15),
// (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9),
// (42,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26),
// (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46),
// (56,28): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28),
// (72,28): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28),
// (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37),
// (11,1): warning CS0162: Unreachable code detected
// for ( // 2
Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1),
// (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (20,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x4) && x4)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(20, 42),
// (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5),
// (25,15): error CS0841: Cannot use local variable 'x6' before it is declared
// Dummy(x6 && TakeOutParam(true, out var x6))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15),
// (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9),
// (42,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26),
// (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Dummy(TakeOutParam(true, out var x9) && x9) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46),
// (56,28): error CS0103: The name 'y10' does not exist in the current context
// Dummy(TakeOutParam(y10, out var x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28),
// (72,28): error CS0103: The name 'y12' does not exist in the current context
// Dummy(TakeOutParam(y12, out var x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28),
// (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37),
// (11,1): warning CS0162: Unreachable code detected
// for ( // 2
Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1),
// (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
}
[Fact]
public void GlobalCode_For_02()
{
var source =
@"
bool f = true;
for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0);
Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1);
Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2))
{
System.Console.WriteLine(x0);
System.Console.WriteLine(x1);
f = false;
}
static bool Dummy(bool x, object y, object z)
{
System.Console.WriteLine(z);
return x;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"10
1
10
1
200
200
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x0Decl = GetOutVarDeclarations(tree, "x0").Single();
var x0Ref = GetReferences(tree, "x0").ToArray();
Assert.Equal(2, x0Ref.Length);
VerifyModelForOutVar(model, x0Decl, x0Ref);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_Foreach_01()
{
var source =
@"using static Helpers;
System.Collections.IEnumerable Dummy(params object[] x) {return null;}
foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1))
{
Dummy(x1);
}
foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2))
Dummy(x2);
var x4 = 11;
Dummy(x4);
foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Dummy(x4);
foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8))
Dummy(x8);
System.Console.WriteLine(x8);
foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9))
{
Dummy(x9);
foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Dummy(x9);
}
foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
{
var y10 = 12;
Dummy(y10);
}
// foreach (var i in Dummy(TakeOutParam(y11, out var x11)))
// {
// let y11 = 12;
// Dummy(y11);
// }
foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
var y12 = 12;
// foreach (var i in Dummy(TakeOutParam(y13, out var x13)))
// let y13 = 12;
foreach (var i in Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
foreach (var x15 in
Dummy(TakeOutParam(1, out var x15), x15))
{
Dummy(x15);
}
static class Helpers
{
public static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
public static bool TakeOutParam(bool y, out bool x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,25): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57),
// (39,38): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38),
// (51,38): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38),
// (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49),
// (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (15,52): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 52),
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,25): error CS0841: Cannot use local variable 'x6' before it is declared
// foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57),
// (39,38): error CS0103: The name 'y10' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y10, out var x10)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38),
// (51,38): error CS0103: The name 'y12' does not exist in the current context
// foreach (var i in Dummy(TakeOutParam(y12, out var x12)))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38),
// (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49),
// (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var x15 in
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
var x15Decl = GetOutVarDeclarations(tree, "x15").Single();
var x15Ref = GetReferences(tree, "x15").ToArray();
Assert.Equal(2, x15Ref.Length);
VerifyModelForOutVar(model, x15Decl, x15Ref[0]);
VerifyNotAnOutLocal(model, x15Ref[1]);
}
}
[Fact]
public void GlobalCode_Foreach_02()
{
var source =
@"
bool f = true;
foreach (var i in Dummy(TakeOutParam(3, out var x1), x1))
{
System.Console.WriteLine(x1);
}
static System.Collections.IEnumerable Dummy(object y, object z)
{
System.Console.WriteLine(z);
return ""a"";
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"3
3");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Lambda_01()
{
var source =
@"
bool Dummy(params object[] x) {return true;}
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x3) && x3 > 0));
Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out var x5) &&
TakeOutParam(o2, out var x5) &&
x5 > 0));
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0));
Dummy(x7, 1);
Dummy(x7,
(System.Func<object, bool>) (o => TakeOutParam(o, out var x7) && x7 > 0),
x7);
Dummy(x7, 2);
Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Dummy(TakeOutParam(true, out var x9),
(System.Func<object, bool>) (o => TakeOutParam(o, out var x9) &&
x9 > 0), x9);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x10) &&
x10 > 0),
TakeOutParam(true, out var x10), x10);
var x11 = 11;
Dummy(x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x11) &&
x11 > 0), x11);
Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x12) &&
x12 > 0),
x12);
var x12 = 11;
Dummy(x12);
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(bool y, out bool x)
{
x = true;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,41): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41),
// (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82),
// (14,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7),
// (15,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7),
// (17,9): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9),
// (18,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutField(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutField(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutField(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,41): error CS0841: Cannot use local variable 'x4' before it is declared
// Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4)));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41),
// (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(o2, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82),
// (14,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7),
// (15,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7),
// (17,9): error CS0103: The name 'x7' does not exist in the current context
// x7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9),
// (18,7): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7),
// (20,7): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int'
// Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 7),
// (20,79): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int'
// Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8));
Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(o, out var y8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 79),
// (37,9): error CS0841: Cannot use local variable 'x12' before it is declared
// x12);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(37, 9),
// (47,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope
// static bool TakeOutParam(bool y, out bool x)
Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13),
// (47,13): warning CS8321: The local function 'TakeOutParam' is declared but never used
// static bool TakeOutParam(bool y, out bool x)
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").Single();
VerifyModelForOutVar(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").Single();
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]);
VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(5, x7Ref.Length);
VerifyNotInScope(model, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyModelForOutVar(model, x7Decl, x7Ref[2]);
VerifyNotInScope(model, x7Ref[3]);
VerifyNotInScope(model, x7Ref[4]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(2, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(2, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]);
var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray();
var x10Ref = GetReferences(tree, "x10").ToArray();
Assert.Equal(2, x10Decl.Length);
Assert.Equal(2, x10Ref.Length);
VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]);
VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]);
var x11Decl = GetOutVarDeclarations(tree, "x11").Single();
var x11Ref = GetReferences(tree, "x11").ToArray();
Assert.Equal(3, x11Ref.Length);
VerifyNotAnOutLocal(model, x11Ref[0]);
VerifyModelForOutVar(model, x11Decl, x11Ref[1]);
VerifyNotAnOutLocal(model, x11Ref[2]);
var x12Decl = GetOutVarDeclarations(tree, "x12").Single();
var x12Ref = GetReferences(tree, "x12").ToArray();
Assert.Equal(3, x12Ref.Length);
VerifyModelForOutVar(model, x12Decl, x12Ref[0]);
VerifyNotAnOutLocal(model, x12Ref[1]);
VerifyNotAnOutLocal(model, x12Ref[2]);
}
}
[Fact]
[WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")]
public void GlobalCode_Lambda_02()
{
var source =
@"
System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1);
System.Console.WriteLine(l());
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Lambda_03()
{
var source =
@"
System.Console.WriteLine(((System.Func<bool>)(() => TakeOutParam(1, out int x1) && Dummy(x1)))());
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1
True");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_Query_01()
{
var source =
@"
using System.Linq;
bool Dummy(params object[] x) {return true;}
var r01 = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1}
select x + y1;
Dummy(y1);
var r02 = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0}
from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2}
select x1 + x2 + y2 +
z2;
Dummy(z2);
var r03 = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0}
let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0
select new { x1, x2, y3,
z3};
Dummy(z3);
var r04 = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0}
join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4}
on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) +
v4
equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) +
u4
select new { x1, x2, y4, z4,
u4, v4 };
Dummy(z4);
Dummy(u4);
Dummy(v4);
var r05 = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0}
join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5}
on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) +
v5
equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) +
u5
into g
select new { x1, y5, z5, g,
u5, v5 };
Dummy(z5);
Dummy(u5);
Dummy(v5);
var r06 = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0}
where x > y6 && TakeOutParam(1, out var z6) && z6 == 1
select x + y6 +
z6;
Dummy(z6);
var r07 = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0}
orderby x > y7 && TakeOutParam(1, out var z7) && z7 ==
u7,
x > y7 && TakeOutParam(1, out var u7) && u7 ==
z7
select x + y7 +
z7 + u7;
Dummy(z7);
Dummy(u7);
var r08 = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0}
select x > y8 && TakeOutParam(1, out var z8) && z8 == 1;
Dummy(z8);
var r09 = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0}
group x > y9 && TakeOutParam(1, out var z9) && z9 ==
u9
by
x > y9 && TakeOutParam(1, out var u9) && u9 ==
z9;
Dummy(z9);
Dummy(u9);
var r10 = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0}
from y10 in new[] { 1 }
select x1 + y10;
var r11 = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0}
let y11 = x1 + 1
select x1 + y11;
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (14,21): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21),
// (21,25): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25),
// (28,29): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29),
// (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29),
// (32,25): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25),
// (32,29): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29),
// (41,29): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29),
// (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29),
// (46,25): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25),
// (46,29): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29),
// (55,21): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21),
// (61,21): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21),
// (63,21): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21),
// (65,21): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21),
// (65,26): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26),
// (80,17): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17),
// (77,17): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17),
// (16,7): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7),
// (23,7): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7),
// (35,7): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7),
// (36,7): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7),
// (49,7): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7),
// (50,7): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7),
// (57,7): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7),
// (67,7): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7),
// (68,7): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7),
// (73,7): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7),
// (82,7): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7),
// (83,7): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutField(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutField(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutField(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutField(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutField(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutField(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutField(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutField(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutField(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutField(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutField(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutField(model, y10Decl, y10Ref[0]);
VerifyNotAnOutField(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutField(model, y11Decl, y11Ref[0]);
VerifyNotAnOutField(model, y11Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (14,21): error CS0103: The name 'z2' does not exist in the current context
// z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21),
// (16,7): error CS0103: The name 'z2' does not exist in the current context
// Dummy(z2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7),
// (21,25): error CS0103: The name 'z3' does not exist in the current context
// z3};
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25),
// (23,7): error CS0103: The name 'z3' does not exist in the current context
// Dummy(z3);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7),
// (28,29): error CS0103: The name 'v4' does not exist in the current context
// v4
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29),
// (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u4
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29),
// (32,25): error CS0103: The name 'u4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25),
// (32,29): error CS0103: The name 'v4' does not exist in the current context
// u4, v4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29),
// (35,7): error CS0103: The name 'u4' does not exist in the current context
// Dummy(u4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7),
// (36,7): error CS0103: The name 'v4' does not exist in the current context
// Dummy(v4);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7),
// (41,29): error CS0103: The name 'v5' does not exist in the current context
// v5
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29),
// (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.
// u5
Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29),
// (46,25): error CS0103: The name 'u5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25),
// (46,29): error CS0103: The name 'v5' does not exist in the current context
// u5, v5 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29),
// (49,7): error CS0103: The name 'u5' does not exist in the current context
// Dummy(u5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7),
// (50,7): error CS0103: The name 'v5' does not exist in the current context
// Dummy(v5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7),
// (55,21): error CS0103: The name 'z6' does not exist in the current context
// z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21),
// (57,7): error CS0103: The name 'z6' does not exist in the current context
// Dummy(z6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7),
// (61,21): error CS0103: The name 'u7' does not exist in the current context
// u7,
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21),
// (63,21): error CS0103: The name 'z7' does not exist in the current context
// z7
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21),
// (65,21): error CS0103: The name 'z7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21),
// (65,26): error CS0103: The name 'u7' does not exist in the current context
// z7 + u7;
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26),
// (67,7): error CS0103: The name 'z7' does not exist in the current context
// Dummy(z7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7),
// (68,7): error CS0103: The name 'u7' does not exist in the current context
// Dummy(u7);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7),
// (73,7): error CS0103: The name 'z8' does not exist in the current context
// Dummy(z8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7),
// (77,17): error CS0103: The name 'u9' does not exist in the current context
// u9
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17),
// (80,17): error CS0103: The name 'z9' does not exist in the current context
// z9;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17),
// (82,7): error CS0103: The name 'z9' does not exist in the current context
// Dummy(z9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7),
// (83,7): error CS0103: The name 'u9' does not exist in the current context
// Dummy(u9);
Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7),
// (86,18): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10'
// from y10 in new[] { 1 }
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(86, 18),
// (90,17): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11'
// let y11 = x1 + 1
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(90, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var y1Decl = GetOutVarDeclarations(tree, "y1").Single();
var y1Ref = GetReferences(tree, "y1").ToArray();
Assert.Equal(4, y1Ref.Length);
VerifyModelForOutVar(model, y1Decl, y1Ref);
var y2Decl = GetOutVarDeclarations(tree, "y2").Single();
var y2Ref = GetReferences(tree, "y2").ToArray();
Assert.Equal(3, y2Ref.Length);
VerifyModelForOutVar(model, y2Decl, y2Ref);
var z2Decl = GetOutVarDeclarations(tree, "z2").Single();
var z2Ref = GetReferences(tree, "z2").ToArray();
Assert.Equal(4, z2Ref.Length);
VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]);
VerifyNotInScope(model, z2Ref[2]);
VerifyNotInScope(model, z2Ref[3]);
var y3Decl = GetOutVarDeclarations(tree, "y3").Single();
var y3Ref = GetReferences(tree, "y3").ToArray();
Assert.Equal(3, y3Ref.Length);
VerifyModelForOutVar(model, y3Decl, y3Ref);
var z3Decl = GetOutVarDeclarations(tree, "z3").Single();
var z3Ref = GetReferences(tree, "z3").ToArray();
Assert.Equal(3, z3Ref.Length);
VerifyModelForOutVar(model, z3Decl, z3Ref[0]);
VerifyNotInScope(model, z3Ref[1]);
VerifyNotInScope(model, z3Ref[2]);
var y4Decl = GetOutVarDeclarations(tree, "y4").Single();
var y4Ref = GetReferences(tree, "y4").ToArray();
Assert.Equal(5, y4Ref.Length);
VerifyModelForOutVar(model, y4Decl, y4Ref);
var z4Decl = GetOutVarDeclarations(tree, "z4").Single();
var z4Ref = GetReferences(tree, "z4").ToArray();
Assert.Equal(6, z4Ref.Length);
VerifyModelForOutVar(model, z4Decl, z4Ref);
var u4Decl = GetOutVarDeclarations(tree, "u4").Single();
var u4Ref = GetReferences(tree, "u4").ToArray();
Assert.Equal(4, u4Ref.Length);
VerifyModelForOutVar(model, u4Decl, u4Ref[0]);
VerifyNotInScope(model, u4Ref[1]);
VerifyNotInScope(model, u4Ref[2]);
VerifyNotInScope(model, u4Ref[3]);
var v4Decl = GetOutVarDeclarations(tree, "v4").Single();
var v4Ref = GetReferences(tree, "v4").ToArray();
Assert.Equal(4, v4Ref.Length);
VerifyNotInScope(model, v4Ref[0]);
VerifyModelForOutVar(model, v4Decl, v4Ref[1]);
VerifyNotInScope(model, v4Ref[2]);
VerifyNotInScope(model, v4Ref[3]);
var y5Decl = GetOutVarDeclarations(tree, "y5").Single();
var y5Ref = GetReferences(tree, "y5").ToArray();
Assert.Equal(5, y5Ref.Length);
VerifyModelForOutVar(model, y5Decl, y5Ref);
var z5Decl = GetOutVarDeclarations(tree, "z5").Single();
var z5Ref = GetReferences(tree, "z5").ToArray();
Assert.Equal(6, z5Ref.Length);
VerifyModelForOutVar(model, z5Decl, z5Ref);
var u5Decl = GetOutVarDeclarations(tree, "u5").Single();
var u5Ref = GetReferences(tree, "u5").ToArray();
Assert.Equal(4, u5Ref.Length);
VerifyModelForOutVar(model, u5Decl, u5Ref[0]);
VerifyNotInScope(model, u5Ref[1]);
VerifyNotInScope(model, u5Ref[2]);
VerifyNotInScope(model, u5Ref[3]);
var v5Decl = GetOutVarDeclarations(tree, "v5").Single();
var v5Ref = GetReferences(tree, "v5").ToArray();
Assert.Equal(4, v5Ref.Length);
VerifyNotInScope(model, v5Ref[0]);
VerifyModelForOutVar(model, v5Decl, v5Ref[1]);
VerifyNotInScope(model, v5Ref[2]);
VerifyNotInScope(model, v5Ref[3]);
var y6Decl = GetOutVarDeclarations(tree, "y6").Single();
var y6Ref = GetReferences(tree, "y6").ToArray();
Assert.Equal(3, y6Ref.Length);
VerifyModelForOutVar(model, y6Decl, y6Ref);
var z6Decl = GetOutVarDeclarations(tree, "z6").Single();
var z6Ref = GetReferences(tree, "z6").ToArray();
Assert.Equal(3, z6Ref.Length);
VerifyModelForOutVar(model, z6Decl, z6Ref[0]);
VerifyNotInScope(model, z6Ref[1]);
VerifyNotInScope(model, z6Ref[2]);
var y7Decl = GetOutVarDeclarations(tree, "y7").Single();
var y7Ref = GetReferences(tree, "y7").ToArray();
Assert.Equal(4, y7Ref.Length);
VerifyModelForOutVar(model, y7Decl, y7Ref);
var z7Decl = GetOutVarDeclarations(tree, "z7").Single();
var z7Ref = GetReferences(tree, "z7").ToArray();
Assert.Equal(4, z7Ref.Length);
VerifyModelForOutVar(model, z7Decl, z7Ref[0]);
VerifyNotInScope(model, z7Ref[1]);
VerifyNotInScope(model, z7Ref[2]);
VerifyNotInScope(model, z7Ref[3]);
var u7Decl = GetOutVarDeclarations(tree, "u7").Single();
var u7Ref = GetReferences(tree, "u7").ToArray();
Assert.Equal(4, u7Ref.Length);
VerifyNotInScope(model, u7Ref[0]);
VerifyModelForOutVar(model, u7Decl, u7Ref[1]);
VerifyNotInScope(model, u7Ref[2]);
VerifyNotInScope(model, u7Ref[3]);
var y8Decl = GetOutVarDeclarations(tree, "y8").Single();
var y8Ref = GetReferences(tree, "y8").ToArray();
Assert.Equal(2, y8Ref.Length);
VerifyModelForOutVar(model, y8Decl, y8Ref);
var z8Decl = GetOutVarDeclarations(tree, "z8").Single();
var z8Ref = GetReferences(tree, "z8").ToArray();
Assert.Equal(2, z8Ref.Length);
VerifyModelForOutVar(model, z8Decl, z8Ref[0]);
VerifyNotInScope(model, z8Ref[1]);
var y9Decl = GetOutVarDeclarations(tree, "y9").Single();
var y9Ref = GetReferences(tree, "y9").ToArray();
Assert.Equal(3, y9Ref.Length);
VerifyModelForOutVar(model, y9Decl, y9Ref);
var z9Decl = GetOutVarDeclarations(tree, "z9").Single();
var z9Ref = GetReferences(tree, "z9").ToArray();
Assert.Equal(3, z9Ref.Length);
VerifyModelForOutVar(model, z9Decl, z9Ref[0]);
VerifyNotInScope(model, z9Ref[1]);
VerifyNotInScope(model, z9Ref[2]);
var u9Decl = GetOutVarDeclarations(tree, "u9").Single();
var u9Ref = GetReferences(tree, "u9").ToArray();
Assert.Equal(3, u9Ref.Length);
VerifyNotInScope(model, u9Ref[0]);
VerifyModelForOutVar(model, u9Decl, u9Ref[1]);
VerifyNotInScope(model, u9Ref[2]);
var y10Decl = GetOutVarDeclarations(tree, "y10").Single();
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyModelForOutVar(model, y10Decl, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y11Decl = GetOutVarDeclarations(tree, "y11").Single();
var y11Ref = GetReferences(tree, "y11").ToArray();
Assert.Equal(2, y11Ref.Length);
VerifyModelForOutVar(model, y11Decl, y11Ref[0]);
VerifyNotAnOutLocal(model, y11Ref[1]);
}
}
[Fact]
public void GlobalCode_Query_02()
{
var source =
@"
using System.Linq;
var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0}
select Print(x1);
res.ToArray();
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
static bool Print(object x)
{
System.Console.WriteLine(x);
return true;
}
";
var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
2");
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var yDecl = GetOutVarDeclarations(tree, "y1").Single();
var yRef = GetReferences(tree, "y1").Single();
VerifyModelForOutField(model, yDecl, yRef);
}
[Fact]
public void GlobalCode_Using_01()
{
var source =
@"
System.IDisposable Dummy(params object[] x) {return null;}
using (Dummy(TakeOutParam(true, out var x1), x1))
{
Dummy(x1);
}
using (Dummy(TakeOutParam(true, out var x2), x2))
Dummy(x2);
var x4 = 11;
Dummy(x4);
using (Dummy(TakeOutParam(true, out var x4), x4))
Dummy(x4);
using (Dummy(x6 && TakeOutParam(true, out var x6)))
Dummy(x6);
using (Dummy(TakeOutParam(true, out var x7) && x7))
{
var x7 = 12;
Dummy(x7);
}
using (Dummy(TakeOutParam(true, out var x8), x8))
Dummy(x8);
System.Console.WriteLine(x8);
using (Dummy(TakeOutParam(true, out var x9), x9))
{
Dummy(x9);
using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Dummy(x9);
}
using (Dummy(TakeOutParam(y10, out var x10), x10))
{
var y10 = 12;
Dummy(y10);
}
// using (Dummy(TakeOutParam(y11, out var x11), x11))
// {
// let y11 = 12;
// Dummy(y11);
// }
using (Dummy(TakeOutParam(y12, out var x12), x12))
var y12 = 12;
// using (Dummy(TakeOutParam(y13, out var x13), x13))
// let y13 = 12;
using (Dummy(TakeOutParam(1, out var x14),
TakeOutParam(2, out var x14),
x14))
{
Dummy(x14);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (18,14): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45),
// (39,27): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27),
// (51,27): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27),
// (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (15,41): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x4), x4))
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 41),
// (18,14): error CS0841: Cannot use local variable 'x6' before it is declared
// using (Dummy(x6 && TakeOutParam(true, out var x6)))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14),
// (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// var x7 = 12;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9),
// (30,26): error CS0103: The name 'x8' does not exist in the current context
// System.Console.WriteLine(x8);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26),
// (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (Dummy(TakeOutParam(true, out var x9), x9)) // 2
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45),
// (39,27): error CS0103: The name 'y10' does not exist in the current context
// using (Dummy(TakeOutParam(y10, out var x10), x10))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27),
// (51,27): error CS0103: The name 'y12' does not exist in the current context
// using (Dummy(TakeOutParam(y12, out var x12), x12))
Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27),
// (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement
// var y12 = 12;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5),
// (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used
// var y12 = 12;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9),
// (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope
// TakeOutParam(2, out var x14),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl, x2Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").Single();
var x4Ref = GetReferences(tree, "x4").ToArray();
Assert.Equal(3, x4Ref.Length);
VerifyNotAnOutLocal(model, x4Ref[0]);
VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl, x6Ref);
var x7Decl = GetOutVarDeclarations(tree, "x7").Single();
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(2, x7Ref.Length);
VerifyModelForOutVar(model, x7Decl, x7Ref[0]);
VerifyNotAnOutLocal(model, x7Ref[1]);
var x8Decl = GetOutVarDeclarations(tree, "x8").Single();
var x8Ref = GetReferences(tree, "x8").ToArray();
Assert.Equal(3, x8Ref.Length);
VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]);
VerifyNotInScope(model, x8Ref[2]);
var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray();
var x9Ref = GetReferences(tree, "x9").ToArray();
Assert.Equal(2, x9Decl.Length);
Assert.Equal(4, x9Ref.Length);
VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]);
VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]);
var x10Decl = GetOutVarDeclarations(tree, "x10").Single();
var x10Ref = GetReferences(tree, "x10").Single();
VerifyModelForOutVar(model, x10Decl, x10Ref);
var y10Ref = GetReferences(tree, "y10").ToArray();
Assert.Equal(2, y10Ref.Length);
VerifyNotInScope(model, y10Ref[0]);
VerifyNotAnOutLocal(model, y10Ref[1]);
var y12Ref = GetReferences(tree, "y12").Single();
VerifyNotInScope(model, y12Ref);
var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray();
var x14Ref = GetReferences(tree, "x14").ToArray();
Assert.Equal(2, x14Decl.Length);
Assert.Equal(2, x14Ref.Length);
VerifyModelForOutVar(model, x14Decl[0], x14Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]);
}
}
[Fact]
public void GlobalCode_Using_02()
{
var source =
@"
using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)),
d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2)))
{
System.Console.WriteLine(d1);
System.Console.WriteLine(x1);
System.Console.WriteLine(d2);
System.Console.WriteLine(x2);
}
using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1)))
{
System.Console.WriteLine(x1);
}
static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
class C : System.IDisposable
{
private readonly string _val;
public C(string val)
{
_val = val;
}
public void Dispose()
{
System.Console.WriteLine(""Disposing {0}"", _val);
}
public override string ToString()
{
return _val;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"a
b
c
d
Disposing c
Disposing a
f
Disposing e");
}
[Fact]
public void GlobalCode_ExpressionStatement_01()
{
string source =
@"
H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
H.TakeOutParam(2, out int x2);
H.TakeOutParam(3, out int x3);
object x3;
H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,27): error CS0102: The type 'Script' already contains a definition for 'x2'
// H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,36): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope
// H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36),
// (13,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
private static void AssertNoGlobalStatements(SyntaxTree tree)
{
Assert.Empty(tree.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>());
}
[Fact]
public void GlobalCode_ExpressionStatement_02()
{
string source =
@"
H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
H.TakeOutParam(2, out var x2);
H.TakeOutParam(3, out var x3);
object x3;
H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,27): error CS0102: The type 'Script' already contains a definition for 'x2'
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,36): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope
// H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36),
// (13,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ExpressionStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_IfStatement_01()
{
string source =
@"
if (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
if (H.TakeOutParam(2, out int x2)) {}
if (H.TakeOutParam(3, out int x3)) {}
object x3;
if (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
if (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
int x6 = 6;
if (H.Dummy())
{
string x6 = ""6"";
H.Dummy(x6);
}
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,31): error CS0102: The type 'Script' already contains a definition for 'x2'
// if (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,40): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40),
// (30,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(30, 17),
// (30,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(30, 21),
// (30,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(30, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope
// if (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (21,5): warning CS0219: The variable 'x6' is assigned but its value is never used
// int x6 = 6;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(21, 5),
// (24,12): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// string x6 = "6";
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(24, 12),
// (33,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(33, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_IfStatement_02()
{
string source =
@"
if (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
if (H.TakeOutParam(2, out var x2)) {}
if (H.TakeOutParam(3, out var x3)) {}
object x3;
if (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
if (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,31): error CS0102: The type 'Script' already contains a definition for 'x2'
// if (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,40): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[0], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope
// if (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40),
// (16,29): error CS0841: Cannot use local variable 'x5' before it is declared
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x5").WithArguments("x5").WithLocation(16, 29),
// (21,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 34),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]);
}
}
[Fact]
public void GlobalCode_IfStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
if (H.TakeOutParam(1, out var x1))
{
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_IfStatement_04()
{
string source =
@"
System.Console.WriteLine(x1);
if (H.TakeOutParam(1, out var x1))
H.Dummy(H.TakeOutParam(""11"", out var x1), x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static void Dummy(object x, object y)
{
System.Console.WriteLine(y);
}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_YieldReturnStatement_01()
{
string source =
@"
yield return H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
yield return H.TakeOutParam(2, out int x2);
yield return H.TakeOutParam(3, out int x3);
object x3;
yield return H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,40): error CS0102: The type 'Script' already contains a definition for 'x2'
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,49): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49),
// (2,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1),
// (6,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1),
// (8,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1),
// (11,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type
// yield return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out int x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1),
// (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope
// yield return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_YieldReturnStatement_02()
{
string source =
@"
yield return H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
yield return H.TakeOutParam(2, out var x2);
yield return H.TakeOutParam(3, out var x3);
object x3;
yield return H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,40): error CS0102: The type 'Script' already contains a definition for 'x2'
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,49): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49),
// (2,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1),
// (6,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1),
// (8,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1),
// (11,1): error CS7020: Cannot use 'yield' in top-level script code
// yield return H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type
// yield return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out var x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1),
// (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope
// yield return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_01()
{
string source =
@"
return H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
return H.TakeOutParam(2, out int x2);
return H.TakeOutParam(3, out int x3);
object x3;
return H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,34): error CS0102: The type 'Script' already contains a definition for 'x2'
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,43): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out int x1)").WithArguments("bool", "int").WithLocation(2, 8),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out int x2)").WithArguments("bool", "int").WithLocation(6, 8),
// (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope
// return H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out int x3)").WithArguments("bool", "int").WithLocation(8, 8),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))").WithArguments("bool", "int").WithLocation(11, 8),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (14,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_02()
{
string source =
@"
return H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
return H.TakeOutParam(2, out var x2);
return H.TakeOutParam(3, out var x3);
object x3;
return H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,34): error CS0102: The type 'Script' already contains a definition for 'x2'
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,43): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out var x1)").WithArguments("bool", "int").WithLocation(2, 8),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out var x2)").WithArguments("bool", "int").WithLocation(6, 8),
// (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope
// return H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out var x3)").WithArguments("bool", "int").WithLocation(8, 8),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// return H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))").WithArguments("bool", "int").WithLocation(11, 8),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (14,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ReturnStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
Test();
return H.Dummy(H.TakeOutParam(1, out var x1), x1);
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool Dummy(object x, object y)
{
System.Console.WriteLine(y);
return true;
}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_ThrowStatement_01()
{
string source =
@"
throw H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
throw H.TakeOutParam(2, out int x2);
throw H.TakeOutParam(3, out int x3);
object x3;
throw H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static System.Exception Dummy(params object[] x) {return null;}
public static System.Exception TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// throw H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// throw H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_ThrowStatement_02()
{
string source =
@"
throw H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
throw H.TakeOutParam(2, out var x2);
throw H.TakeOutParam(3, out var x3);
object x3;
throw H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static System.Exception Dummy(params object[] x) {return null;}
public static System.Exception TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// throw H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString());
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,1): warning CS0162: Unreachable code detected
// H.Dummy(x1);
Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1),
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// throw H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_01()
{
string source =
@"
switch (H.TakeOutParam(1, out int x1)) {default: break;}
H.Dummy(x1);
object x2;
switch (H.TakeOutParam(2, out int x2)) {default: break;}
switch (H.TakeOutParam(3, out int x3)) {default: break;}
object x3;
switch (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {default: break;}
switch (H.TakeOutParam(51, out int x5))
{
default:
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
break;
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,35): error CS0102: The type 'Script' already contains a definition for 'x2'
// switch (H.TakeOutParam(2, out int x2)) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,44): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44),
// (25,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17),
// (25,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21),
// (25,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope
// switch (H.TakeOutParam(2, out int x2)) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44),
// (17,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 37),
// (28,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_02()
{
string source =
@"
switch (H.TakeOutParam(1, out var x1)) {default: break;}
H.Dummy(x1);
object x2;
switch (H.TakeOutParam(2, out var x2)) {default: break;}
switch (H.TakeOutParam(3, out var x3)) {default: break;}
object x3;
switch (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {default: break;}
switch (H.TakeOutParam(51, out var x5))
{
default:
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
break;
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,35): error CS0102: The type 'Script' already contains a definition for 'x2'
// switch (H.TakeOutParam(2, out var x2)) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,44): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {default: break;}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44),
// (25,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17),
// (25,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21),
// (25,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope
// switch (H.TakeOutParam(2, out var x2)) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {default: break;}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44),
// (17,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 34),
// (28,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_SwitchStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
switch (H.TakeOutParam(1, out var x1))
{
default:
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
break;
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_WhileStatement_01()
{
string source =
@"
while (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
while (H.TakeOutParam(2, out int x2)) {}
while (H.TakeOutParam(3, out int x3)) {}
object x3;
while (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
while (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(3, out int x3)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_WhileStatement_02()
{
string source =
@"
while (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
while (H.TakeOutParam(2, out var x2)) {}
while (H.TakeOutParam(3, out var x3)) {}
object x3;
while (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
while (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34),
// (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// while (H.TakeOutParam(3, out var x3)) {}
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34),
// (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (19,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_WhileStatement_03()
{
string source =
@"
while (H.TakeOutParam(1, out var x1))
{
System.Console.WriteLine(x1);
break;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void GlobalCode_DoStatement_01()
{
string source =
@"
do {} while (H.TakeOutParam(1, out int x1));
H.Dummy(x1);
object x2;
do {} while (H.TakeOutParam(2, out int x2));
do {} while (H.TakeOutParam(3, out int x3));
object x3;
do {} while (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4)));
do
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
while (H.TakeOutParam(51, out int x5));
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(2, out int x2));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40),
// (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(3, out int x3));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (22,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_DoStatement_02()
{
string source =
@"
do {} while (H.TakeOutParam(1, out var x1));
H.Dummy(x1);
object x2;
do {} while (H.TakeOutParam(2, out var x2));
do {} while (H.TakeOutParam(3, out var x3));
object x3;
do {} while (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4)));
do
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
while (H.TakeOutParam(51, out var x5));
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9),
// (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(2, out var x2));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40),
// (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// do {} while (H.TakeOutParam(3, out var x3));
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40),
// (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4)));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (20,9): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9),
// (22,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6),
// (24,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13),
// (24,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25),
// (24,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]);
VerifyModelForOutVar(model, x5Decl[1]);
VerifyNotInScope(model, x5Ref[1]);
VerifyNotInScope(model, x5Ref[2]);
}
}
[Fact]
public void GlobalCode_DoStatement_03()
{
string source =
@"
int f = 1;
do
{
}
while (H.TakeOutParam(f++, out var x1) && Test(x1) < 3);
int Test(int x)
{
System.Console.WriteLine(x);
return x;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"1
2
3").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Decl.Length);
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl[0], x1Ref);
}
[Fact]
public void GlobalCode_LockStatement_01()
{
string source =
@"
lock (H.TakeOutParam(1, out int x1)) {}
H.Dummy(x1);
object x2;
lock (H.TakeOutParam(2, out int x2)) {}
lock (H.TakeOutParam(3, out int x3)) {}
object x3;
lock (H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4))) {}
lock (H.TakeOutParam(51, out int x5))
{
H.TakeOutParam(""52"", out string x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static object Dummy(params object[] x) {return true;}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// lock (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// lock (H.TakeOutParam(2, out int x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42),
// (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out string x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_LockStatement_02()
{
string source =
@"
lock (H.TakeOutParam(1, out var x1)) {}
H.Dummy(x1);
object x2;
lock (H.TakeOutParam(2, out var x2)) {}
lock (H.TakeOutParam(3, out var x3)) {}
object x3;
lock (H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4))) {}
lock (H.TakeOutParam(51, out var x5))
{
H.TakeOutParam(""52"", out var x5);
H.Dummy(x5);
}
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static object Dummy(params object[] x) {return true;}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,33): error CS0102: The type 'Script' already contains a definition for 'x2'
// lock (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,42): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope
// lock (H.TakeOutParam(2, out var x2)) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4))) {}
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42),
// (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// H.TakeOutParam("52", out var x5);
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Decl.Length);
Assert.Equal(3, x5Ref.Length);
VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]);
VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]);
}
}
[Fact]
public void GlobalCode_LockStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
lock (H.TakeOutParam(1, out var x1))
{
H.TakeOutParam(""11"", out var x1);
System.Console.WriteLine(x1);
}
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
public void GlobalCode_LockStatement_04()
{
string source =
@"
System.Console.WriteLine(x1);
lock (H.TakeOutParam(1, out var x1))
H.Dummy(H.TakeOutParam(""11"", out var x1), x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static void Dummy(object x, object y)
{
System.Console.WriteLine(y);
}
public static object TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
11
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Decl.Length);
Assert.Equal(3, x1Ref.Length);
VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]);
VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_DeconstructionDeclarationStatement_01()
{
string source =
@"
(bool a, int b) = (H.TakeOutParam(1, out int x1), 1);
H.Dummy(x1);
object x2;
(bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
(bool e, int f) = (H.TakeOutParam(3, out int x3), 3);
object x3;
(bool g, bool h) = (H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
(bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
H.TakeOutParam(6, out int x6));
Test();
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref[0]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref[0]);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (16,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(16, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref[0]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_01()
{
string source =
@"
a: H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
b: H.TakeOutParam(2, out int x2);
c: H.TakeOutParam(3, out int x3);
object x3;
d: H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,30): error CS0102: The type 'Script' already contains a definition for 'x2'
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,39): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39),
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope
// b: H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_02()
{
string source =
@"
a: H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
b: H.TakeOutParam(2, out var x2);
c: H.TakeOutParam(3, out var x3);
object x3;
d: H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
void Test()
{
H.Dummy(x1, x2, x3, x4);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,30): error CS0102: The type 'Script' already contains a definition for 'x2'
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,39): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39),
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (16,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17),
// (16,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21),
// (16,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a: H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1),
// (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope
// b: H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30),
// (8,1): warning CS0164: This label has not been referenced
// c: H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (11,1): warning CS0164: This label has not been referenced
// d: H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1),
// (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39),
// (19,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_03()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_LabeledStatement_04()
{
string source =
@"
a:
bool b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
c:
bool d = H.TakeOutParam(2, out int x2);
e:
bool f = H.TakeOutParam(3, out int x3);
object x3;
g:
bool h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
i:
bool x5 = H.TakeOutParam(5, out int x5);
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutField(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// bool x5 = H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
VerifyNotAnOutLocal(model, x5Ref[1]);
}
}
[Fact]
public void GlobalCode_LabeledStatement_05()
{
string source =
@"
a:
bool b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
c:
bool d = H.TakeOutParam(2, out var x2);
e:
bool f = H.TakeOutParam(3, out var x3);
object x3;
g:
bool h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
i:
bool x5 = H.TakeOutParam(5, out var x5);
H.Dummy(x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutField(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (2,1): warning CS0164: This label has not been referenced
// a:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1),
// (6,1): warning CS0164: This label has not been referenced
// c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1),
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (8,1): warning CS0164: This label has not been referenced
// e:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (11,1): warning CS0164: This label has not been referenced
// g:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (14,1): warning CS0164: This label has not been referenced
// i:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1),
// (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// bool x5 = H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(2, x5Ref.Length);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref[0]);
VerifyNotAnOutLocal(model, x5Ref[1]);
}
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
public void GlobalCode_LabeledStatement_06_Script()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_LabeledStatement_06_SimpleProgram()
{
string source =
@"
a:b:c:
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(compilation, expectedOutput:
@"1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutVar(model, x1Decl, x1Ref);
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_07()
{
string source =
@"l1:
(bool a, int b) = (H.TakeOutParam(1, out int x1), 1);
H.Dummy(x1);
object x2;
l2:
(bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
l3:
(bool e, int f) = (H.TakeOutParam(3, out int x3), 3);
object x3;
l4:
(bool g, bool h) = (H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
l5:
(bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
H.TakeOutParam(6, out int x6));
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out int x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out int x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out int x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (22,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref);
}
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_08()
{
string source =
@"l1:
(bool a, int b) = (H.TakeOutParam(1, out var x1), 1);
H.Dummy(x1);
object x2;
l2:
(bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
l3:
(bool e, int f) = (H.TakeOutParam(3, out var x3), 3);
object x3;
l4:
(bool g, bool h) = (H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
l5:
(bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
H.TakeOutParam(6, out var x6));
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (6,46): error CS0102: The type 'Script' already contains a definition for 'x2'
// (bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46),
// (9,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8),
// (12,48): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48),
// (14,49): error CS0102: The type 'Script' already contains a definition for 'x5'
// (bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49),
// (15,49): error CS0102: The type 'Script' already contains a definition for 'x6'
// H.TakeOutParam(6, out var x6));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49),
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (19,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17),
// (19,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21),
// (19,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25),
// (19,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29),
// (19,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").ToArray();
Assert.Equal(1, x5Ref.Length);
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(1, x6Ref.Length);
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (1,1): warning CS0164: This label has not been referenced
// l1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1),
// (5,1): warning CS0164: This label has not been referenced
// l2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1),
// (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// (bool c, int d) = (H.TakeOutParam(2, out var x2), 2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46),
// (7,1): warning CS0164: This label has not been referenced
// l3:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1),
// (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8),
// (9,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8),
// (10,1): warning CS0164: This label has not been referenced
// l4:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1),
// (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48),
// (13,1): warning CS0164: This label has not been referenced
// l5:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1),
// (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope
// (bool x5, bool x6) = (H.TakeOutParam(5, out var x5),
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49),
// (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope
// H.TakeOutParam(6, out var x6));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49),
// (22,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl);
VerifyNotAnOutLocal(model, x6Ref);
}
}
[Fact]
[CompilerTrait(CompilerFeature.Tuples)]
public void GlobalCode_LabeledStatement_09()
{
string source =
@"
System.Console.WriteLine(x1);
a:b:c:
var (d, e) = (H.TakeOutParam(1, out var x1), 1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics(
// (3,1): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1),
// (3,3): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3),
// (3,5): warning CS0164: This label has not been referenced
// a:b:c:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_01()
{
string source =
@"
bool b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
bool d = H.TakeOutParam(2, out int x2);
bool f = H.TakeOutParam(3, out int x3);
object x3;
bool h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
bool x5 =
H.TakeOutParam(5, out int x5);
bool i = H.TakeOutParam(5, out int x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope
// x6;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10),
// (19,10): warning CS0168: The variable 'x6' is declared but never used
// x6;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
}
}
[Fact]
public void GlobalCode_FieldDeclaration_02()
{
string source =
@"
bool b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
bool d = H.TakeOutParam(2, out var x2);
bool f = H.TakeOutParam(3, out var x3);
object x3;
bool h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
bool x5 =
H.TakeOutParam(5, out var x5);
bool i = H.TakeOutParam(5, out var x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,36): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,45): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// bool d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36),
// (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope
// object x3;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8),
// (10,8): warning CS0168: The variable 'x3' is declared but never used
// object x3;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8),
// (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45),
// (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37),
// (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope
// x6;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10),
// (19,10): warning CS0168: The variable 'x6' is declared but never used
// x6;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10),
// (26,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0], x4Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl);
VerifyNotAnOutLocal(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl, x6Ref);
}
}
[Fact]
public void GlobalCode_FieldDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
var d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static var b = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_05()
{
string source =
@"
bool b = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_06()
{
string source =
@"
bool b = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_FieldDeclaration_07()
{
string source =
@"
Test();
bool a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2);
Test();
bool Test()
{
System.Console.WriteLine(""{0} {1}"", x1, x2);
return false;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0 0
1 0
1 2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_01()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
bool d { get; } = H.TakeOutParam(2, out int x2);
bool f { get; } = H.TakeOutParam(3, out int x3);
object x3;
bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
bool x5 { get; } =
H.TakeOutParam(5, out int x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,45): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d { get; } = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,54): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25),
// (20,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool b { get; } = H.TakeOutParam(1, out int x1);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool d { get; } = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6),
// (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool f { get; } = H.TakeOutParam(3, out int x3);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6),
// (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4),
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6),
// (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54),
// (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool x5 { get; } =
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6),
// (20,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13),
// (20,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25),
// (20,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1),
// (23,1): error CS0165: Use of unassigned local variable 'x3'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
}
}
[Fact]
public void GlobalCode_PropertyDeclaration_02()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
bool d { get; } = H.TakeOutParam(2, out var x2);
bool f { get; } = H.TakeOutParam(3, out var x3);
object x3;
bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
bool x5 { get; } =
H.TakeOutParam(5, out var x5);
void Test()
{
H.Dummy(x1, x2, x3, x4, x5);
}
Test();
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,45): error CS0102: The type 'Script' already contains a definition for 'x2'
// bool d { get; } = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,54): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (20,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17),
// (20,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21),
// (20,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25),
// (20,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool b { get; } = H.TakeOutParam(1, out var x1);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool d { get; } = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6),
// (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool f { get; } = H.TakeOutParam(3, out var x3);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6),
// (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4),
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6),
// (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54),
// (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods
// bool x5 { get; } =
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6),
// (20,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13),
// (20,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25),
// (20,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29),
// (23,1): error CS0165: Use of unassigned local variable 'x2'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1),
// (23,1): error CS0165: Use of unassigned local variable 'x3'
// Test();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
}
}
[Fact]
public void GlobalCode_PropertyDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
bool d { get; set; } = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static bool b { get; } = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_05()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_PropertyDeclaration_06()
{
string source =
@"
bool b { get; } = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_01()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out int x1);
H.Dummy(x1);
object x2;
event System.Action d = H.TakeOutParam(2, out int x2);
event System.Action f = H.TakeOutParam(3, out int x3);
object x3;
event System.Action h = H.Dummy(H.TakeOutParam(41, out int x4),
H.TakeOutParam(42, out int x4));
event System.Action x5 =
H.TakeOutParam(5, out int x5);
event System.Action i = H.TakeOutParam(5, out int x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,51): error CS0102: The type 'Script' already contains a definition for 'x2'
// event System.Action d = H.TakeOutParam(2, out int x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,52): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out int x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected };
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out int x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29),
// (23,33): error CS0103: The name 'x6' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
}
[Fact]
public void GlobalCode_EventDeclaration_02()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out var x1);
H.Dummy(x1);
object x2;
event System.Action d = H.TakeOutParam(2, out var x2);
event System.Action f = H.TakeOutParam(3, out var x3);
object x3;
event System.Action h = H.Dummy(H.TakeOutParam(41, out var x4),
H.TakeOutParam(42, out var x4));
event System.Action x5 =
H.TakeOutParam(5, out var x5);
event System.Action i = H.TakeOutParam(5, out var x6),
x6;
void Test()
{
H.Dummy(x1, x2, x3, x4, x5, x6);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (7,51): error CS0102: The type 'Script' already contains a definition for 'x2'
// event System.Action d = H.TakeOutParam(2, out var x2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51),
// (10,8): error CS0102: The type 'Script' already contains a definition for 'x3'
// object x3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8),
// (13,52): error CS0102: The type 'Script' already contains a definition for 'x4'
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52),
// (16,37): error CS0102: The type 'Script' already contains a definition for 'x5'
// H.TakeOutParam(5, out var x5);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37),
// (19,10): error CS0102: The type 'Script' already contains a definition for 'x6'
// x6;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10),
// (23,17): error CS0229: Ambiguity between 'x2' and 'x2'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17),
// (23,21): error CS0229: Ambiguity between 'x3' and 'x3'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21),
// (23,25): error CS0229: Ambiguity between 'x4' and 'x4'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25),
// (23,29): error CS0229: Ambiguity between 'x5' and 'x5'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29),
// (23,33): error CS0229: Ambiguity between 'x6' and 'x6'
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref);
VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected };
compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify(
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope
// H.TakeOutParam(42, out var x4));
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52),
// (21,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6),
// (23,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13),
// (23,25): error CS0103: The name 'x4' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25),
// (23,29): error CS0103: The name 'x5' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29),
// (23,33): error CS0103: The name 'x6' does not exist in the current context
// H.Dummy(x1, x2, x3, x4, x5, x6);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVar(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVar(model, x2Decl);
VerifyNotAnOutLocal(model, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").Single();
VerifyModelForOutVar(model, x3Decl);
VerifyNotAnOutLocal(model, x3Ref);
var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray();
var x4Ref = GetReferences(tree, "x4").Single();
Assert.Equal(2, x4Decl.Length);
VerifyModelForOutVar(model, x4Decl[0]);
VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]);
VerifyNotInScope(model, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").Single();
var x5Ref = GetReferences(tree, "x5").Single();
VerifyModelForOutVar(model, x5Decl);
VerifyNotInScope(model, x5Ref);
var x6Decl = GetOutVarDeclarations(tree, "x6").Single();
var x6Ref = GetReferences(tree, "x6").Single();
VerifyModelForOutVar(model, x6Decl);
VerifyNotInScope(model, x6Ref);
}
}
[Fact]
public void GlobalCode_EventDeclaration_03()
{
string source =
@"
System.Console.WriteLine(x1);
event System.Action d = H.TakeOutParam(1, out var x1);
Test();
void Test()
{
System.Console.WriteLine(x1);
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_04()
{
string source =
@"
static var a = InitA();
System.Console.WriteLine(x1);
static event System.Action b = H.TakeOutParam(1, out var x1);
Test();
static var c = InitB();
void Test()
{
System.Console.WriteLine(x1);
}
static object InitA()
{
System.Console.WriteLine(""InitA {0}"", x1);
return null;
}
static object InitB()
{
System.Console.WriteLine(""InitB {0}"", x1);
return null;
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"InitA 0
InitB 1
1
1").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(4, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_05()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out var x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_06()
{
string source =
@"
event System.Action b = H.TakeOutParam(1, out int x1);
static var d = x1;
static void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// static var d = x1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16),
// (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_EventDeclaration_07()
{
string source =
@"
Test();
event System.Action a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2);
Test();
System.Action Test()
{
System.Console.WriteLine(""{0} {1}"", x1, x2);
return null;
}
class H
{
public static System.Action TakeOutParam<T>(T y, out T x)
{
x = y;
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
CompileAndVerify(compilation, expectedOutput:
@"0 0
1 0
1 2").VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl, x2Ref);
}
[Fact]
public void GlobalCode_DeclaratorArguments_01()
{
string source =
@"
bool a, b(out var x1);
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,21): error CS1003: Syntax error, ']' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21),
// (3,19): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(3, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,21): error CS1003: Syntax error, ']' expected
// bool a, b(out var x1);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21),
// (3,6): warning CS0168: The variable 'a' is declared but never used
// bool a, b(out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6),
// (3,9): warning CS0168: The variable 'b' is declared but never used
// bool a, b(out var x1);
Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_02()
{
string source =
@"
label:
bool a, b(H.TakeOutParam(1, out var x1));
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,40): error CS1003: Syntax error, ']' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40),
// (2,1): warning CS0164: This label has not been referenced
// label:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10),
// (3,10): error CS1003: Syntax error, '[' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10),
// (3,40): error CS1003: Syntax error, ']' expected
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40),
// (2,1): warning CS0164: This label has not been referenced
// label:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1),
// (4,9): error CS0165: Use of unassigned local variable 'x1'
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(4, 9),
// (3,6): warning CS0168: The variable 'a' is declared but never used
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6),
// (3,9): warning CS0168: The variable 'b' is declared but never used
// bool a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_03()
{
string source =
@"
event System.Action a, b(H.TakeOutParam(1, out var x1));
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static System.Action Dummy(params object[] x) {return null;}
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25),
// (3,25): error CS1003: Syntax error, '[' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25),
// (3,55): error CS1003: Syntax error, ']' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration)
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25),
// (3,25): error CS1003: Syntax error, '[' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25),
// (3,55): error CS1003: Syntax error, ']' expected
// event System.Action a, b(H.TakeOutParam(1, out var x1));
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6),
// (8,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelNotSupported(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
}
}
[Fact]
public void GlobalCode_DeclaratorArguments_04()
{
string source =
@"
fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
H.Dummy(x1);
void Test()
{
H.Dummy(x1);
}
class H
{
public static bool Dummy(params object[] x) {return true;}
public static int TakeOutParam<T>(T y, out T x)
{
x = y;
return 3;
}
}
";
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"),
parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (3,18): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18),
// (3,20): error CS0133: The expression being assigned to 'b' must be constant
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("b").WithLocation(3, 20),
// (3,12): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12),
// (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelForOutField(model, x1Decl, x1Ref);
}
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (3,12): error CS0116: A namespace cannot directly contain members such as fields or methods
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(3, 12),
// (3,18): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18),
// (3,20): error CS0133: The expression being assigned to '<invalid-global-code>.b' must be constant
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("<invalid-global-code>.b").WithLocation(3, 20),
// (3,12): error CS1642: Fixed size buffer fields may only be members of structs
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12),
// (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// fixed bool a[2], b[H.TakeOutParam(1, out var x1)];
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12),
// (4,9): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9),
// (8,13): error CS0103: The name 'x1' does not exist in the current context
// H.Dummy(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13),
// (6,6): warning CS8321: The local function 'Test' is declared but never used
// void Test()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
AssertContainedInDeclaratorArguments(x1Decl);
VerifyModelNotSupported(model, x1Decl);
VerifyNotInScope(model, x1Ref[0]);
VerifyNotInScope(model, x1Ref[1]);
}
}
[Fact]
public void GlobalCode_RestrictedType_01()
{
string source =
@"
H.TakeOutParam(out var x1);
H.TakeOutParam(out System.ArgIterator x2);
class H
{
public static void TakeOutParam(out System.ArgIterator x)
{
x = default(System.ArgIterator);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (9,37): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// public static void TakeOutParam(out System.ArgIterator x)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 37),
// (5,20): error CS0610: Field or property cannot be of type 'ArgIterator'
// H.TakeOutParam(out System.ArgIterator x2);
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(5, 20),
// (3,20): error CS0610: Field or property cannot be of type 'ArgIterator'
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "var").WithArguments("System.ArgIterator").WithLocation(3, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl);
}
[Fact]
public void GlobalCode_StaticType_01()
{
string source =
@"
H.TakeOutParam(out var x1);
H.TakeOutParam(out StaticType x2);
class H
{
public static void TakeOutParam(out StaticType x)
{
x = default(System.ArgIterator);
}
}
static class StaticType{}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (5,31): error CS0723: Cannot declare a variable of static type 'StaticType'
// H.TakeOutParam(out StaticType x2);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x2").WithArguments("StaticType").WithLocation(5, 31),
// (9,24): error CS0721: 'StaticType': static types cannot be used as parameters
// public static void TakeOutParam(out StaticType x)
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "TakeOutParam").WithArguments("StaticType").WithLocation(9, 24),
// (3,24): error CS0723: Cannot declare a variable of static type 'StaticType'
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x1").WithArguments("StaticType").WithLocation(3, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
VerifyModelForOutField(model, x2Decl);
}
[Fact]
public void GlobalCode_InferenceFailure_01()
{
string source =
@"
H.TakeOutParam(out var x1, x1);
class H
{
public static void TakeOutParam(out int x, long y)
{
x = 1;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.GetDeclarationDiagnostics().Verify(
// (3,24): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.TakeOutParam(out var x1, x1);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact]
public void GlobalCode_InferenceFailure_02()
{
string source =
@"
var a = b;
var b = H.TakeOutParam(out var x1, a);
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single());
Assert.True(b.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = H.TakeOutParam(out var x1, a);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
}
[Fact]
public void GlobalCode_InferenceFailure_03()
{
string source =
@"
var a = H.TakeOutParam(out var x1, b);
var b = a;
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single());
Assert.True(b.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = a;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
}
[Fact]
public void GlobalCode_InferenceFailure_04()
{
string source =
@"
var a = x1;
var b = H.TakeOutParam(out var x1, a);
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var a = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "a").Single());
Assert.True(a.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (3,5): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var a = x1;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(3, 5)
);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclarations(tree, "x1").Single();
x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = H.TakeOutParam(out var x1, a);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(4, 32)
);
}
[Fact]
public void GlobalCode_InferenceFailure_05()
{
string source =
@"
var a = H.TakeOutParam(out var x1, b);
var b = x1;
class H
{
public static int TakeOutParam(out int x, long y)
{
x = 1;
return 123;
}
}
";
// `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation,
// which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field).
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (3,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var a = H.TakeOutParam(out var x1, b);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 32)
);
compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true);
tree = compilation.SyntaxTrees.Single();
model = compilation.GetSemanticModel(tree);
x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var bDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single();
var b = (IFieldSymbol)model.GetDeclaredSymbol(bDecl);
Assert.True(b.Type.IsErrorType());
x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("System.Int32", x1.Type.ToTestDisplayString());
Assert.False(x1.Type.IsErrorType());
compilation.VerifyDiagnostics(
// (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var b = x1;
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5)
);
}
[Fact]
public void GlobalCode_InferenceFailure_06()
{
string source =
@"
H.TakeOutParam(out var x1);
class H
{
public static int TakeOutParam<T>(out T x)
{
x = default(T);
return 123;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24),
// (2,3): error CS0411: The type arguments for method 'H.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("H.TakeOutParam<T>(out T)").WithLocation(2, 3)
);
compilation.GetDeclarationDiagnostics().Verify(
// (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'.
// H.TakeOutParam(out var x1);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
VerifyModelForOutField(model, x1Decl);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/17377")]
public void GlobalCode_InferenceFailure_07()
{
string source =
@"
H.M((var x1, int x2));
H.M(x1);
class H
{
public static void M(object a) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
compilation.VerifyDiagnostics(
// (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10),
// (2,6): error CS8185: A declaration is not allowed in this context.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(2, 6),
// (2,14): error CS8185: A declaration is not allowed in this context.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(2, 14),
// (2,5): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, int x2)").WithArguments("System.ValueTuple`2").WithLocation(2, 5),
// (2,5): error CS1503: Argument 1: cannot convert from '(var, int)' to 'object'
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_BadArgType, "(var x1, int x2)").WithArguments("1", "(var, int)", "object").WithLocation(2, 5)
);
compilation.GetDeclarationDiagnostics().Verify(
// (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// H.M((var x1, int x2));
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(1, x1Ref.Length);
VerifyModelForOutField(model, x1Decl, x1Ref);
var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation());
Assert.Equal("var", x1.Type.ToTestDisplayString());
Assert.True(x1.Type.IsErrorType());
}
[Fact, WorkItem(17321, "https://github.com/dotnet/roslyn/issues/17321")]
public void InferenceFailure_01()
{
string source =
@"
class H
{
object M1() => M(M(1), x1);
static object M(object o1) => o1;
static void M(object o1, object o2) {}
}
";
var node0 = SyntaxFactory.ParseCompilationUnit(source);
var one = node0.DescendantNodes().OfType<LiteralExpressionSyntax>().Single();
var decl = SyntaxFactory.DeclarationExpression(
type: SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("var")),
designation: SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier("x1")));
var node1 = node0.ReplaceNode(one, decl);
var tree = node1.SyntaxTree;
Assert.NotNull(tree);
var compilation = CreateCompilation(new[] { tree });
compilation.VerifyDiagnostics(
// (4,24): error CS8185: A declaration is not allowed in this context.
// object M1() => M(M(varx1), x1);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "varx1").WithLocation(4, 24)
);
var model = compilation.GetSemanticModel(tree);
var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>()
.Where(p => p.Identifier().ValueText == "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref);
}
[Fact]
public void GlobalCode_AliasInfo_01()
{
string source =
@"
H.TakeOutParam(1, out var x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact]
public void GlobalCode_AliasInfo_02()
{
string source =
@"
using var = System.Int32;
H.TakeOutParam(1, out var x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GlobalCode_AliasInfo_03()
{
string source =
@"
using a = System.Int32;
H.TakeOutParam(1, out a x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString());
}
[Fact]
public void GlobalCode_AliasInfo_04()
{
string source =
@"
H.TakeOutParam(1, out int x1);
class H
{
public static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
Assert.Null(model.GetAliasInfo(x1Decl.Type));
}
[Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")]
public void ExpressionVariableInCase_1()
{
string source =
@"
class Program
{
static void Main(string[] args)
{
switch (true)
{
case !TakeOutParam(3, out var x1):
System.Console.WriteLine(x1);
break;
}
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// The point of this test is that it should not crash.
compilation.VerifyDiagnostics(
// (8,18): error CS0150: A constant value is expected
// case !TakeOutParam(3, out var x1):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!TakeOutParam(3, out var x1)").WithLocation(8, 18)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
[Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")]
public void ExpressionVariableInCase_2()
{
string source =
@"
class Program
{
static void Main(string[] args)
{
switch (true)
{
case !TakeOutParam(3, out UndeclaredType x1):
System.Console.WriteLine(x1);
break;
}
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
// The point of this test is that it should not crash.
compilation.VerifyDiagnostics(
// (8,19): error CS0103: The name 'TakeOutParam' does not exist in the current context
// case !TakeOutParam(3, out UndeclaredType x1):
Diagnostic(ErrorCode.ERR_NameNotInContext, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(8, 19),
// (8,39): error CS0246: The type or namespace name 'UndeclaredType' could not be found (are you missing a using directive or an assembly reference?)
// case !TakeOutParam(3, out UndeclaredType x1):
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndeclaredType").WithArguments("UndeclaredType").WithLocation(8, 39)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
}
private static void VerifyModelForOutField(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
VerifyModelForOutField(model, decl, false, references);
}
private static void VerifyModelForOutFieldDuplicate(
SemanticModel model,
DeclarationExpressionSyntax decl,
params IdentifierNameSyntax[] references)
{
VerifyModelForOutField(model, decl, true, references);
}
private static void VerifyModelForOutField(
SemanticModel model,
DeclarationExpressionSyntax decl,
bool duplicate,
params IdentifierNameSyntax[] references)
{
var variableDesignationSyntax = GetVariableDesignation(decl);
var symbol = model.GetDeclaredSymbol(variableDesignationSyntax);
Assert.Equal(decl.Identifier().ValueText, symbol.Name);
Assert.Equal(SymbolKind.Field, symbol.Kind);
Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax));
var symbols = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText);
var names = model.LookupNames(decl.SpanStart);
if (duplicate)
{
Assert.True(symbols.Count() > 1);
Assert.Contains(symbol, symbols);
}
else
{
Assert.Same(symbol, symbols.Single());
}
Assert.Contains(decl.Identifier().ValueText, names);
var local = (IFieldSymbol)symbol;
var declarator = decl.Ancestors().OfType<VariableDeclaratorSyntax>().FirstOrDefault();
var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement &&
(declarator.ArgumentList?.Contains(decl)).GetValueOrDefault();
// We're not able to get type information at such location (out var argument in global code) at this point
// See https://github.com/dotnet/roslyn/issues/13569
AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: inFieldDeclaratorArgumentlist ? null : local.Type);
foreach (var reference in references)
{
var referenceInfo = model.GetSymbolInfo(reference);
symbols = model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText);
if (duplicate)
{
Assert.Null(referenceInfo.Symbol);
Assert.Contains(symbol, referenceInfo.CandidateSymbols);
Assert.True(symbols.Count() > 1);
Assert.Contains(symbol, symbols);
}
else
{
Assert.Same(symbol, referenceInfo.Symbol);
Assert.Same(symbol, symbols.Single());
Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
}
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
}
if (!inFieldDeclaratorArgumentlist)
{
var dataFlowParent = (ExpressionSyntax)decl.Parent.Parent.Parent;
if (model.IsSpeculativeSemanticModel)
{
Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent));
}
else
{
var dataFlow = model.AnalyzeDataFlow(dataFlowParent);
if (dataFlow.Succeeded)
{
Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
Assert.False(dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance));
}
}
}
}
[Fact]
public void MethodTypeArgumentInference_01()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out int a);
TakeOutParam(out long b);
}
static void TakeOutParam<T>(out T x)
{
x = default(T);
System.Console.WriteLine(typeof(T));
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.Int32
System.Int64");
}
[Fact]
public void MethodTypeArgumentInference_02()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var a);
}
static void TakeOutParam<T>(out T x)
{
x = default(T);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out var a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T)").WithLocation(6, 9)
);
}
[Fact]
public void MethodTypeArgumentInference_03()
{
var source =
@"
public class X
{
public static void Main()
{
long a = 0;
TakeOutParam(out int b, a);
int c;
TakeOutParam(out c, a);
}
static void TakeOutParam<T>(out T x, T y)
{
x = default(T);
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out int b, a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(7, 9),
// (9,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// TakeOutParam(out c, a);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(9, 9)
);
}
[Fact]
public void MethodTypeArgumentInference_04()
{
var source =
@"
public class X
{
public static void Main()
{
byte a = 0;
int b = 0;
TakeOutParam(out int c, a);
TakeOutParam(out b, a);
}
static void TakeOutParam<T>(out T x, T y)
{
x = default(T);
System.Console.WriteLine(typeof(T));
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput:
@"System.Int32
System.Int32");
}
[Fact, WorkItem(14825, "https://github.com/dotnet/roslyn/issues/14825")]
public void OutVarDeclaredInReceiverUsedInArgument()
{
var source =
@"using System.Linq;
public class C
{
public string[] Goo2(out string x) { x = """"; return null; }
public string[] Goo3(bool b) { return null; }
public string[] Goo5(string u) { return null; }
public void Test()
{
var t1 = Goo2(out var x1).Concat(Goo5(x1));
var t2 = Goo3(t1 is var x2).Concat(Goo5(x2.First()));
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVar(model, x1Decl, x1Ref);
Assert.Equal("System.String", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString());
}
[Fact]
public void OutVarDiscard()
{
var source =
@"
public class C
{
static void Main()
{
M(out int _);
M(out var _);
M(out _);
}
static void M(out int x) { x = 1; System.Console.Write(""M""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "MMM");
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.Single();
var model = comp.Compilation.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetTypeInfo(discard1).Type);
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("int _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetTypeInfo(discard2).Type);
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
var discard3 = GetDiscardIdentifiers(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard3));
var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol;
Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
comp.VerifyIL("C.Main()", @"
{
// Code size 22 (0x16)
.maxstack 1
.locals init (int V_0)
IL_0000: ldloca.s V_0
IL_0002: call ""void C.M(out int)""
IL_0007: ldloca.s V_0
IL_0009: call ""void C.M(out int)""
IL_000e: ldloca.s V_0
IL_0010: call ""void C.M(out int)""
IL_0015: ret
}
");
}
[Fact]
public void NamedOutVarDiscard()
{
var source =
@"
public class C
{
static void Main()
{
M(y: out string _, x: out int _);
M(y: out var _, x: out var _);
M(y: out _, x: out _);
}
static void M(out int x, out string y) { x = 1; y = ""hello""; System.Console.Write(""M""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "MMM");
comp.VerifyDiagnostics();
}
[Fact]
public void OutVarDiscardInCtor_01()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out int i1);
new C(out int _);
new C(out var _);
new C(out _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CCCC");
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("int _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("int", declaration1.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration2.Type));
var discard3 = GetDiscardIdentifiers(tree).First();
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol;
Assert.Equal("int _", discard3Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
}
[Fact]
public void OutVarDiscardInCtor_02()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out long x1);
new C(out long _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int'
// new C(out long x1);
Diagnostic(ErrorCode.ERR_BadArgType, "long x1").WithArguments("1", "out long", "out int").WithLocation(7, 19),
// (8,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int'
// new C(out long _);
Diagnostic(ErrorCode.ERR_BadArgType, "long _").WithArguments("1", "out long", "out int").WithLocation(8, 19),
// (7,19): error CS0165: Use of unassigned local variable 'x1'
// new C(out long x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "long x1").WithArguments("x1").WithLocation(7, 19)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
VerifyModelForOutVarWithoutDataFlow(model, x1Decl);
var discard1 = GetDiscardDesignations(tree).Single();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("long _", declaration1.ToString());
Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("long", declaration1.Type.ToString());
Assert.Equal("System.Int64", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int64", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int64", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
}
[Fact]
public void OutVarDiscardAliasInfo_01()
{
var source =
@"
using alias1 = System.Int32;
using var = System.Int32;
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out alias1 _);
new C(out var _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CC");
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("alias1 _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("alias1", declaration1.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Equal("alias1=System.Int32", model.GetAliasInfo(declaration1.Type).ToTestDisplayString());
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Equal("var=System.Int32", model.GetAliasInfo(declaration2.Type).ToTestDisplayString());
}
[Fact]
public void OutVarDiscardAliasInfo_02()
{
var source =
@"
enum alias1 : long {}
class var {}
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C""); }
static void Main()
{
new C(out alias1 _);
new C(out var _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (10,19): error CS1503: Argument 1: cannot convert from 'out alias1' to 'out int'
// new C(out alias1 _);
Diagnostic(ErrorCode.ERR_BadArgType, "alias1 _").WithArguments("1", "out alias1", "out int").WithLocation(10, 19),
// (11,19): error CS1503: Argument 1: cannot convert from 'out var' to 'out int'
// new C(out var _);
Diagnostic(ErrorCode.ERR_BadArgType, "var _").WithArguments("1", "out var", "out int").WithLocation(11, 19)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).ElementAt(0);
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("alias1 _", declaration1.ToString());
Assert.Equal("alias1", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
Assert.Equal("alias1", declaration1.Type.ToString());
Assert.Equal("alias1", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString());
TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type);
Assert.Equal("alias1", typeInfo.Type.ToTestDisplayString());
Assert.Equal("alias1", typeInfo.ConvertedType.ToTestDisplayString());
Assert.True(model.GetConversion(declaration1.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration1.Type));
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("var", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, model.GetTypeInfo(declaration2).Type.TypeKind);
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
Assert.Equal("var", declaration2.Type.ToString());
Assert.Equal("var", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration2.Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration2.Type).IsIdentity);
Assert.Null(model.GetAliasInfo(declaration2.Type));
}
[Fact]
public void OutVarDiscardInCtorInitializer()
{
var source =
@"
public class C
{
public C(out int i) { i = 1; System.Console.Write(""C ""); }
static void Main()
{
new Derived2(out int i2);
new Derived3(out int i3);
new Derived4();
}
}
public class Derived2 : C
{
public Derived2(out int i) : base(out int _) { i = 2; System.Console.Write(""Derived2 ""); }
}
public class Derived3 : C
{
public Derived3(out int i) : base(out var _) { i = 3; System.Console.Write(""Derived3 ""); }
}
public class Derived4 : C
{
public Derived4(out int i) : base(out _) { i = 4; }
public Derived4() : this(out _) { System.Console.Write(""Derived4""); }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C Derived2 C Derived3 C Derived4");
}
[Fact]
public void DiscardNotRecognizedInOtherScenarios()
{
var source =
@"
public class C
{
void M<T>()
{
_.ToString();
M(_);
_<T>.ToString();
(_<T>, _<T>) = (1, 2);
M<_>();
new C() { _ = 1 };
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (6,9): error CS0103: The name '_' does not exist in the current context
// _.ToString();
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 9),
// (7,11): error CS0103: The name '_' does not exist in the current context
// M(_);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 11),
// (8,9): error CS0103: The name '_' does not exist in the current context
// _<T>.ToString();
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(8, 9),
// (9,10): error CS0103: The name '_' does not exist in the current context
// (_<T>, _<T>) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 10),
// (9,16): error CS0103: The name '_' does not exist in the current context
// (_<T>, _<T>) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 16),
// (10,11): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?)
// M<_>();
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(10, 11),
// (11,19): error CS0117: 'C' does not contain a definition for '_'
// new C() { _ = 1 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "_").WithArguments("C", "_").WithLocation(11, 19)
);
}
[Fact]
public void TypedDiscardInMethodTypeInference()
{
var source =
@"
public class C
{
static void M<T>(out T t)
{
t = default(T);
System.Console.Write(t.GetType().ToString());
}
static void Main()
{
M(out int _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "System.Int32");
}
[Fact]
public void UntypedDiscardInMethodTypeInference()
{
var source =
@"
public class C
{
static void M<T>(out T t)
{
t = default(T);
}
static void Main()
{
M(out var _);
M(out _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (10,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(out var _);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(10, 9),
// (11,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// M(out _);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(11, 9)
);
}
[Fact]
public void PickOverloadWithTypedDiscard()
{
var source =
@"
public class C
{
static void M(out object x) { x = 1; System.Console.Write(""object returning M. ""); }
static void M(out int x) { x = 2; System.Console.Write(""int returning M.""); }
static void Main()
{
M(out object _);
M(out int _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "object returning M. int returning M.");
}
[Fact]
public void CannotPickOverloadWithUntypedDiscard()
{
var source =
@"
public class C
{
static void M(out object x) { x = 1; }
static void M(out int x) { x = 2; }
static void Main()
{
M(out var _);
M(out _);
M(out byte _);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)'
// M(out var _);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(8, 9),
// (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)'
// M(out _);
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(9, 9),
// (10,15): error CS1503: Argument 1: cannot convert from 'out byte' to 'out object'
// M(out byte _);
Diagnostic(ErrorCode.ERR_BadArgType, "byte _").WithArguments("1", "out byte", "out object").WithLocation(10, 15)
);
}
[Fact]
public void NoOverloadWithDiscard()
{
var source =
@"
public class A { }
public class B : A
{
static void M(A a)
{
a.M2(out A x);
a.M2(out A _);
}
}
public static class S
{
public static void M2(this A self, out B x) { x = null; }
}";
var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll, references: new[] { Net40.SystemCore });
comp.VerifyDiagnostics(
// (7,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B'
// a.M2(out A x);
Diagnostic(ErrorCode.ERR_BadArgType, "A x").WithArguments("2", "out A", "out B").WithLocation(7, 18),
// (8,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B'
// a.M2(out A _);
Diagnostic(ErrorCode.ERR_BadArgType, "A _").WithArguments("2", "out A", "out B").WithLocation(8, 18)
);
}
[Fact]
[WorkItem(363727, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/363727")]
public void FindCorrectBinderOnEmbeddedStatementWithMissingIdentifier()
{
var source =
@"
public class C
{
static void M(string x)
{
if(true)
&& int.TryParse(x, out int y)) id(iVal);
// Note that the embedded statement is parsed as a missing identifier, followed by && with many spaces attached as leading trivia
}
}";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "x").Single();
Assert.Equal("x", x.ToString());
Assert.Equal("System.String x", model.GetSymbolInfo(x).Symbol.ToTestDisplayString());
}
[Fact]
public void DuplicateDeclarationInSwitchBlock()
{
var text = @"
public class C
{
public static void Main(string[] args)
{
switch (args.Length)
{
case 0:
M(M(out var x1), x1);
M(M(out int x1), x1);
break;
case 1:
M(M(out int x1), x1);
break;
}
}
static int M(out int z) => z = 1;
static int M(int a, int b) => a+b;
}";
var comp = CreateCompilationWithMscorlib45(text);
comp.VerifyDiagnostics(
// (10,29): error CS0128: A local variable or function named 'x1' is already defined in this scope
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(10, 29),
// (13,29): error CS0128: A local variable or function named 'x1' is already defined in this scope
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 29),
// (13,34): error CS0165: Use of unassigned local variable 'x1'
// M(M(out int x1), x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 34)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var x6Decl = GetOutVarDeclarations(tree, "x1").ToArray();
var x6Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(3, x6Decl.Length);
Assert.Equal(3, x6Ref.Length);
VerifyModelForOutVar(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[2]);
}
[Fact]
public void DeclarationInLocalFunctionParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
int x = z1 + z2;
}
static int M(out int z) => z = 1;
static bool M(int a, int b) => a+b == 0;
}
";
// 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,75): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 75),
// (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z1), z1)").WithArguments("b").WithLocation(6, 30),
// (6,61): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61),
// (7,75): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 75),
// (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z2), z2)").WithArguments("b").WithLocation(7, 30),
// (7,61): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61),
// (9,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17),
// (9,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22),
// (6,14): warning CS8321: The local function 'Local2' is declared but never used
// void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14),
// (7,14): warning CS8321: The local function 'Local5' is declared but never used
// void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInAnonymousMethodParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
System.Action<bool, int> d1 = delegate (
bool b = M(M(out int z1), z1),
int s2 = z1)
{ var t = z1; };
System.Action<bool, int> d2 = delegate (
bool b = M(M(out var z2), z2),
int s2 = z2)
{ var t = z2; };
int x = z1 + z2;
d1 = d2 = null;
}
static int M(out int z) => z = 1;
static int M(int a, int b) => a+b;
}
";
// the scope of an expression variable introduced in the default expression
// of a lambda parameter is that default expression.
var compilation = CreateCompilationWithMscorlib45(text);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_DefaultValueNotAllowed).Verify(
// (9,55): error CS0103: The name 'z1' does not exist in the current context
// { var t = z1; };
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 55),
// (13,55): error CS0103: The name 'z2' does not exist in the current context
// { var t = z2; };
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(13, 55),
// (15,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(15, 17),
// (15,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(15, 22)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var z1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "z1").First();
Assert.Equal("System.Int32", model.GetTypeInfo(z1).Type.ToTestDisplayString());
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void Scope_LocalFunction_Attribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(p = TakeOutParam(out int x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out int x4))]
[Test(p = TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out int x6) && x6 > 0,
p2 = TakeOutParam(out int x6) && x6 > 0)]
[Test(p = TakeOutParam(out int x7) && x7 > 0)]
[Test(p = x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,23): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23),
// (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48),
// (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45),
// (15,23): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_02()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(TakeOutParam(out int x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out int x4))]
[Test(TakeOutParam(51, out int x5) &&
TakeOutParam(52, out int x5) &&
x5 > 0)]
[Test(TakeOutParam(out int x6) && x6 > 0,
TakeOutParam(out int x6) && x6 > 0)]
[Test(TakeOutParam(out int x7) && x7 > 0)]
[Test(x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,19): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out int x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19),
// (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out int x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44),
// (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out int x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40),
// (15,19): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_03()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(p = TakeOutParam(out var x3) && x3 > 0)]
[Test(p = x4 && TakeOutParam(out var x4))]
[Test(p = TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(p1 = TakeOutParam(out var x6) && x6 > 0,
p2 = TakeOutParam(out var x6) && x6 > 0)]
[Test(p = TakeOutParam(out var x7) && x7 > 0)]
[Test(p = x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
public bool p1 {get; set;}
public bool p2 {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,23): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(p = x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23),
// (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48),
// (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope
// p2 = TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45),
// (15,23): error CS0103: The name 'x7' does not exist in the current context
// [Test(p = x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_04()
{
var source =
@"
public class X
{
public static void Main()
{
void Local1(
[Test(TakeOutParam(out var x3) && x3 > 0)]
[Test(x4 && TakeOutParam(out var x4))]
[Test(TakeOutParam(51, out var x5) &&
TakeOutParam(52, out var x5) &&
x5 > 0)]
[Test(TakeOutParam(out var x6) && x6 > 0,
TakeOutParam(out var x6) && x6 > 0)]
[Test(TakeOutParam(out var x7) && x7 > 0)]
[Test(x7 > 2)]
int p1)
{
Dummy(x7, p1);
}
Local1(1);
}
bool Dummy(params object[] x) {return true;}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
static bool TakeOutParam(object y, out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
public Test(bool p1, bool p2) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (18,19): error CS0103: The name 'x7' does not exist in the current context
// Dummy(x7, p1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19),
// (8,19): error CS0841: Cannot use local variable 'x4' before it is declared
// [Test(x4 && TakeOutParam(out var x4))]
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19),
// (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope
// TakeOutParam(52, out var x5) &&
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44),
// (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope
// TakeOutParam(out var x6) && x6 > 0)]
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40),
// (15,19): error CS0103: The name 'x7' does not exist in the current context
// [Test(x7 > 2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x3Decl = GetOutVarDeclaration(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref);
var x4Decl = GetOutVarDeclaration(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref);
var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray();
var x5Ref = GetReference(tree, "x5");
Assert.Equal(2, x5Decl.Length);
VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]);
var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray();
var x6Ref = GetReferences(tree, "x6").ToArray();
Assert.Equal(2, x6Decl.Length);
Assert.Equal(2, x6Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]);
var x7Decl = GetOutVarDeclaration(tree, "x7");
var x7Ref = GetReferences(tree, "x7").ToArray();
Assert.Equal(3, x7Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]);
VerifyNotInScope(model, x7Ref[1]);
VerifyNotInScope(model, x7Ref[2]);
}
[Fact]
public void Scope_LocalFunction_Attribute_05()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var x1);
TakeOutParam(out var x2);
void Local1(
[Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
int p1)
{
p1 = 0;
}
Local1(x2);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public bool p {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (10,44): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 44)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]);
}
[Fact]
public void Scope_LocalFunction_Attribute_06()
{
var source =
@"
public class X
{
public static void Main()
{
TakeOutParam(out var x1);
TakeOutParam(out var x2);
void Local1(
[Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
int p1)
{
p1 = 0;
}
Local1(x2);
}
static bool TakeOutParam(out int x)
{
x = 123;
return true;
}
}
class Test : System.Attribute
{
public Test(bool p) {}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify(
// (10,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)]
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 40)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclaration(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Decl.Length);
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]);
}
[Fact]
public void Scope_InvalidArrayDimensions01()
{
var text = @"
public class Cls
{
public static void Main()
{
int x1 = 0;
int[Test1(out int x1), x1] _1;
int[Test1(out int x2), x2] x2;
}
static int Test1(out int x)
{
x = 1;
return 1;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (7,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x1), x1]").WithLocation(7, 12),
// (7,27): error CS0128: A local variable or function named 'x1' is already defined in this scope
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 27),
// (8,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x2), x2]").WithLocation(8, 12),
// (8,36): error CS0128: A local variable or function named 'x2' is already defined in this scope
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(8, 36),
// (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used
// int x1 = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13),
// (7,27): warning CS0168: The variable 'x1' is declared but never used
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(7, 27),
// (7,36): warning CS0168: The variable '_1' is declared but never used
// int[Test1(out int x1), x1] _1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "_1").WithArguments("_1").WithLocation(7, 36),
// (8,27): warning CS0168: The variable 'x2' is declared but never used
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 27),
// (8,36): warning CS0168: The variable 'x2' is declared but never used
// int[Test1(out int x2), x2] x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 36)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").Single();
VerifyNotAnOutLocal(model, x1Ref);
VerifyModelForOutVarDuplicateInSameScope(model, x1Decl);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").Single();
VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref);
}
[Fact]
public void Scope_InvalidArrayDimensions_02()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
void Test1()
{
using (int[] d = null)
{
Dummy(x1);
}
}
void Test2()
{
using (int[] d = null)
Dummy(x2);
}
void Test3()
{
var x3 = 11;
Dummy(x3);
using (int[] d = null)
Dummy(x3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
// replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]'
var syntaxTree = Parse(source, filename: "file.cs");
for (int i = 0; i < 3; i++)
{
var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2);
var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single();
{
var rankSpecifierNew = rankSpecifierOld
.WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(
SyntaxFactory.NodeOrTokenList(
SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"),
SyntaxFactory.Token(SyntaxKind.CommaToken),
SyntaxFactory.ParseExpression($"x{i + 1}")
)));
syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree;
}
}
var compilation = CreateCompilation(syntaxTree, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// file.cs(12,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x1),x1] d = null").WithArguments("int[*,*]").WithLocation(12, 16),
// file.cs(12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 19),
// file.cs(12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20),
// file.cs(12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x1),x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51),
// file.cs(14,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19),
// file.cs(20,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x2),x2] d = null").WithArguments("int[*,*]").WithLocation(20, 16),
// file.cs(20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(20, 19),
// file.cs(20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20),
// file.cs(20,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x2),x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 51),
// file.cs(21,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19),
// file.cs(29,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x3),x3] d = null").WithArguments("int[*,*]").WithLocation(29, 16),
// file.cs(29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3),x3]").WithLocation(29, 19),
// file.cs(29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20),
// file.cs(29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// file.cs(29,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using (int[TakeOutParam(true, out var x3),x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 51),
// file.cs(30,19): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]);
}
[Fact]
public void Scope_InvalidArrayDimensions_03()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
void Test1()
{
using int[TakeOutParam(true, out var x1), x1] d = null;
Dummy(x1);
}
void Test2()
{
var x2 = 11;
Dummy(x2);
using int[TakeOutParam(true, out var x2), x2] d = null;
Dummy(x2);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (12,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x1), x1] d = null;").WithArguments("int[*,*]").WithLocation(12, 9),
// (12,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 18),
// (12,19): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 19),
// (12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x1), x1] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51),
// (13,15): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 15),
// (21,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x2), x2] d = null;").WithArguments("int[*,*]").WithLocation(21, 9),
// (21,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(21, 18),
// (21,19): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 19),
// (21,46): error CS0128: A local variable or function named 'x2' is already defined in this scope
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(21, 46),
// (21,46): warning CS0168: The variable 'x2' is declared but never used
// using int[TakeOutParam(true, out var x2), x2] d = null;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(21, 46)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(3, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyNotAnOutLocal(model, x2Ref[1]);
VerifyNotAnOutLocal(model, x2Ref[2]);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, isShadowed: true);
}
[Fact]
public void Scope_InvalidArrayDimensions_04()
{
var source =
@"
public class X
{
public static void Main()
{
}
bool Dummy(object x) {return true;}
void Test1()
{
for (int[] a = null;;)
Dummy(x1);
}
void Test2()
{
var x2 = 11;
Dummy(x2);
for (int[] a = null;;)
Dummy(x2);
}
static bool TakeOutParam(object y, out bool x)
{
x = true;
return true;
}
}
";
// replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]'
var syntaxTree = Parse(source, filename: "file.cs");
for (int i = 0; i < 2; i++)
{
var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2);
var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single();
{
var rankSpecifierNew = rankSpecifierOld
.WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>(
SyntaxFactory.NodeOrTokenList(
SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"),
SyntaxFactory.Token(SyntaxKind.CommaToken),
SyntaxFactory.ParseExpression($"x{i + 1}")
)));
syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree;
}
}
var compilation = CreateCompilation(syntaxTree, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// file.cs(12,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 17),
// file.cs(12,18): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 18),
// file.cs(12,49): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 49),
// file.cs(13,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 19),
// file.cs(12,53): warning CS0219: The variable 'a' is assigned but its value is never used
// for (int[TakeOutParam(true, out var x1),x1] a = null;;)
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(12, 53),
// file.cs(21,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(21, 17),
// file.cs(21,45): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 45),
// file.cs(21,18): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 18),
// file.cs(21,49): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(21, 49),
// file.cs(22,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(22, 19),
// file.cs(21,53): warning CS0219: The variable 'a' is assigned but its value is never used
// for (int[TakeOutParam(true, out var x2),x2] a = null;;)
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(21, 53)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(3, x2Ref.Length);
VerifyNotAnOutLocal(model, x2Ref[0]);
VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref[1], x2Ref[2]);
}
[Fact]
public void Scope_InvalidArrayDimensions_05()
{
var source =
@"
public class X
{
public static void Main()
{
}
System.IDisposable Dummy(object x) {return null;}
unsafe void Test1()
{
fixed (int[TakeOutParam(true, out var x1), x1] d = null)
{
Dummy(x1);
}
}
unsafe void Test2()
{
fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Dummy(x2);
}
unsafe void Test3()
{
var x3 = 11;
Dummy(x3);
fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Dummy(x3);
}
static bool TakeOutParam<T>(T y, out T x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (10,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test1()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test1").WithLocation(10, 17),
// (12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 19),
// (12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20),
// (12,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 52),
// (12,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x1), x1] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(12, 56),
// (14,19): error CS0165: Use of unassigned local variable 'x1'
// Dummy(x1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19),
// (18,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test2()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test2").WithLocation(18, 17),
// (20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(20, 19),
// (20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20),
// (20,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 52),
// (20,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x2), x2] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(20, 56),
// (21,19): error CS0165: Use of unassigned local variable 'x2'
// Dummy(x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19),
// (24,17): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe void Test3()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test3").WithLocation(24, 17),
// (29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3), x3]").WithLocation(29, 19),
// (29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20),
// (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47),
// (29,52): error CS0029: Cannot implicitly convert type 'bool' to 'int'
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 52),
// (29,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type
// fixed (int[TakeOutParam(true, out var x3), x3] d = null)
Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(29, 56),
// (30,19): error CS0165: Use of unassigned local variable 'x3'
// Dummy(x3);
Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var x1Decl = GetOutVarDeclarations(tree, "x1").Single();
var x1Ref = GetReferences(tree, "x1").ToArray();
Assert.Equal(2, x1Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref);
var x2Decl = GetOutVarDeclarations(tree, "x2").Single();
var x2Ref = GetReferences(tree, "x2").ToArray();
Assert.Equal(2, x2Ref.Length);
VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref);
var x3Decl = GetOutVarDeclarations(tree, "x3").Single();
var x3Ref = GetReferences(tree, "x3").ToArray();
Assert.Equal(3, x3Ref.Length);
VerifyNotAnOutLocal(model, x3Ref[0]);
VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]);
}
[Fact]
public void DeclarationInNameof_00()
{
var text = @"
class C
{
public static void Main()
{
var x = nameof(M2(M1(out var x1), x1)).ToString();
}
static int M1(out int z) => z = 1;
static int M2(int a, int b) => 2;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,24): error CS8081: Expression does not have a name.
// var x = nameof(M2(M1(out var x1), x1)).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M2(M1(out var x1), x1)").WithLocation(6, 24)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var name = "x1";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(1, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
[Fact]
public void DeclarationInNameof_01()
{
var text = @"
class C
{
public static void Main(int arg)
{
void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
int x = z1 + z2;
}
static int M(out int z) => z = 1;
static bool M(object a, int b) => b == 0;
}
";
// 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,83): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 83),
// (6,39): error CS8081: Expression does not have a name.
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 39),
// (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out int z1)), z1)").WithArguments("b").WithLocation(6, 30),
// (6,69): error CS0103: The name 'z1' does not exist in the current context
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 69),
// (7,83): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 83),
// (7,39): error CS8081: Expression does not have a name.
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 39),
// (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 30),
// (7,69): error CS0103: The name 'z2' does not exist in the current context
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 69),
// (9,17): error CS0103: The name 'z1' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17),
// (9,22): error CS0103: The name 'z2' does not exist in the current context
// int x = z1 + z2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22),
// (6,14): warning CS8321: The local function 'Local2' is declared but never used
// void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14),
// (7,14): warning CS8321: The local function 'Local5' is declared but never used
// void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(4, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, reference: refs[0]);
VerifyNotInScope(model, refs[1]);
VerifyNotInScope(model, refs[2]);
VerifyNotInScope(model, refs[3]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_02a()
{
var text = @"
[My(C.M(nameof(C.M(out int z1)), z1), z1)]
[My(C.M(nameof(C.M(out var z2)), z2), z2)]
class C
{
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
class MyAttribute: System.Attribute
{
public MyAttribute(bool x, int y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (2,16): error CS8081: Expression does not have a name.
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 16),
// (2,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 5),
// (2,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 39),
// (3,16): error CS8081: Expression does not have a name.
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 16),
// (3,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 5),
// (3,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 39)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_02b()
{
var text1 = @"
[assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
[assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
";
var text2 = @"
class C
{
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
class MyAttribute: System.Attribute
{
public MyAttribute(bool x, int y) {}
}
";
var compilation = CreateCompilationWithMscorlib45(new[] { text1, text2 });
compilation.VerifyDiagnostics(
// (2,26): error CS8081: Expression does not have a name.
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 26),
// (2,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 15),
// (2,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 49),
// (3,26): error CS8081: Expression does not have a name.
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 26),
// (3,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 15),
// (3,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 49)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_03()
{
var text = @"
class C
{
public static void Main(string[] args)
{
switch ((object)args.Length)
{
case !M(nameof(M(out int z1)), z1):
System.Console.WriteLine(z1);
break;
case !M(nameof(M(out var z2)), z2):
System.Console.WriteLine(z2);
break;
}
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (8,28): error CS8081: Expression does not have a name.
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(8, 28),
// (8,18): error CS0150: A constant value is expected
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out int z1)), z1)").WithLocation(8, 18),
// (11,28): error CS8081: Expression does not have a name.
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(11, 28),
// (11,18): error CS0150: A constant value is expected
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out var z2)), z2)").WithLocation(11, 18),
// (8,44): error CS0165: Use of unassigned local variable 'z1'
// case !M(nameof(M(out int z1)), z1):
Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(8, 44),
// (11,44): error CS0165: Use of unassigned local variable 'z2'
// case !M(nameof(M(out var z2)), z2):
Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(11, 44)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_04()
{
var text = @"
class C
{
const bool a = M(nameof(M(out int z1)), z1);
const bool b = M(nameof(M(out var z2)), z2);
const bool c = (z1 + z2) == 0;
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (5,29): error CS8081: Expression does not have a name.
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(5, 29),
// (5,20): error CS0133: The expression being assigned to 'C.b' must be constant
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("C.b").WithLocation(5, 20),
// (6,21): error CS0103: The name 'z1' does not exist in the current context
// const bool c = (z1 + z2) == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 21),
// (6,26): error CS0103: The name 'z2' does not exist in the current context
// const bool c = (z1 + z2) == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(6, 26),
// (4,29): error CS8081: Expression does not have a name.
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(4, 29),
// (4,20): error CS0133: The expression being assigned to 'C.a' must be constant
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("C.a").WithLocation(4, 20)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_05()
{
var text = @"
class C
{
public static void Main(string[] args)
{
const bool a = M(nameof(M(out int z1)), z1);
const bool b = M(nameof(M(out var z2)), z2);
bool c = (z1 + z2) == 0;
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,33): error CS8081: Expression does not have a name.
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 33),
// (6,24): error CS0133: The expression being assigned to 'a' must be constant
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("a").WithLocation(6, 24),
// (7,33): error CS8081: Expression does not have a name.
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 33),
// (7,24): error CS0133: The expression being assigned to 'b' must be constant
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 24),
// (6,49): error CS0165: Use of unassigned local variable 'z1'
// const bool a = M(nameof(M(out int z1)), z1);
Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(6, 49),
// (7,49): error CS0165: Use of unassigned local variable 'z2'
// const bool b = M(nameof(M(out var z2)), z2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(7, 49)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
for (int i = 1; i <= 2; i++)
{
var name = $"z{i}";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVarInNotExecutableCode(model, decl, refs);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
}
[Fact]
public void DeclarationInNameof_06()
{
var text = @"
class C
{
public static void Main(string[] args)
{
string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString();
bool c = z1 == 0;
}
public static int M(out int z) => z = 1;
public static bool M(object a, int b) => b == 0;
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,27): error CS8081: Expression does not have a name.
// string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(System.Action)(() => M(M(out var z1), z1))").WithLocation(6, 27),
// (7,18): error CS0103: The name 'z1' does not exist in the current context
// bool c = z1 == 0;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(7, 18)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var name = "z1";
var decl = GetOutVarDeclaration(tree, name);
var refs = GetReferences(tree, name).ToArray();
Assert.Equal(2, refs.Length);
VerifyModelForOutVar(model, decl, refs[0]);
VerifyNotInScope(model, refs[1]);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_01()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p =>
{
weakRef.TryGetTarget(out var x);
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_02()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p1 =>
{
void Local1 (Action<T> onNext = p2 =>
{
weakRef.TryGetTarget(out var x);
})
{
}
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_03()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (Action<T> onNext = p1 =>
{
void Local1 (Action<T> onNext = p2 =>
{
void Local1 (Action<T> onNext = p3 =>
{
weakRef.TryGetTarget(out var x);
})
{
}
})
{
}
})
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_04()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (object onNext = from p in y select weakRef.TryGetTarget(out var x))
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_05()
{
string source = @"
class C
{
void M<T>()
{
void Local1 (object onNext = from p in y
select (Action<T>)( p =>
{
void Local2 (object onNext = from p in y select weakRef.TryGetTarget(out var x))
{
}
}
)
)
{
}
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType)); // crashes
var decl = GetOutVarDeclaration(tree, "x");
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_06()
{
string source = @"
class C
{
void M<T>()
{
System.Type t = typeof(int[p =>
{
weakRef.TryGetTarget(out var x);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_07()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[p1 =>
{
System.Type t2 = typeof(int[p2 =>
{
weakRef.TryGetTarget(out var x);
}]);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_08()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[p1 =>
{
System.Type t2 = typeof(int[p2 =>
{
System.Type t3 = typeof(int[p3 =>
{
weakRef.TryGetTarget(out var x);
}]);
}]);
}]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_09()
{
string source = @"
class C
{
void M<T>()
{
System.Type t = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")]
[WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")]
public void GetEnclosingBinderInternalRecovery_10()
{
string source = @"
class C
{
void M<T>()
{
System.Type t1 = typeof(int[from p in y
select (Action<T>)( p =>
{
System.Type t2 = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]);
}
)
]
);
}
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single();
Assert.Equal("var", varType.ToString());
Assert.Null(model.GetAliasInfo(varType));
var decl = GetOutVarDeclaration(tree, "x");
Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes
VerifyModelForOutVarInNotExecutableCode(model, decl);
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation);
Assert.Equal("var", symbol.Type.ToTestDisplayString());
}
[Fact]
[WorkItem(445600, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=445600")]
public void GetEnclosingBinderInternalRecovery_11()
{
var text = @"
class Program
{
static void Main(string[] args)
{
foreach
other(some().F(a => TestOutVar(out var x) ? x : 1));
}
static void TestOutVar(out int a)
{
a = 0;
}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (6,16): error CS1003: Syntax error, '(' expected
// foreach
Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", "").WithLocation(6, 16),
// (7,60): error CS1515: 'in' expected
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_InExpected, ";").WithLocation(7, 60),
// (7,60): error CS0230: Type and identifier are both required in a foreach statement
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_BadForeachDecl, ";").WithLocation(7, 60),
// (7,60): error CS1525: Invalid expression term ';'
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 60),
// (7,60): error CS1026: ) expected
// other(some().F(a => TestOutVar(out var x) ? x : 1));
Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(7, 60)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var xDecl = GetOutVarDeclaration(tree, "x");
var xRef = GetReferences(tree, "x", 1);
VerifyModelForOutVarWithoutDataFlow(model, xDecl, xRef);
Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef[0]).Type.ToTestDisplayString());
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates()
{
var source =
@"using System;
class C
{
static void Main()
{
G(x => x > 0 && F(out var y) && y > 0);
}
static bool F(out int i)
{
i = 0;
return true;
}
static void G(Func<int, bool> f, object o) { }
static void G(C c, object o) { }
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (6,9): error CS1501: No overload for method 'G' takes 1 arguments
// G(x => x > 0 && F(out var y) && y > 0);
Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(6, 9));
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates_Expression()
{
var source =
@"using System;
using System.Linq.Expressions;
class C
{
static void Main()
{
G(x => x > 0 && F(out var y) && y > 0);
}
static bool F(out int i)
{
i = 0;
return true;
}
static void G(Expression<Func<int, bool>> f, object o) { }
static void G(C c, object o) { }
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (7,9): error CS1501: No overload for method 'G' takes 1 arguments
// G(x => x > 0 && F(out var y) && y > 0);
Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(7, 9));
}
[Fact]
[WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")]
public void ErrorRecoveryShouldIgnoreNonDelegates_Query()
{
var source =
@"using System.Linq;
class C
{
static void M()
{
var c = from x in new[] { 1, 2, 3 }
group x > 1 && F(out var y) && y == null
by x;
}
static bool F(out object o)
{
o = null;
return true;
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")]
public void SpeculativeSemanticModelWithOutDiscard()
{
var source =
@"class C
{
static void F()
{
C.G(out _);
}
static void G(out object o)
{
o = null;
}
}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var identifierBefore = GetReferences(tree, "G").Single();
Assert.Equal(tree, identifierBefore.Location.SourceTree);
var statementBefore = identifierBefore.Ancestors().OfType<StatementSyntax>().First();
var statementAfter = SyntaxFactory.ParseStatement(@"G(out _);");
bool success = model.TryGetSpeculativeSemanticModel(statementBefore.SpanStart, statementAfter, out model);
Assert.True(success);
var identifierAfter = statementAfter.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "G");
Assert.Null(identifierAfter.Location.SourceTree);
var info = model.GetSymbolInfo(identifierAfter);
Assert.Equal("void C.G(out System.Object o)", info.Symbol.ToTestDisplayString());
}
[Fact]
[WorkItem(10604, "https://github.com/dotnet/roslyn/issues/10604")]
[WorkItem(16306, "https://github.com/dotnet/roslyn/issues/16306")]
public void GetForEachSymbolInfoWithOutVar()
{
var source =
@"using System.Collections.Generic;
public class C
{
void M()
{
foreach (var x in M2(out int i)) { }
}
IEnumerable<object> M2(out int j)
{
throw null;
}
}";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var foreachStatement = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single();
var info = model.GetForEachStatementInfo(foreachStatement);
Assert.Equal("System.Object", info.ElementType.ToTestDisplayString());
Assert.Equal("System.Collections.Generic.IEnumerator<System.Object> System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator()",
info.GetEnumeratorMethod.ToTestDisplayString());
}
[WorkItem(19382, "https://github.com/dotnet/roslyn/issues/19382")]
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void DiscardAndArgList()
{
var text = @"
using System;
public class C
{
static void Main()
{
M(out _, __arglist(2, 3, true));
}
static void M(out int x, __arglist)
{
x = 0;
DumpArgs(new ArgIterator(__arglist));
}
static void DumpArgs(ArgIterator args)
{
while(args.GetRemainingCount() > 0)
{
TypedReference tr = args.GetNextArg();
object arg = TypedReference.ToObject(tr);
Console.Write(arg);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
);
CompileAndVerify(compilation, expectedOutput: "23True");
}
[Fact]
[WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")]
public void OutVarInArgList_01()
{
var text = @"
public class C
{
static void Main()
{
M(1, __arglist(out int y));
M(2, __arglist(out var z));
System.Console.WriteLine(z);
}
static void M(int x, __arglist)
{
x = 0;
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// M(1, __arglist(out int y));
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 28),
// (7,32): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'.
// M(2, __arglist(out var z));
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 32),
// (7,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// M(2, __arglist(out var z));
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 28)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVar(model, zDecl, zRef);
}
[Fact]
[WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")]
public void OutVarInArgList_02()
{
var text = @"
public class C
{
static void Main()
{
__arglist(out int y);
__arglist(out var z);
System.Console.WriteLine(z);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// __arglist(out int y);
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 23),
// (6,9): error CS0226: An __arglist expression may only appear inside of a call or new expression
// __arglist(out int y);
Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out int y)").WithLocation(6, 9),
// (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'.
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 27),
// (7,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out'
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 23),
// (7,9): error CS0226: An __arglist expression may only appear inside of a call or new expression
// __arglist(out var z);
Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out var z)").WithLocation(7, 9)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVar(model, zDecl, zRef);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void OutVarInNewT_01()
{
var text = @"
public class C
{
static void M<T>() where T : new()
{
var x = new T(out var z);
System.Console.WriteLine(z);
}
}";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
// var x = new T(out var z);
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z)").WithArguments("T").WithLocation(6, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef);
var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal("new T(out var z)", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out var z)')
Children(1):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z')
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void OutVarInNewT_02()
{
var text = @"
public class C
{
static void M<T>() where T : C, new()
{
var x = new T(out var z) {F1 = 1};
System.Console.WriteLine(z);
}
public int F1;
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
compilation.VerifyDiagnostics(
// (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
// var x = new T(out var z) {F1 = 1};
Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z) {F1 = 1}").WithArguments("T").WithLocation(6, 17)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var zDecl = GetOutVarDeclaration(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef);
var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal("new T(out var z) {F1 = 1}", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out v ... z) {F1 = 1}')
Children(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z')
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: T, IsInvalid) (Syntax: '{F1 = 1}')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'F1 = 1')
Left:
IFieldReferenceOperation: System.Int32 C.F1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'F1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'F1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
");
}
[Fact]
public void EventInitializers_01()
{
var source =
@"
public class X
{
public static void Main()
{
System.Console.WriteLine(Test1());
}
static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1));
static System.Func<bool> GetDelegate(bool value) => () => value;
static bool Dummy(int x)
{
System.Console.WriteLine(x);
return true;
}
static bool TakeOutParam(int y, out int x)
{
x = y;
return true;
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular);
CompileAndVerify(compilation, expectedOutput: @"1
True");
CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (9,76): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1));
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 76)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ConstructorBodyOperation()
{
var text = @"
public class C
{
C() : this(out var x)
{ M(out var y); }
=> M(out var z);
C (out int x){x=1;}
void M (out int x){x=1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
Assert.Equal(": this(out var x)", initializerSyntax.ToString());
compilation.VerifyOperationTree(initializerSyntax, expectedOperationTree:
@"
IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation initializerOperation = model.GetOperation(initializerSyntax);
Assert.Equal(OperationKind.ExpressionStatement, initializerOperation.Parent.Kind);
var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
Assert.Equal("{ M(out var y); }", blockBodySyntax.ToString());
compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }')
Locals: Local_1: System.Int32 y
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation blockBodyOperation = model.GetOperation(blockBodySyntax);
Assert.Equal(OperationKind.ConstructorBody, blockBodyOperation.Parent.Kind);
Assert.Same(initializerOperation.Parent.Parent, blockBodyOperation.Parent);
Assert.Null(blockBodyOperation.Parent.Parent);
var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var z)", expressionBodySyntax.ToString());
compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
Assert.Same(blockBodyOperation.Parent, model.GetOperation(expressionBodySyntax).Parent);
var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First();
Assert.Same(blockBodyOperation.Parent, model.GetOperation(declarationSyntax));
compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree:
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'C() : this( ... out var z);')
Locals: Local_1: System.Int32 x
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Expression:
IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }')
Locals: Local_1: System.Int32 y
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ExpressionBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)')
Expression:
IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void MethodBodyOperation()
{
var text = @"
public class C
{
int P
{
get {return M(out var x);} => M(out var y);
} => M(out var z);
int M (out int x){x=1; return 1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var y)", expressionBodySyntax.ToString());
compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)')
Locals: Local_1: System.Int32 y
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation expressionBodyOperation = model.GetOperation(expressionBodySyntax);
Assert.Equal(OperationKind.MethodBody, expressionBodyOperation.Parent.Kind);
Assert.Null(expressionBodyOperation.Parent.Parent);
var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
Assert.Equal("{return M(out var x);}", blockBodySyntax.ToString());
compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}')
Locals: Local_1: System.Int32 x
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
IOperation blockBodyOperation = model.GetOperation(blockBodySyntax);
Assert.Same(expressionBodyOperation.Parent, blockBodyOperation.Parent);
var propertyExpressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().ElementAt(1);
Assert.Equal("=> M(out var z)", propertyExpressionBodySyntax.ToString());
Assert.Null(model.GetOperation(propertyExpressionBodySyntax)); // https://github.com/dotnet/roslyn/issues/24900
var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single();
Assert.Same(expressionBodyOperation.Parent, model.GetOperation(declarationSyntax));
compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree:
@"
IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'get {return ... out var y);')
BlockBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}')
Locals: Local_1: System.Int32 x
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x')
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ExpressionBody:
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)')
Locals: Local_1: System.Int32 y
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void PropertyExpressionBodyOperation()
{
var text = @"
public class C
{
int P => M(out var z);
int M (out int x){x=1; return 1;}
}
";
var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node3 = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First();
Assert.Equal("=> M(out var z)", node3.ToString());
compilation.VerifyOperationTree(node3, expectedOperationTree:
@"
IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '=> M(out var z)')
Locals: Local_1: System.Int32 z
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'M(out var z)')
ReturnedValue:
IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M(out var z)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var z')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var z')
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
Assert.Null(model.GetOperation(node3).Parent);
}
[Fact]
public void OutVarInConstructorUsedInObjectInitializer()
{
var source =
@"
public class C
{
public int Number { get; set; }
public C(out int n)
{
n = 1;
}
public static void Main()
{
C c = new C(out var i) { Number = i };
System.Console.WriteLine(c.Number);
}
}
";
CompileAndVerify(source, expectedOutput: @"1");
}
[Fact]
public void OutVarInConstructorUsedInCollectionInitializer()
{
var source =
@"
public class C : System.Collections.Generic.List<int>
{
public C(out int n)
{
n = 1;
}
public static void Main()
{
C c = new C(out var i) { i, i, i };
System.Console.WriteLine(c[0]);
}
}
";
CompileAndVerify(source, expectedOutput: @"1");
}
[Fact]
[WorkItem(49997, "https://github.com/dotnet/roslyn/issues/49997")]
public void Issue49997()
{
var text = @"
public class Cls
{
public static void Main()
{
if ()
.Test1().Test2(out var x1).Test3();
}
}
static class Ext
{
public static void Test3(this Cls x) {}
}
";
var compilation = CreateCompilation(text);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test3").Last();
Assert.True(model.GetSymbolInfo(node).IsEmpty);
}
}
internal static class OutVarTestsExtensions
{
internal static SingleVariableDesignationSyntax VariableDesignation(this DeclarationExpressionSyntax self)
{
return (SingleVariableDesignationSyntax)self.Designation;
}
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.