repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeImplementsStatement.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeElement2))]
public sealed class CodeImplementsStatement : AbstractCodeElement
{
internal static EnvDTE80.CodeElement2 Create(
CodeModelState state,
AbstractCodeMember parent,
string namespaceName,
int ordinal)
{
var element = new CodeImplementsStatement(state, parent, namespaceName, ordinal);
var result = (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element);
return result;
}
internal static EnvDTE80.CodeElement2 CreateUnknown(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
{
var element = new CodeImplementsStatement(state, fileCodeModel, nodeKind, name);
return (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element);
}
private readonly ParentHandle<AbstractCodeMember> _parentHandle;
private readonly string _namespaceName;
private readonly int _ordinal;
private CodeImplementsStatement(
CodeModelState state,
AbstractCodeMember parent,
string namespaceName,
int ordinal)
: base(state, parent.FileCodeModel)
{
_parentHandle = new ParentHandle<AbstractCodeMember>(parent);
_namespaceName = namespaceName;
_ordinal = ordinal;
}
private CodeImplementsStatement(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
: base(state, fileCodeModel, nodeKind)
{
_namespaceName = name;
}
internal override bool TryLookupNode(out SyntaxNode node)
{
node = null;
var parentNode = _parentHandle.Value.LookupNode();
if (parentNode == null)
{
return false;
}
if (!CodeModelService.TryGetImplementsNode(parentNode, _namespaceName, _ordinal, out var implementsNode))
{
return false;
}
node = implementsNode;
return node != null;
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementImplementsStmt; }
}
public override object Parent
{
get { return _parentHandle.Value; }
}
public override EnvDTE.CodeElements Children
{
get { return EmptyCollection.Create(this.State, this); }
}
protected override void SetName(string value)
=> throw Exceptions.ThrowENotImpl();
public override void RenameSymbol(string newName)
=> throw Exceptions.ThrowENotImpl();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeElement2))]
public sealed class CodeImplementsStatement : AbstractCodeElement
{
internal static EnvDTE80.CodeElement2 Create(
CodeModelState state,
AbstractCodeMember parent,
string namespaceName,
int ordinal)
{
var element = new CodeImplementsStatement(state, parent, namespaceName, ordinal);
var result = (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element);
return result;
}
internal static EnvDTE80.CodeElement2 CreateUnknown(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
{
var element = new CodeImplementsStatement(state, fileCodeModel, nodeKind, name);
return (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element);
}
private readonly ParentHandle<AbstractCodeMember> _parentHandle;
private readonly string _namespaceName;
private readonly int _ordinal;
private CodeImplementsStatement(
CodeModelState state,
AbstractCodeMember parent,
string namespaceName,
int ordinal)
: base(state, parent.FileCodeModel)
{
_parentHandle = new ParentHandle<AbstractCodeMember>(parent);
_namespaceName = namespaceName;
_ordinal = ordinal;
}
private CodeImplementsStatement(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
: base(state, fileCodeModel, nodeKind)
{
_namespaceName = name;
}
internal override bool TryLookupNode(out SyntaxNode node)
{
node = null;
var parentNode = _parentHandle.Value.LookupNode();
if (parentNode == null)
{
return false;
}
if (!CodeModelService.TryGetImplementsNode(parentNode, _namespaceName, _ordinal, out var implementsNode))
{
return false;
}
node = implementsNode;
return node != null;
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementImplementsStmt; }
}
public override object Parent
{
get { return _parentHandle.Value; }
}
public override EnvDTE.CodeElements Children
{
get { return EmptyCollection.Create(this.State, this); }
}
protected override void SetName(string value)
=> throw Exceptions.ThrowENotImpl();
public override void RenameSymbol(string newName)
=> throw Exceptions.ThrowENotImpl();
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationAttributeData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationAttributeData : AttributeData
{
private readonly INamedTypeSymbol _attributeClass;
private readonly ImmutableArray<TypedConstant> _constructorArguments;
private readonly ImmutableArray<KeyValuePair<string, TypedConstant>> _namedArguments;
protected override INamedTypeSymbol CommonAttributeClass => _attributeClass;
protected override IMethodSymbol CommonAttributeConstructor => null;
protected override ImmutableArray<TypedConstant> CommonConstructorArguments => _constructorArguments;
protected override ImmutableArray<KeyValuePair<string, TypedConstant>> CommonNamedArguments => _namedArguments;
protected override SyntaxReference CommonApplicationSyntaxReference => null;
public CodeGenerationAttributeData(
INamedTypeSymbol attributeClass,
ImmutableArray<TypedConstant> constructorArguments,
ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments)
{
_attributeClass = attributeClass;
_constructorArguments = constructorArguments.NullToEmpty();
_namedArguments = namedArguments.NullToEmpty();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationAttributeData : AttributeData
{
private readonly INamedTypeSymbol _attributeClass;
private readonly ImmutableArray<TypedConstant> _constructorArguments;
private readonly ImmutableArray<KeyValuePair<string, TypedConstant>> _namedArguments;
protected override INamedTypeSymbol CommonAttributeClass => _attributeClass;
protected override IMethodSymbol CommonAttributeConstructor => null;
protected override ImmutableArray<TypedConstant> CommonConstructorArguments => _constructorArguments;
protected override ImmutableArray<KeyValuePair<string, TypedConstant>> CommonNamedArguments => _namedArguments;
protected override SyntaxReference CommonApplicationSyntaxReference => null;
public CodeGenerationAttributeData(
INamedTypeSymbol attributeClass,
ImmutableArray<TypedConstant> constructorArguments,
ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments)
{
_attributeClass = attributeClass;
_constructorArguments = constructorArguments.NullToEmpty();
_namedArguments = namedArguments.NullToEmpty();
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/VisualStudio/Core/Def/EditorConfigSettings/CodeStyle/View/CodeStyleSettingsView.xaml.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using System.Windows.Controls;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View
{
/// <summary>
/// Interaction logic for CodeStyleView.xaml
/// </summary>
internal partial class CodeStyleSettingsView : UserControl, ISettingsEditorView
{
private readonly IWpfSettingsEditorViewModel _viewModel;
public CodeStyleSettingsView(IWpfSettingsEditorViewModel viewModel)
{
InitializeComponent();
_viewModel = viewModel;
TableControl = _viewModel.GetTableControl();
CodeStyleTable.Child = TableControl.Control;
DataContext = viewModel;
}
public UserControl SettingControl => this;
public IWpfTableControl TableControl { get; }
public Task<SourceText> UpdateEditorConfigAsync(SourceText sourceText) => _viewModel.UpdateEditorConfigAsync(sourceText);
public void OnClose() => _viewModel.ShutDown();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using System.Windows.Controls;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View
{
/// <summary>
/// Interaction logic for CodeStyleView.xaml
/// </summary>
internal partial class CodeStyleSettingsView : UserControl, ISettingsEditorView
{
private readonly IWpfSettingsEditorViewModel _viewModel;
public CodeStyleSettingsView(IWpfSettingsEditorViewModel viewModel)
{
InitializeComponent();
_viewModel = viewModel;
TableControl = _viewModel.GetTableControl();
CodeStyleTable.Child = TableControl.Control;
DataContext = viewModel;
}
public UserControl SettingControl => this;
public IWpfTableControl TableControl { get; }
public Task<SourceText> UpdateEditorConfigAsync(SourceText sourceText) => _viewModel.UpdateEditorConfigAsync(sourceText);
public void OnClose() => _viewModel.ShutDown();
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Tools/AnalyzerRunner/IncrementalAnalyzerRunner.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols.SymbolTree;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.IncrementalCaches;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Storage;
namespace AnalyzerRunner
{
public sealed class IncrementalAnalyzerRunner
{
private readonly Workspace _workspace;
private readonly Options _options;
public IncrementalAnalyzerRunner(Workspace workspace, Options options)
{
_workspace = workspace;
_options = options;
}
public bool HasAnalyzers => _options.IncrementalAnalyzerNames.Any();
public async Task RunAsync(CancellationToken cancellationToken)
{
if (!HasAnalyzers)
{
return;
}
var usePersistentStorage = _options.UsePersistentStorage;
_workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options
.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, _options.AnalysisScope)
.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic, _options.AnalysisScope)
.WithChangedOption(StorageOptions.Database, usePersistentStorage ? StorageDatabase.SQLite : StorageDatabase.None)));
var exportProvider = (IMefHostExportProvider)_workspace.Services.HostServices;
var solutionCrawlerRegistrationService = (SolutionCrawlerRegistrationService)_workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>();
solutionCrawlerRegistrationService.Register(_workspace);
if (usePersistentStorage)
{
var persistentStorageService = _workspace.Services.GetRequiredService<IPersistentStorageService>();
await using var persistentStorage = await persistentStorageService.GetStorageAsync(_workspace.CurrentSolution, cancellationToken).ConfigureAwait(false);
if (persistentStorage is NoOpPersistentStorage)
{
throw new InvalidOperationException("Benchmark is not configured to use persistent storage.");
}
}
var incrementalAnalyzerProviders = exportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>();
foreach (var incrementalAnalyzerName in _options.IncrementalAnalyzerNames)
{
var incrementalAnalyzerProvider = incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(_workspace.Kind) ?? false)?.Value;
incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(WorkspaceKind.Host) ?? false)?.Value;
incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(WorkspaceKind.RemoteWorkspace) ?? false)?.Value;
incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).Single(provider => provider.Metadata.WorkspaceKinds is null).Value;
var incrementalAnalyzer = incrementalAnalyzerProvider.CreateIncrementalAnalyzer(_workspace);
solutionCrawlerRegistrationService.GetTestAccessor().WaitUntilCompletion(_workspace, ImmutableArray.Create(incrementalAnalyzer));
switch (incrementalAnalyzerName)
{
case nameof(SymbolTreeInfoIncrementalAnalyzerProvider):
var symbolTreeInfoCacheService = _workspace.Services.GetRequiredService<ISymbolTreeInfoCacheService>();
var symbolTreeInfo = await symbolTreeInfoCacheService.TryGetSourceSymbolTreeInfoAsync(_workspace.CurrentSolution.Projects.First(), cancellationToken).ConfigureAwait(false);
if (symbolTreeInfo is null)
{
throw new InvalidOperationException("Benchmark failed to calculate symbol tree info.");
}
break;
default:
// No additional actions required
break;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols.SymbolTree;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.IncrementalCaches;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Storage;
namespace AnalyzerRunner
{
public sealed class IncrementalAnalyzerRunner
{
private readonly Workspace _workspace;
private readonly Options _options;
public IncrementalAnalyzerRunner(Workspace workspace, Options options)
{
_workspace = workspace;
_options = options;
}
public bool HasAnalyzers => _options.IncrementalAnalyzerNames.Any();
public async Task RunAsync(CancellationToken cancellationToken)
{
if (!HasAnalyzers)
{
return;
}
var usePersistentStorage = _options.UsePersistentStorage;
_workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options
.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp, _options.AnalysisScope)
.WithChangedOption(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic, _options.AnalysisScope)
.WithChangedOption(StorageOptions.Database, usePersistentStorage ? StorageDatabase.SQLite : StorageDatabase.None)));
var exportProvider = (IMefHostExportProvider)_workspace.Services.HostServices;
var solutionCrawlerRegistrationService = (SolutionCrawlerRegistrationService)_workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>();
solutionCrawlerRegistrationService.Register(_workspace);
if (usePersistentStorage)
{
var persistentStorageService = _workspace.Services.GetRequiredService<IPersistentStorageService>();
await using var persistentStorage = await persistentStorageService.GetStorageAsync(_workspace.CurrentSolution, cancellationToken).ConfigureAwait(false);
if (persistentStorage is NoOpPersistentStorage)
{
throw new InvalidOperationException("Benchmark is not configured to use persistent storage.");
}
}
var incrementalAnalyzerProviders = exportProvider.GetExports<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>();
foreach (var incrementalAnalyzerName in _options.IncrementalAnalyzerNames)
{
var incrementalAnalyzerProvider = incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(_workspace.Kind) ?? false)?.Value;
incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(WorkspaceKind.Host) ?? false)?.Value;
incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).SingleOrDefault(provider => provider.Metadata.WorkspaceKinds?.Contains(WorkspaceKind.RemoteWorkspace) ?? false)?.Value;
incrementalAnalyzerProvider ??= incrementalAnalyzerProviders.Where(x => x.Metadata.Name == incrementalAnalyzerName).Single(provider => provider.Metadata.WorkspaceKinds is null).Value;
var incrementalAnalyzer = incrementalAnalyzerProvider.CreateIncrementalAnalyzer(_workspace);
solutionCrawlerRegistrationService.GetTestAccessor().WaitUntilCompletion(_workspace, ImmutableArray.Create(incrementalAnalyzer));
switch (incrementalAnalyzerName)
{
case nameof(SymbolTreeInfoIncrementalAnalyzerProvider):
var symbolTreeInfoCacheService = _workspace.Services.GetRequiredService<ISymbolTreeInfoCacheService>();
var symbolTreeInfo = await symbolTreeInfoCacheService.TryGetSourceSymbolTreeInfoAsync(_workspace.CurrentSolution.Projects.First(), cancellationToken).ConfigureAwait(false);
if (symbolTreeInfo is null)
{
throw new InvalidOperationException("Benchmark failed to calculate symbol tree info.");
}
break;
default:
// No additional actions required
break;
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Compilers/CSharp/Test/Syntax/Parsing/StackAllocInitializerParsingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Xunit;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing
{
[CompilerTrait(CompilerFeature.StackAllocInitializer)]
public class StackAllocInitializerParsingTests : ParsingTests
{
public StackAllocInitializerParsingTests(ITestOutputHelper output) : base(output) { }
[Fact]
public void StackAllocInitializer_01()
{
UsingExpression("stackalloc int[] { 42 }", options: TestOptions.Regular7,
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(1, 1));
N(SyntaxKind.StackAllocArrayCreationExpression);
{
N(SyntaxKind.StackAllocKeyword);
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "42");
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void StackAllocInitializer_02()
{
UsingExpression("stackalloc int[1] { 42 }", options: TestOptions.Regular7,
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(1, 1));
N(SyntaxKind.StackAllocArrayCreationExpression);
{
N(SyntaxKind.StackAllocKeyword);
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "42");
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void StackAllocInitializer_03()
{
UsingExpression("stackalloc[] { 42 }", options: TestOptions.Regular7,
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(1, 1));
N(SyntaxKind.ImplicitStackAllocArrayCreationExpression);
{
N(SyntaxKind.StackAllocKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "42");
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void StackAllocInitializer_04()
{
UsingExpression("stackalloc[1] { 42 }", options: TestOptions.Regular7,
// (1,1): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater.
// stackalloc[1] { 42 }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(1, 1),
// (1,12): error CS8381: "Invalid rank specifier: expected ']'
// stackalloc[1] { 42 }
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "1").WithLocation(1, 12)
);
N(SyntaxKind.ImplicitStackAllocArrayCreationExpression);
{
N(SyntaxKind.StackAllocKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "42");
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void StackAllocInitializer_05()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28)
);
}
[Fact]
public void StackAllocInitializer_06()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3,] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28),
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 29)
);
}
[Fact]
public void StackAllocInitializer_07()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[,3] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 29),
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 28)
);
}
[Fact]
public void StackAllocInitializer_08()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[,3 { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3 { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 29),
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3 { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 28),
// (4,31): error CS1003: Syntax error, ']' expected
// var x = stackalloc[,3 { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments("]", "{").WithLocation(4, 31)
);
}
[Fact]
public void StackAllocInitializer_09()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3 { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3 { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28),
// (4,30): error CS1003: Syntax error, ']' expected
// var x = stackalloc[3 { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments("]", "{").WithLocation(4, 30)
);
}
[Fact]
public void StackAllocInitializer_10()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3, { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3, { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28),
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3, { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 29),
// (4,31): error CS1003: Syntax error, ']' expected
// var x = stackalloc[3, { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments("]", "{").WithLocation(4, 31)
);
}
[Fact]
public void StackAllocInitializer_11()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3,,] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28),
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 29),
// (4,30): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 30)
);
}
[Fact]
public void StackAllocInitializer_12()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[,3,] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 29),
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 28),
// (4,30): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 30)
);
}
[Fact]
public void StackAllocInitializer_13()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[,,3] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,30): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 30),
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 28),
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 29)
);
}
[Fact]
public void StackAllocInitializer_14()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3,,3] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28),
// (4,31): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 31),
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 29),
// (4,30): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 30)
);
}
[Fact]
public void StackAllocInitializer_15()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[ { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,29): error CS1003: Syntax error, ']' expected
// var x = stackalloc[ { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments("]", "{").WithLocation(4, 29)
);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Xunit;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing
{
[CompilerTrait(CompilerFeature.StackAllocInitializer)]
public class StackAllocInitializerParsingTests : ParsingTests
{
public StackAllocInitializerParsingTests(ITestOutputHelper output) : base(output) { }
[Fact]
public void StackAllocInitializer_01()
{
UsingExpression("stackalloc int[] { 42 }", options: TestOptions.Regular7,
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(1, 1));
N(SyntaxKind.StackAllocArrayCreationExpression);
{
N(SyntaxKind.StackAllocKeyword);
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "42");
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void StackAllocInitializer_02()
{
UsingExpression("stackalloc int[1] { 42 }", options: TestOptions.Regular7,
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(1, 1));
N(SyntaxKind.StackAllocArrayCreationExpression);
{
N(SyntaxKind.StackAllocKeyword);
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "42");
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void StackAllocInitializer_03()
{
UsingExpression("stackalloc[] { 42 }", options: TestOptions.Regular7,
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(1, 1));
N(SyntaxKind.ImplicitStackAllocArrayCreationExpression);
{
N(SyntaxKind.StackAllocKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "42");
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void StackAllocInitializer_04()
{
UsingExpression("stackalloc[1] { 42 }", options: TestOptions.Regular7,
// (1,1): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater.
// stackalloc[1] { 42 }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(1, 1),
// (1,12): error CS8381: "Invalid rank specifier: expected ']'
// stackalloc[1] { 42 }
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "1").WithLocation(1, 12)
);
N(SyntaxKind.ImplicitStackAllocArrayCreationExpression);
{
N(SyntaxKind.StackAllocKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "42");
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void StackAllocInitializer_05()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28)
);
}
[Fact]
public void StackAllocInitializer_06()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3,] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28),
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 29)
);
}
[Fact]
public void StackAllocInitializer_07()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[,3] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 29),
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 28)
);
}
[Fact]
public void StackAllocInitializer_08()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[,3 { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3 { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 29),
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3 { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 28),
// (4,31): error CS1003: Syntax error, ']' expected
// var x = stackalloc[,3 { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments("]", "{").WithLocation(4, 31)
);
}
[Fact]
public void StackAllocInitializer_09()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3 { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3 { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28),
// (4,30): error CS1003: Syntax error, ']' expected
// var x = stackalloc[3 { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments("]", "{").WithLocation(4, 30)
);
}
[Fact]
public void StackAllocInitializer_10()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3, { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3, { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28),
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3, { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 29),
// (4,31): error CS1003: Syntax error, ']' expected
// var x = stackalloc[3, { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments("]", "{").WithLocation(4, 31)
);
}
[Fact]
public void StackAllocInitializer_11()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3,,] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28),
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 29),
// (4,30): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 30)
);
}
[Fact]
public void StackAllocInitializer_12()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[,3,] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 29),
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 28),
// (4,30): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,3,] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 30)
);
}
[Fact]
public void StackAllocInitializer_13()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[,,3] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,30): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 30),
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 28),
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 29)
);
}
[Fact]
public void StackAllocInitializer_14()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[3,,3] { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,28): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 28),
// (4,31): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, "3").WithLocation(4, 31),
// (4,29): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 29),
// (4,30): error CS8381: "Invalid rank specifier: expected ']'
// var x = stackalloc[3,,3] { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(4, 30)
);
}
[Fact]
public void StackAllocInitializer_15()
{
var test = @"
class C {
void Goo() {
var x = stackalloc[ { 1, 2, 3 };
}
}
";
ParseAndValidate(test,
// (4,29): error CS1003: Syntax error, ']' expected
// var x = stackalloc[ { 1, 2, 3 };
Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments("]", "{").WithLocation(4, 29)
);
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Tools/ExternalAccess/FSharp/Editor/Shared/Utilities/FSharpClassificationTypeMap.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Shared.Utilities
{
[Export]
internal class FSharpClassificationTypeMap
{
private readonly Dictionary<string, IClassificationType> _identityMap;
private readonly IClassificationTypeRegistryService _registryService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpClassificationTypeMap(IClassificationTypeRegistryService registryService)
{
_registryService = registryService;
// Prepopulate the identity map with the constant string values from ClassificationTypeNames
var fields = typeof(ClassificationTypeNames).GetFields();
_identityMap = new Dictionary<string, IClassificationType>(fields.Length, ReferenceEqualityComparer.Instance);
foreach (var field in fields)
{
// The strings returned from reflection do not have reference-identity
// with the string constants used by the compiler. Fortunately, a call
// to string.Intern fixes them.
var value = string.Intern((string)field.GetValue(null));
_identityMap.Add(value, registryService.GetClassificationType(value));
}
}
public IClassificationType GetClassificationType(string name)
{
var type = GetClassificationTypeWorker(name);
if (type == null)
{
FatalError.ReportAndCatch(new Exception($"classification type doesn't exist for {name}"));
}
return type ?? GetClassificationTypeWorker(ClassificationTypeNames.Text);
}
private IClassificationType GetClassificationTypeWorker(string name)
{
return _identityMap.TryGetValue(name, out var result)
? result
: _registryService.GetClassificationType(name);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Shared.Utilities
{
[Export]
internal class FSharpClassificationTypeMap
{
private readonly Dictionary<string, IClassificationType> _identityMap;
private readonly IClassificationTypeRegistryService _registryService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpClassificationTypeMap(IClassificationTypeRegistryService registryService)
{
_registryService = registryService;
// Prepopulate the identity map with the constant string values from ClassificationTypeNames
var fields = typeof(ClassificationTypeNames).GetFields();
_identityMap = new Dictionary<string, IClassificationType>(fields.Length, ReferenceEqualityComparer.Instance);
foreach (var field in fields)
{
// The strings returned from reflection do not have reference-identity
// with the string constants used by the compiler. Fortunately, a call
// to string.Intern fixes them.
var value = string.Intern((string)field.GetValue(null));
_identityMap.Add(value, registryService.GetClassificationType(value));
}
}
public IClassificationType GetClassificationType(string name)
{
var type = GetClassificationTypeWorker(name);
if (type == null)
{
FatalError.ReportAndCatch(new Exception($"classification type doesn't exist for {name}"));
}
return type ?? GetClassificationTypeWorker(ClassificationTypeNames.Text);
}
private IClassificationType GetClassificationTypeWorker(string name)
{
return _identityMap.TryGetValue(name, out var result)
? result
: _registryService.GetClassificationType(name);
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/EditorFeatures/Test/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexPatternDetectorTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.EmbeddedLanguages.RegularExpressions.LanguageServices
{
public class RegexPatternDetectorTests
{
private static void Match(string value, RegexOptions? expectedOptions = null, string prefix = "//")
{
var (matched, options) = RegexPatternDetector.TestAccessor.TryMatch(prefix + value);
Assert.True(matched);
if (expectedOptions != null)
{
Assert.Equal(expectedOptions.Value, options);
}
}
private static void NoMatch(string value, string prefix = "//")
{
var (matched, _) = RegexPatternDetector.TestAccessor.TryMatch(prefix + value);
Assert.False(matched);
}
[Fact]
public void TestSimpleForm()
=> Match("lang=regex");
[Fact]
public void TestSimpleFormVB()
=> Match("' lang=regex", prefix: "");
[Fact]
public void TestSimpleFormCSharpMultiLine()
=> Match("/* lang=regex", prefix: "");
[Fact]
public void TestEndingInP()
=> Match("lang=regexp");
[Fact]
public void TestLanguageForm()
=> Match("language=regex");
[Fact]
public void TestLanguageFormWithP()
=> Match("language=regexp");
[Fact]
public void TestLanguageFullySpelled()
=> NoMatch("languag=regexp");
[Fact]
public void TestSpacesAroundEquals()
=> Match("lang = regex");
[Fact]
public void TestSpacesAroundPieces()
=> Match(" lang=regex ");
[Fact]
public void TestSpacesAroundPiecesAndEquals()
=> Match(" lang = regex ");
[Fact]
public void TestSpaceBetweenRegexAndP()
=> Match("lang=regex p");
[Fact]
public void TestPeriodAtEnd()
=> Match("lang=regex.");
[Fact]
public void TestNotWithWordCharAtEnd()
=> NoMatch("lang=regexc");
[Fact]
public void TestWithNoNWordBeforeStart1()
=> NoMatch(":lang=regex");
[Fact]
public void TestWithNoNWordBeforeStart2()
=> NoMatch(": lang=regex");
[Fact]
public void TestNotWithWordCharAtStart()
=> NoMatch("clang=regex");
[Fact]
public void TestOption()
=> Match("lang=regex,ecmascript", RegexOptions.ECMAScript);
[Fact]
public void TestOptionWithSpaces()
=> Match("lang=regex , ecmascript", RegexOptions.ECMAScript);
[Fact]
public void TestOptionFollowedByPeriod()
=> Match("lang=regex,ecmascript. Explanation", RegexOptions.ECMAScript);
[Fact]
public void TestMultiOptionFollowedByPeriod()
=> Match("lang=regex,ecmascript,ignorecase. Explanation", RegexOptions.ECMAScript | RegexOptions.IgnoreCase);
[Fact]
public void TestMultiOptionFollowedByPeriod_CaseInsensitive()
=> Match("Language=Regexp,ECMAScript,IgnoreCase. Explanation", RegexOptions.ECMAScript | RegexOptions.IgnoreCase);
[Fact]
public void TestInvalidOption1()
=> NoMatch("lang=regex,ignore");
[Fact]
public void TestInvalidOption2()
=> NoMatch("lang=regex,ecmascript,ignore");
[Fact]
public void TestNotOnDocComment()
=> NoMatch("/// lang=regex,ignore", prefix: "");
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.EmbeddedLanguages.RegularExpressions.LanguageServices
{
public class RegexPatternDetectorTests
{
private static void Match(string value, RegexOptions? expectedOptions = null, string prefix = "//")
{
var (matched, options) = RegexPatternDetector.TestAccessor.TryMatch(prefix + value);
Assert.True(matched);
if (expectedOptions != null)
{
Assert.Equal(expectedOptions.Value, options);
}
}
private static void NoMatch(string value, string prefix = "//")
{
var (matched, _) = RegexPatternDetector.TestAccessor.TryMatch(prefix + value);
Assert.False(matched);
}
[Fact]
public void TestSimpleForm()
=> Match("lang=regex");
[Fact]
public void TestSimpleFormVB()
=> Match("' lang=regex", prefix: "");
[Fact]
public void TestSimpleFormCSharpMultiLine()
=> Match("/* lang=regex", prefix: "");
[Fact]
public void TestEndingInP()
=> Match("lang=regexp");
[Fact]
public void TestLanguageForm()
=> Match("language=regex");
[Fact]
public void TestLanguageFormWithP()
=> Match("language=regexp");
[Fact]
public void TestLanguageFullySpelled()
=> NoMatch("languag=regexp");
[Fact]
public void TestSpacesAroundEquals()
=> Match("lang = regex");
[Fact]
public void TestSpacesAroundPieces()
=> Match(" lang=regex ");
[Fact]
public void TestSpacesAroundPiecesAndEquals()
=> Match(" lang = regex ");
[Fact]
public void TestSpaceBetweenRegexAndP()
=> Match("lang=regex p");
[Fact]
public void TestPeriodAtEnd()
=> Match("lang=regex.");
[Fact]
public void TestNotWithWordCharAtEnd()
=> NoMatch("lang=regexc");
[Fact]
public void TestWithNoNWordBeforeStart1()
=> NoMatch(":lang=regex");
[Fact]
public void TestWithNoNWordBeforeStart2()
=> NoMatch(": lang=regex");
[Fact]
public void TestNotWithWordCharAtStart()
=> NoMatch("clang=regex");
[Fact]
public void TestOption()
=> Match("lang=regex,ecmascript", RegexOptions.ECMAScript);
[Fact]
public void TestOptionWithSpaces()
=> Match("lang=regex , ecmascript", RegexOptions.ECMAScript);
[Fact]
public void TestOptionFollowedByPeriod()
=> Match("lang=regex,ecmascript. Explanation", RegexOptions.ECMAScript);
[Fact]
public void TestMultiOptionFollowedByPeriod()
=> Match("lang=regex,ecmascript,ignorecase. Explanation", RegexOptions.ECMAScript | RegexOptions.IgnoreCase);
[Fact]
public void TestMultiOptionFollowedByPeriod_CaseInsensitive()
=> Match("Language=Regexp,ECMAScript,IgnoreCase. Explanation", RegexOptions.ECMAScript | RegexOptions.IgnoreCase);
[Fact]
public void TestInvalidOption1()
=> NoMatch("lang=regex,ignore");
[Fact]
public void TestInvalidOption2()
=> NoMatch("lang=regex,ecmascript,ignore");
[Fact]
public void TestNotOnDocComment()
=> NoMatch("/// lang=regex,ignore", prefix: "");
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ExpressionSyntaxExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class ExpressionSyntaxExtensions
{
public static ExpressionSyntax Parenthesize(
this ExpressionSyntax expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true)
{
// a 'ref' expression should never be parenthesized. It fundamentally breaks the code.
// This is because, from the language's perspective there is no such thing as a ref
// expression. instead, there are constructs like ```return ref expr``` or
// ```x ? ref expr1 : ref expr2```, or ```ref int a = ref expr``` in these cases, the
// ref's do not belong to the exprs, but instead belong to the parent construct. i.e.
// ```return ref``` or ``` ? ref ... : ref ... ``` or ``` ... = ref ...```. For
// parsing convenience, and to prevent having to update all these constructs, we settled
// on a ref-expression node. But this node isn't a true expression that be operated
// on like with everything else.
if (expression.IsKind(SyntaxKind.RefExpression))
{
return expression;
}
// Throw expressions are not permitted to be parenthesized:
//
// "a" ?? throw new ArgumentNullException()
//
// is legal whereas
//
// "a" ?? (throw new ArgumentNullException())
//
// is not.
if (expression.IsKind(SyntaxKind.ThrowExpression))
{
return expression;
}
var result = ParenthesizeWorker(expression, includeElasticTrivia);
return addSimplifierAnnotation
? result.WithAdditionalAnnotations(Simplifier.Annotation)
: result;
}
private static ExpressionSyntax ParenthesizeWorker(
this ExpressionSyntax expression, bool includeElasticTrivia)
{
var withoutTrivia = expression.WithoutTrivia();
var parenthesized = includeElasticTrivia
? SyntaxFactory.ParenthesizedExpression(withoutTrivia)
: SyntaxFactory.ParenthesizedExpression(
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty),
withoutTrivia,
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty));
return parenthesized.WithTriviaFrom(expression);
}
public static PatternSyntax Parenthesize(
this PatternSyntax pattern, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true)
{
var withoutTrivia = pattern.WithoutTrivia();
var parenthesized = includeElasticTrivia
? SyntaxFactory.ParenthesizedPattern(withoutTrivia)
: SyntaxFactory.ParenthesizedPattern(
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty),
withoutTrivia,
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty));
var result = parenthesized.WithTriviaFrom(pattern);
return addSimplifierAnnotation
? result.WithAdditionalAnnotations(Simplifier.Annotation)
: result;
}
public static CastExpressionSyntax Cast(
this ExpressionSyntax expression,
ITypeSymbol targetType)
{
var parenthesized = expression.Parenthesize();
var castExpression = SyntaxFactory.CastExpression(
targetType.GenerateTypeSyntax(), parenthesized.WithoutTrivia()).WithTriviaFrom(parenthesized);
return castExpression.WithAdditionalAnnotations(Simplifier.Annotation);
}
/// <summary>
/// Adds to <paramref name="targetType"/> if it does not contain an anonymous
/// type and binds to the same type at the given <paramref name="position"/>.
/// </summary>
public static ExpressionSyntax CastIfPossible(
this ExpressionSyntax expression,
ITypeSymbol targetType,
int position,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (targetType.ContainsAnonymousType())
{
return expression;
}
if (targetType.Kind == SymbolKind.DynamicType)
{
targetType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
}
var typeSyntax = targetType.GenerateTypeSyntax();
var type = semanticModel.GetSpeculativeTypeInfo(
position,
typeSyntax,
SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
if (!targetType.Equals(type))
{
return expression;
}
var castExpression = expression.Cast(targetType);
// Ensure that inserting the cast doesn't change the semantics.
var specAnalyzer = new SpeculationAnalyzer(expression, castExpression, semanticModel, cancellationToken);
var speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel;
if (speculativeSemanticModel == null)
{
return expression;
}
var speculatedCastExpression = (CastExpressionSyntax)specAnalyzer.ReplacedExpression;
if (!CastSimplifier.IsUnnecessaryCast(speculatedCastExpression, speculativeSemanticModel, cancellationToken))
{
return expression;
}
return castExpression;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class ExpressionSyntaxExtensions
{
public static ExpressionSyntax Parenthesize(
this ExpressionSyntax expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true)
{
// a 'ref' expression should never be parenthesized. It fundamentally breaks the code.
// This is because, from the language's perspective there is no such thing as a ref
// expression. instead, there are constructs like ```return ref expr``` or
// ```x ? ref expr1 : ref expr2```, or ```ref int a = ref expr``` in these cases, the
// ref's do not belong to the exprs, but instead belong to the parent construct. i.e.
// ```return ref``` or ``` ? ref ... : ref ... ``` or ``` ... = ref ...```. For
// parsing convenience, and to prevent having to update all these constructs, we settled
// on a ref-expression node. But this node isn't a true expression that be operated
// on like with everything else.
if (expression.IsKind(SyntaxKind.RefExpression))
{
return expression;
}
// Throw expressions are not permitted to be parenthesized:
//
// "a" ?? throw new ArgumentNullException()
//
// is legal whereas
//
// "a" ?? (throw new ArgumentNullException())
//
// is not.
if (expression.IsKind(SyntaxKind.ThrowExpression))
{
return expression;
}
var result = ParenthesizeWorker(expression, includeElasticTrivia);
return addSimplifierAnnotation
? result.WithAdditionalAnnotations(Simplifier.Annotation)
: result;
}
private static ExpressionSyntax ParenthesizeWorker(
this ExpressionSyntax expression, bool includeElasticTrivia)
{
var withoutTrivia = expression.WithoutTrivia();
var parenthesized = includeElasticTrivia
? SyntaxFactory.ParenthesizedExpression(withoutTrivia)
: SyntaxFactory.ParenthesizedExpression(
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty),
withoutTrivia,
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty));
return parenthesized.WithTriviaFrom(expression);
}
public static PatternSyntax Parenthesize(
this PatternSyntax pattern, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true)
{
var withoutTrivia = pattern.WithoutTrivia();
var parenthesized = includeElasticTrivia
? SyntaxFactory.ParenthesizedPattern(withoutTrivia)
: SyntaxFactory.ParenthesizedPattern(
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty),
withoutTrivia,
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty));
var result = parenthesized.WithTriviaFrom(pattern);
return addSimplifierAnnotation
? result.WithAdditionalAnnotations(Simplifier.Annotation)
: result;
}
public static CastExpressionSyntax Cast(
this ExpressionSyntax expression,
ITypeSymbol targetType)
{
var parenthesized = expression.Parenthesize();
var castExpression = SyntaxFactory.CastExpression(
targetType.GenerateTypeSyntax(), parenthesized.WithoutTrivia()).WithTriviaFrom(parenthesized);
return castExpression.WithAdditionalAnnotations(Simplifier.Annotation);
}
/// <summary>
/// Adds to <paramref name="targetType"/> if it does not contain an anonymous
/// type and binds to the same type at the given <paramref name="position"/>.
/// </summary>
public static ExpressionSyntax CastIfPossible(
this ExpressionSyntax expression,
ITypeSymbol targetType,
int position,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (targetType.ContainsAnonymousType())
{
return expression;
}
if (targetType.Kind == SymbolKind.DynamicType)
{
targetType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
}
var typeSyntax = targetType.GenerateTypeSyntax();
var type = semanticModel.GetSpeculativeTypeInfo(
position,
typeSyntax,
SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
if (!targetType.Equals(type))
{
return expression;
}
var castExpression = expression.Cast(targetType);
// Ensure that inserting the cast doesn't change the semantics.
var specAnalyzer = new SpeculationAnalyzer(expression, castExpression, semanticModel, cancellationToken);
var speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel;
if (speculativeSemanticModel == null)
{
return expression;
}
var speculatedCastExpression = (CastExpressionSyntax)specAnalyzer.ReplacedExpression;
if (!CastSimplifier.IsUnnecessaryCast(speculatedCastExpression, speculativeSemanticModel, cancellationToken))
{
return expression;
}
return castExpression;
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Features/Core/Portable/ExternalAccess/VSTypeScript/VSTypeScriptDocumentDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript
{
[DiagnosticAnalyzer(InternalLanguageNames.TypeScript)]
internal sealed class VSTypeScriptDocumentDiagnosticAnalyzer : DocumentDiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray<DiagnosticDescriptor>.Empty;
public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
var analyzer = document.Project.LanguageServices.GetRequiredService<VSTypeScriptDiagnosticAnalyzerLanguageService>().Implementation;
if (analyzer == null)
{
return SpecializedTasks.EmptyImmutableArray<Diagnostic>();
}
return analyzer.AnalyzeDocumentSyntaxAsync(document, cancellationToken);
}
public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken)
{
var analyzer = document.Project.LanguageServices.GetRequiredService<VSTypeScriptDiagnosticAnalyzerLanguageService>().Implementation;
if (analyzer == null)
{
return SpecializedTasks.EmptyImmutableArray<Diagnostic>();
}
return analyzer.AnalyzeDocumentSemanticsAsync(document, 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.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript
{
[DiagnosticAnalyzer(InternalLanguageNames.TypeScript)]
internal sealed class VSTypeScriptDocumentDiagnosticAnalyzer : DocumentDiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray<DiagnosticDescriptor>.Empty;
public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
var analyzer = document.Project.LanguageServices.GetRequiredService<VSTypeScriptDiagnosticAnalyzerLanguageService>().Implementation;
if (analyzer == null)
{
return SpecializedTasks.EmptyImmutableArray<Diagnostic>();
}
return analyzer.AnalyzeDocumentSyntaxAsync(document, cancellationToken);
}
public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken)
{
var analyzer = document.Project.LanguageServices.GetRequiredService<VSTypeScriptDiagnosticAnalyzerLanguageService>().Implementation;
if (analyzer == null)
{
return SpecializedTasks.EmptyImmutableArray<Diagnostic>();
}
return analyzer.AnalyzeDocumentSemanticsAsync(document, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.Analysis.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class ClosureConversion
{
/// <summary>
/// Perform a first analysis pass in preparation for removing all lambdas from a method body. The entry point is Analyze.
/// The results of analysis are placed in the fields seenLambda, blockParent, variableBlock, captured, and captures.
/// </summary>
internal sealed partial class Analysis
{
/// <summary>
/// If a local function is in the set, at some point in the code it is converted to a delegate and should then not be optimized to a struct closure.
/// Also contains all lambdas (as they are converted to delegates implicitly).
/// </summary>
public readonly PooledHashSet<MethodSymbol> MethodsConvertedToDelegates;
/// <summary>
/// True if the method signature can be rewritten to contain ref/out parameters.
/// </summary>
public bool CanTakeRefParameters(MethodSymbol function)
=> !function.IsAsync && !function.IsIterator
// We can't rewrite delegate signatures
&& !MethodsConvertedToDelegates.Contains(function);
/// <summary>
/// The root of the scope tree for this method.
/// </summary>
public readonly Scope ScopeTree;
private readonly MethodSymbol _topLevelMethod;
private readonly int _topLevelMethodOrdinal;
private readonly VariableSlotAllocator _slotAllocatorOpt;
private readonly TypeCompilationState _compilationState;
private Analysis(
Scope scopeTree,
PooledHashSet<MethodSymbol> methodsConvertedToDelegates,
MethodSymbol topLevelMethod,
int topLevelMethodOrdinal,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState)
{
ScopeTree = scopeTree;
MethodsConvertedToDelegates = methodsConvertedToDelegates;
_topLevelMethod = topLevelMethod;
_topLevelMethodOrdinal = topLevelMethodOrdinal;
_slotAllocatorOpt = slotAllocatorOpt;
_compilationState = compilationState;
}
public static Analysis Analyze(
BoundNode node,
MethodSymbol method,
int topLevelMethodOrdinal,
MethodSymbol substitutedSourceMethod,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState,
ArrayBuilder<ClosureDebugInfo> closureDebugInfo,
DiagnosticBag diagnostics)
{
var methodsConvertedToDelegates = PooledHashSet<MethodSymbol>.GetInstance();
var scopeTree = ScopeTreeBuilder.Build(
node,
method,
methodsConvertedToDelegates,
diagnostics);
Debug.Assert(scopeTree != null);
var analysis = new Analysis(
scopeTree,
methodsConvertedToDelegates,
method,
topLevelMethodOrdinal,
slotAllocatorOpt,
compilationState);
analysis.MakeAndAssignEnvironments();
analysis.ComputeLambdaScopesAndFrameCaptures();
if (compilationState.Compilation.Options.OptimizationLevel == OptimizationLevel.Release)
{
// This can affect when a variable is in scope whilst debugging, so only do this in release mode.
analysis.MergeEnvironments();
}
analysis.InlineThisOnlyEnvironments();
return analysis;
}
private static BoundNode FindNodeToAnalyze(BoundNode node)
{
while (true)
{
switch (node.Kind)
{
case BoundKind.SequencePoint:
node = ((BoundSequencePoint)node).StatementOpt;
break;
case BoundKind.SequencePointWithSpan:
node = ((BoundSequencePointWithSpan)node).StatementOpt;
break;
case BoundKind.Block:
case BoundKind.StatementList:
case BoundKind.FieldEqualsValue:
return node;
case BoundKind.GlobalStatementInitializer:
return ((BoundGlobalStatementInitializer)node).Statement;
default:
// Other node types should not appear at the top level
throw ExceptionUtilities.UnexpectedValue(node.Kind);
}
}
}
/// <summary>
/// Must be called only after <see cref="NestedFunction.CapturedEnvironments"/>
/// has been calculated.
///
/// Finds the most optimal capture environment to place a closure in.
/// This roughly corresponds to the 'highest' Scope in the tree where all
/// the captured variables for this closure are in scope. This minimizes
/// the number of indirections we may have to traverse to access captured
/// variables.
/// </summary>
private void ComputeLambdaScopesAndFrameCaptures()
{
VisitNestedFunctions(ScopeTree, (scope, function) =>
{
if (function.CapturedEnvironments.Count > 0)
{
var capturedEnvs = PooledHashSet<ClosureEnvironment>.GetInstance();
capturedEnvs.AddAll(function.CapturedEnvironments);
// Find the nearest captured class environment, if one exists
var curScope = scope;
while (curScope != null)
{
var env = curScope.DeclaredEnvironment;
if (!(env is null) && capturedEnvs.Remove(env) && !env.IsStruct)
{
function.ContainingEnvironmentOpt = env;
break;
}
curScope = curScope.Parent;
}
// Now we need to walk up the scopes to find environment captures
var oldEnv = curScope?.DeclaredEnvironment;
curScope = curScope?.Parent;
while (curScope != null)
{
if (capturedEnvs.Count == 0)
{
break;
}
var env = curScope.DeclaredEnvironment;
if (!(env is null))
{
if (!env.IsStruct)
{
Debug.Assert(!oldEnv.IsStruct);
oldEnv.CapturesParent = true;
oldEnv = env;
}
capturedEnvs.Remove(env);
}
curScope = curScope.Parent;
}
if (capturedEnvs.Count > 0)
{
throw ExceptionUtilities.Unreachable;
}
capturedEnvs.Free();
}
});
}
/// <summary>
/// We may have ended up with a closure environment containing only
/// 'this'. This is basically equivalent to the containing type itself,
/// so we can inline the 'this' parameter into environments that
/// reference this one or lower closures directly onto the containing
/// type.
/// </summary>
private void InlineThisOnlyEnvironments()
{
// First make sure 'this' even exists
if (!_topLevelMethod.TryGetThisParameter(out var thisParam) ||
thisParam == null)
{
return;
}
var env = ScopeTree.DeclaredEnvironment;
// If it does exist, 'this' is always in the top-level environment
if (env is null)
{
return;
}
// The environment must contain only 'this' to be inlined
if (env.CapturedVariables.Count > 1 ||
!env.CapturedVariables.Contains(thisParam))
{
return;
}
if (env.IsStruct)
{
// If everything that captures the 'this' environment
// lives in the containing type, we can remove the env
bool cantRemove = CheckNestedFunctions(ScopeTree, (scope, closure) =>
{
return closure.CapturedEnvironments.Contains(env) &&
closure.ContainingEnvironmentOpt != null;
});
if (!cantRemove)
{
RemoveEnv();
}
}
// If we are in a variant interface, runtime might not consider the
// method synthesized directly within the interface as variant safe.
// For simplicity we do not perform precise analysis whether this would
// definitely be the case. If we are in a variant interface, we always force
// creation of a display class.
else if (VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is null)
{
// Class-based 'this' closures can move member functions to
// the top-level type and environments which capture the 'this'
// environment can capture 'this' directly.
// Note: the top-level type is treated as the initial containing
// environment, so by removing the 'this' environment, all
// nested environments which captured a pointer to the 'this'
// environment will now capture 'this'
RemoveEnv();
VisitNestedFunctions(ScopeTree, (scope, closure) =>
{
if (closure.ContainingEnvironmentOpt == env)
{
closure.ContainingEnvironmentOpt = null;
}
});
}
void RemoveEnv()
{
ScopeTree.DeclaredEnvironment = null;
VisitNestedFunctions(ScopeTree, (scope, nested) =>
{
var index = nested.CapturedEnvironments.IndexOf(env);
if (index >= 0)
{
nested.CapturedEnvironments.RemoveAt(index);
}
});
}
}
private void MakeAndAssignEnvironments()
{
VisitScopeTree(ScopeTree, scope =>
{
// Currently all variables declared in the same scope are added
// to the same closure environment
var variablesInEnvironment = scope.DeclaredVariables;
// Don't create empty environments
if (variablesInEnvironment.Count == 0)
{
return;
}
// First walk the nested scopes to find all closures which
// capture variables from this scope. They all need to capture
// this environment. This includes closures which captured local
// functions that capture those variables, so multiple passes may
// be needed. This will also decide if the environment is a struct
// or a class.
// If we are in a variant interface, runtime might not consider the
// method synthesized directly within the interface as variant safe.
// For simplicity we do not perform precise analysis whether this would
// definitely be the case. If we are in a variant interface, we always force
// creation of a display class.
bool isStruct = VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is null;
var closures = new SetWithInsertionOrder<NestedFunction>();
bool addedItem;
// This loop is O(n), where n is the length of the chain
// L_1 <- L_2 <- L_3 ...
// where L_1 represents a local function that directly captures the current
// environment, L_2 represents a local function that directly captures L_1,
// L_3 represents a local function that captures L_2, and so on.
//
// Each iteration of the loop runs a visitor that is proportional to the
// number of closures in nested scopes, so we hope that the total number
// of nested functions and function chains is small in any real-world code.
do
{
addedItem = false;
VisitNestedFunctions(scope, (closureScope, closure) =>
{
if (!closures.Contains(closure) &&
(closure.CapturedVariables.Overlaps(scope.DeclaredVariables) ||
closure.CapturedVariables.Overlaps(closures.Select(c => c.OriginalMethodSymbol))))
{
closures.Add(closure);
addedItem = true;
isStruct &= CanTakeRefParameters(closure.OriginalMethodSymbol);
}
});
} while (addedItem == true);
// Next create the environment and add it to the declaration scope
var env = new ClosureEnvironment(variablesInEnvironment, isStruct);
Debug.Assert(scope.DeclaredEnvironment is null);
scope.DeclaredEnvironment = env;
_topLevelMethod.TryGetThisParameter(out var thisParam);
foreach (var closure in closures)
{
closure.CapturedEnvironments.Add(env);
if (thisParam != null && env.CapturedVariables.Contains(thisParam))
{
closure.CapturesThis = true;
}
}
});
}
/// <summary>
/// Calculates all functions which directly or indirectly capture a scope's variables.
/// </summary>
/// <returns></returns>
private PooledDictionary<Scope, PooledHashSet<NestedFunction>> CalculateFunctionsCapturingScopeVariables()
{
var closuresCapturingScopeVariables = PooledDictionary<Scope, PooledHashSet<NestedFunction>>.GetInstance();
// calculate functions which directly capture a scope
var environmentsToScopes = PooledDictionary<ClosureEnvironment, Scope>.GetInstance();
VisitScopeTree(ScopeTree, scope =>
{
if (!(scope.DeclaredEnvironment is null))
{
closuresCapturingScopeVariables[scope] = PooledHashSet<NestedFunction>.GetInstance();
environmentsToScopes[scope.DeclaredEnvironment] = scope;
}
foreach (var closure in scope.NestedFunctions)
{
foreach (var env in closure.CapturedEnvironments)
{
// A closure should only ever capture a scope which is an ancestor of its own,
// which we should have already visited
Debug.Assert(environmentsToScopes.ContainsKey(env));
closuresCapturingScopeVariables[environmentsToScopes[env]].Add(closure);
}
}
});
environmentsToScopes.Free();
// if a function captures a scope, which captures its parent, then the closure also captures the parents scope.
// we update closuresCapturingScopeVariables to reflect this.
foreach (var (scope, capturingClosures) in closuresCapturingScopeVariables)
{
if (scope.DeclaredEnvironment is null)
continue;
var currentScope = scope;
while (currentScope.DeclaredEnvironment is null || currentScope.DeclaredEnvironment.CapturesParent)
{
currentScope = currentScope.Parent;
if (currentScope == null)
{
throw ExceptionUtilities.Unreachable;
}
if (currentScope.DeclaredEnvironment is null ||
currentScope.DeclaredEnvironment.IsStruct)
{
continue;
}
closuresCapturingScopeVariables[currentScope].AddAll(capturingClosures);
}
}
return closuresCapturingScopeVariables;
}
/// <summary>
/// Must be called only after <see cref="MakeAndAssignEnvironments"/> and <see cref="ComputeLambdaScopesAndFrameCaptures"/>.
///
/// In order to reduce allocations, merge environments into a parent environment when it is safe to do so.
/// This must be done whilst preserving semantics.
///
/// We also have to make sure not to extend the life of any variable.
/// This means that we can only merge an environment into its parent if exactly the same closures directly or indirectly reference both environments.
/// </summary>
private void MergeEnvironments()
{
var closuresCapturingScopeVariables = CalculateFunctionsCapturingScopeVariables();
// now we merge environments into their parent environments if it is safe to do so
foreach (var (scope, closuresCapturingScope) in closuresCapturingScopeVariables)
{
if (closuresCapturingScope.Count == 0)
continue;
var scopeEnv = scope.DeclaredEnvironment;
// structs don't allocate, so no point merging them
if (scopeEnv.IsStruct)
continue;
var bestScope = scope;
var currentScope = scope;
// Walk up the scope tree, checking at each point if it is:
// a) semantically safe to merge the scope's environment into it's parent scope's environment
// b) doing so would not change GC behaviour
// Once either of these conditions fails, we merge into the closure environment furthest up the scope tree we've found so far
while (currentScope.Parent != null)
{
if (!currentScope.CanMergeWithParent)
break;
var parentScope = currentScope.Parent;
// we skip any scopes which do not have any captured variables, and try to merge into the parent scope instead.
// We also skip any struct environments as they don't allocate, so no point merging them
var env = parentScope.DeclaredEnvironment;
if (env is null || env.IsStruct)
{
currentScope = parentScope;
continue;
}
var closuresCapturingParentScope = closuresCapturingScopeVariables[parentScope];
// if more closures reference one scope's environments than the other scope's environments,
// then merging the two environments would increase the number of objects referencing some variables,
// which may prevent the variables being garbage collected.
if (!closuresCapturingParentScope.SetEquals(closuresCapturingScope))
break;
bestScope = parentScope;
currentScope = parentScope;
}
if (bestScope == scope) // no better scope was found, so continue
continue;
// do the actual work of merging the closure environments
var targetEnv = bestScope.DeclaredEnvironment;
foreach (var variable in scopeEnv.CapturedVariables)
{
targetEnv.CapturedVariables.Add(variable);
}
scope.DeclaredEnvironment = null;
foreach (var closure in closuresCapturingScope)
{
closure.CapturedEnvironments.Remove(scopeEnv);
if (!closure.CapturedEnvironments.Contains(targetEnv))
{
closure.CapturedEnvironments.Add(targetEnv);
}
if (closure.ContainingEnvironmentOpt == scopeEnv)
{
closure.ContainingEnvironmentOpt = targetEnv;
}
}
}
// cleanup
foreach (var set in closuresCapturingScopeVariables.Values)
{
set.Free();
}
closuresCapturingScopeVariables.Free();
}
internal DebugId GetTopLevelMethodId()
{
return _slotAllocatorOpt?.MethodId ?? new DebugId(_topLevelMethodOrdinal, _compilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
internal DebugId GetClosureId(SyntaxNode syntax, ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
{
Debug.Assert(syntax != null);
DebugId closureId;
DebugId previousClosureId;
if (_slotAllocatorOpt != null && _slotAllocatorOpt.TryGetPreviousClosure(syntax, out previousClosureId))
{
closureId = previousClosureId;
}
else
{
closureId = new DebugId(closureDebugInfo.Count, _compilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
int syntaxOffset = _topLevelMethod.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree);
closureDebugInfo.Add(new ClosureDebugInfo(syntaxOffset, closureId));
return closureId;
}
/// <summary>
/// Walk up the scope tree looking for a variable declaration.
/// </summary>
public static Scope GetVariableDeclarationScope(Scope startingScope, Symbol variable)
{
if (variable is ParameterSymbol p && p.IsThis)
{
return null;
}
var currentScope = startingScope;
while (currentScope != null)
{
switch (variable.Kind)
{
case SymbolKind.Parameter:
case SymbolKind.Local:
if (currentScope.DeclaredVariables.Contains(variable))
{
return currentScope;
}
break;
case SymbolKind.Method:
foreach (var function in currentScope.NestedFunctions)
{
if (function.OriginalMethodSymbol == variable)
{
return currentScope;
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(variable.Kind);
}
currentScope = currentScope.Parent;
}
return null;
}
/// <summary>
/// Find the parent <see cref="Scope"/> of the <see cref="Scope"/> corresponding to
/// the given <see cref="BoundNode"/>.
/// </summary>
public static Scope GetScopeParent(Scope treeRoot, BoundNode scopeNode)
{
var correspondingScope = GetScopeWithMatchingBoundNode(treeRoot, scopeNode);
return correspondingScope.Parent;
}
/// <summary>
/// Finds a <see cref="Scope" /> with a matching <see cref="BoundNode"/>
/// as the one given.
/// </summary>
public static Scope GetScopeWithMatchingBoundNode(Scope treeRoot, BoundNode node)
{
return Helper(treeRoot) ?? throw ExceptionUtilities.Unreachable;
Scope Helper(Scope currentScope)
{
if (currentScope.BoundNode == node)
{
return currentScope;
}
foreach (var nestedScope in currentScope.NestedScopes)
{
var found = Helper(nestedScope);
if (found != null)
{
return found;
}
}
return null;
}
}
/// <summary>
/// Walk up the scope tree looking for a nested function.
/// </summary>
/// <returns>
/// A tuple of the found <see cref="NestedFunction"/> and the <see cref="Scope"/> it was found in.
/// </returns>
public static (NestedFunction, Scope) GetVisibleNestedFunction(Scope startingScope, MethodSymbol functionSymbol)
{
var currentScope = startingScope;
while (currentScope != null)
{
foreach (var function in currentScope.NestedFunctions)
{
if (function.OriginalMethodSymbol == functionSymbol)
{
return (function, currentScope);
}
}
currentScope = currentScope.Parent;
}
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Finds a <see cref="NestedFunction"/> with a matching original symbol somewhere in the given scope or nested scopes.
/// </summary>
public static NestedFunction GetNestedFunctionInTree(Scope treeRoot, MethodSymbol functionSymbol)
{
return helper(treeRoot) ?? throw ExceptionUtilities.Unreachable;
NestedFunction helper(Scope scope)
{
foreach (var function in scope.NestedFunctions)
{
if (function.OriginalMethodSymbol == functionSymbol)
{
return function;
}
}
foreach (var nestedScope in scope.NestedScopes)
{
var found = helper(nestedScope);
if (found != null)
{
return found;
}
}
return null;
}
}
public void Free()
{
MethodsConvertedToDelegates.Free();
ScopeTree.Free();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class ClosureConversion
{
/// <summary>
/// Perform a first analysis pass in preparation for removing all lambdas from a method body. The entry point is Analyze.
/// The results of analysis are placed in the fields seenLambda, blockParent, variableBlock, captured, and captures.
/// </summary>
internal sealed partial class Analysis
{
/// <summary>
/// If a local function is in the set, at some point in the code it is converted to a delegate and should then not be optimized to a struct closure.
/// Also contains all lambdas (as they are converted to delegates implicitly).
/// </summary>
public readonly PooledHashSet<MethodSymbol> MethodsConvertedToDelegates;
/// <summary>
/// True if the method signature can be rewritten to contain ref/out parameters.
/// </summary>
public bool CanTakeRefParameters(MethodSymbol function)
=> !function.IsAsync && !function.IsIterator
// We can't rewrite delegate signatures
&& !MethodsConvertedToDelegates.Contains(function);
/// <summary>
/// The root of the scope tree for this method.
/// </summary>
public readonly Scope ScopeTree;
private readonly MethodSymbol _topLevelMethod;
private readonly int _topLevelMethodOrdinal;
private readonly VariableSlotAllocator _slotAllocatorOpt;
private readonly TypeCompilationState _compilationState;
private Analysis(
Scope scopeTree,
PooledHashSet<MethodSymbol> methodsConvertedToDelegates,
MethodSymbol topLevelMethod,
int topLevelMethodOrdinal,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState)
{
ScopeTree = scopeTree;
MethodsConvertedToDelegates = methodsConvertedToDelegates;
_topLevelMethod = topLevelMethod;
_topLevelMethodOrdinal = topLevelMethodOrdinal;
_slotAllocatorOpt = slotAllocatorOpt;
_compilationState = compilationState;
}
public static Analysis Analyze(
BoundNode node,
MethodSymbol method,
int topLevelMethodOrdinal,
MethodSymbol substitutedSourceMethod,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState,
ArrayBuilder<ClosureDebugInfo> closureDebugInfo,
DiagnosticBag diagnostics)
{
var methodsConvertedToDelegates = PooledHashSet<MethodSymbol>.GetInstance();
var scopeTree = ScopeTreeBuilder.Build(
node,
method,
methodsConvertedToDelegates,
diagnostics);
Debug.Assert(scopeTree != null);
var analysis = new Analysis(
scopeTree,
methodsConvertedToDelegates,
method,
topLevelMethodOrdinal,
slotAllocatorOpt,
compilationState);
analysis.MakeAndAssignEnvironments();
analysis.ComputeLambdaScopesAndFrameCaptures();
if (compilationState.Compilation.Options.OptimizationLevel == OptimizationLevel.Release)
{
// This can affect when a variable is in scope whilst debugging, so only do this in release mode.
analysis.MergeEnvironments();
}
analysis.InlineThisOnlyEnvironments();
return analysis;
}
private static BoundNode FindNodeToAnalyze(BoundNode node)
{
while (true)
{
switch (node.Kind)
{
case BoundKind.SequencePoint:
node = ((BoundSequencePoint)node).StatementOpt;
break;
case BoundKind.SequencePointWithSpan:
node = ((BoundSequencePointWithSpan)node).StatementOpt;
break;
case BoundKind.Block:
case BoundKind.StatementList:
case BoundKind.FieldEqualsValue:
return node;
case BoundKind.GlobalStatementInitializer:
return ((BoundGlobalStatementInitializer)node).Statement;
default:
// Other node types should not appear at the top level
throw ExceptionUtilities.UnexpectedValue(node.Kind);
}
}
}
/// <summary>
/// Must be called only after <see cref="NestedFunction.CapturedEnvironments"/>
/// has been calculated.
///
/// Finds the most optimal capture environment to place a closure in.
/// This roughly corresponds to the 'highest' Scope in the tree where all
/// the captured variables for this closure are in scope. This minimizes
/// the number of indirections we may have to traverse to access captured
/// variables.
/// </summary>
private void ComputeLambdaScopesAndFrameCaptures()
{
VisitNestedFunctions(ScopeTree, (scope, function) =>
{
if (function.CapturedEnvironments.Count > 0)
{
var capturedEnvs = PooledHashSet<ClosureEnvironment>.GetInstance();
capturedEnvs.AddAll(function.CapturedEnvironments);
// Find the nearest captured class environment, if one exists
var curScope = scope;
while (curScope != null)
{
var env = curScope.DeclaredEnvironment;
if (!(env is null) && capturedEnvs.Remove(env) && !env.IsStruct)
{
function.ContainingEnvironmentOpt = env;
break;
}
curScope = curScope.Parent;
}
// Now we need to walk up the scopes to find environment captures
var oldEnv = curScope?.DeclaredEnvironment;
curScope = curScope?.Parent;
while (curScope != null)
{
if (capturedEnvs.Count == 0)
{
break;
}
var env = curScope.DeclaredEnvironment;
if (!(env is null))
{
if (!env.IsStruct)
{
Debug.Assert(!oldEnv.IsStruct);
oldEnv.CapturesParent = true;
oldEnv = env;
}
capturedEnvs.Remove(env);
}
curScope = curScope.Parent;
}
if (capturedEnvs.Count > 0)
{
throw ExceptionUtilities.Unreachable;
}
capturedEnvs.Free();
}
});
}
/// <summary>
/// We may have ended up with a closure environment containing only
/// 'this'. This is basically equivalent to the containing type itself,
/// so we can inline the 'this' parameter into environments that
/// reference this one or lower closures directly onto the containing
/// type.
/// </summary>
private void InlineThisOnlyEnvironments()
{
// First make sure 'this' even exists
if (!_topLevelMethod.TryGetThisParameter(out var thisParam) ||
thisParam == null)
{
return;
}
var env = ScopeTree.DeclaredEnvironment;
// If it does exist, 'this' is always in the top-level environment
if (env is null)
{
return;
}
// The environment must contain only 'this' to be inlined
if (env.CapturedVariables.Count > 1 ||
!env.CapturedVariables.Contains(thisParam))
{
return;
}
if (env.IsStruct)
{
// If everything that captures the 'this' environment
// lives in the containing type, we can remove the env
bool cantRemove = CheckNestedFunctions(ScopeTree, (scope, closure) =>
{
return closure.CapturedEnvironments.Contains(env) &&
closure.ContainingEnvironmentOpt != null;
});
if (!cantRemove)
{
RemoveEnv();
}
}
// If we are in a variant interface, runtime might not consider the
// method synthesized directly within the interface as variant safe.
// For simplicity we do not perform precise analysis whether this would
// definitely be the case. If we are in a variant interface, we always force
// creation of a display class.
else if (VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is null)
{
// Class-based 'this' closures can move member functions to
// the top-level type and environments which capture the 'this'
// environment can capture 'this' directly.
// Note: the top-level type is treated as the initial containing
// environment, so by removing the 'this' environment, all
// nested environments which captured a pointer to the 'this'
// environment will now capture 'this'
RemoveEnv();
VisitNestedFunctions(ScopeTree, (scope, closure) =>
{
if (closure.ContainingEnvironmentOpt == env)
{
closure.ContainingEnvironmentOpt = null;
}
});
}
void RemoveEnv()
{
ScopeTree.DeclaredEnvironment = null;
VisitNestedFunctions(ScopeTree, (scope, nested) =>
{
var index = nested.CapturedEnvironments.IndexOf(env);
if (index >= 0)
{
nested.CapturedEnvironments.RemoveAt(index);
}
});
}
}
private void MakeAndAssignEnvironments()
{
VisitScopeTree(ScopeTree, scope =>
{
// Currently all variables declared in the same scope are added
// to the same closure environment
var variablesInEnvironment = scope.DeclaredVariables;
// Don't create empty environments
if (variablesInEnvironment.Count == 0)
{
return;
}
// First walk the nested scopes to find all closures which
// capture variables from this scope. They all need to capture
// this environment. This includes closures which captured local
// functions that capture those variables, so multiple passes may
// be needed. This will also decide if the environment is a struct
// or a class.
// If we are in a variant interface, runtime might not consider the
// method synthesized directly within the interface as variant safe.
// For simplicity we do not perform precise analysis whether this would
// definitely be the case. If we are in a variant interface, we always force
// creation of a display class.
bool isStruct = VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is null;
var closures = new SetWithInsertionOrder<NestedFunction>();
bool addedItem;
// This loop is O(n), where n is the length of the chain
// L_1 <- L_2 <- L_3 ...
// where L_1 represents a local function that directly captures the current
// environment, L_2 represents a local function that directly captures L_1,
// L_3 represents a local function that captures L_2, and so on.
//
// Each iteration of the loop runs a visitor that is proportional to the
// number of closures in nested scopes, so we hope that the total number
// of nested functions and function chains is small in any real-world code.
do
{
addedItem = false;
VisitNestedFunctions(scope, (closureScope, closure) =>
{
if (!closures.Contains(closure) &&
(closure.CapturedVariables.Overlaps(scope.DeclaredVariables) ||
closure.CapturedVariables.Overlaps(closures.Select(c => c.OriginalMethodSymbol))))
{
closures.Add(closure);
addedItem = true;
isStruct &= CanTakeRefParameters(closure.OriginalMethodSymbol);
}
});
} while (addedItem == true);
// Next create the environment and add it to the declaration scope
var env = new ClosureEnvironment(variablesInEnvironment, isStruct);
Debug.Assert(scope.DeclaredEnvironment is null);
scope.DeclaredEnvironment = env;
_topLevelMethod.TryGetThisParameter(out var thisParam);
foreach (var closure in closures)
{
closure.CapturedEnvironments.Add(env);
if (thisParam != null && env.CapturedVariables.Contains(thisParam))
{
closure.CapturesThis = true;
}
}
});
}
/// <summary>
/// Calculates all functions which directly or indirectly capture a scope's variables.
/// </summary>
/// <returns></returns>
private PooledDictionary<Scope, PooledHashSet<NestedFunction>> CalculateFunctionsCapturingScopeVariables()
{
var closuresCapturingScopeVariables = PooledDictionary<Scope, PooledHashSet<NestedFunction>>.GetInstance();
// calculate functions which directly capture a scope
var environmentsToScopes = PooledDictionary<ClosureEnvironment, Scope>.GetInstance();
VisitScopeTree(ScopeTree, scope =>
{
if (!(scope.DeclaredEnvironment is null))
{
closuresCapturingScopeVariables[scope] = PooledHashSet<NestedFunction>.GetInstance();
environmentsToScopes[scope.DeclaredEnvironment] = scope;
}
foreach (var closure in scope.NestedFunctions)
{
foreach (var env in closure.CapturedEnvironments)
{
// A closure should only ever capture a scope which is an ancestor of its own,
// which we should have already visited
Debug.Assert(environmentsToScopes.ContainsKey(env));
closuresCapturingScopeVariables[environmentsToScopes[env]].Add(closure);
}
}
});
environmentsToScopes.Free();
// if a function captures a scope, which captures its parent, then the closure also captures the parents scope.
// we update closuresCapturingScopeVariables to reflect this.
foreach (var (scope, capturingClosures) in closuresCapturingScopeVariables)
{
if (scope.DeclaredEnvironment is null)
continue;
var currentScope = scope;
while (currentScope.DeclaredEnvironment is null || currentScope.DeclaredEnvironment.CapturesParent)
{
currentScope = currentScope.Parent;
if (currentScope == null)
{
throw ExceptionUtilities.Unreachable;
}
if (currentScope.DeclaredEnvironment is null ||
currentScope.DeclaredEnvironment.IsStruct)
{
continue;
}
closuresCapturingScopeVariables[currentScope].AddAll(capturingClosures);
}
}
return closuresCapturingScopeVariables;
}
/// <summary>
/// Must be called only after <see cref="MakeAndAssignEnvironments"/> and <see cref="ComputeLambdaScopesAndFrameCaptures"/>.
///
/// In order to reduce allocations, merge environments into a parent environment when it is safe to do so.
/// This must be done whilst preserving semantics.
///
/// We also have to make sure not to extend the life of any variable.
/// This means that we can only merge an environment into its parent if exactly the same closures directly or indirectly reference both environments.
/// </summary>
private void MergeEnvironments()
{
var closuresCapturingScopeVariables = CalculateFunctionsCapturingScopeVariables();
// now we merge environments into their parent environments if it is safe to do so
foreach (var (scope, closuresCapturingScope) in closuresCapturingScopeVariables)
{
if (closuresCapturingScope.Count == 0)
continue;
var scopeEnv = scope.DeclaredEnvironment;
// structs don't allocate, so no point merging them
if (scopeEnv.IsStruct)
continue;
var bestScope = scope;
var currentScope = scope;
// Walk up the scope tree, checking at each point if it is:
// a) semantically safe to merge the scope's environment into it's parent scope's environment
// b) doing so would not change GC behaviour
// Once either of these conditions fails, we merge into the closure environment furthest up the scope tree we've found so far
while (currentScope.Parent != null)
{
if (!currentScope.CanMergeWithParent)
break;
var parentScope = currentScope.Parent;
// we skip any scopes which do not have any captured variables, and try to merge into the parent scope instead.
// We also skip any struct environments as they don't allocate, so no point merging them
var env = parentScope.DeclaredEnvironment;
if (env is null || env.IsStruct)
{
currentScope = parentScope;
continue;
}
var closuresCapturingParentScope = closuresCapturingScopeVariables[parentScope];
// if more closures reference one scope's environments than the other scope's environments,
// then merging the two environments would increase the number of objects referencing some variables,
// which may prevent the variables being garbage collected.
if (!closuresCapturingParentScope.SetEquals(closuresCapturingScope))
break;
bestScope = parentScope;
currentScope = parentScope;
}
if (bestScope == scope) // no better scope was found, so continue
continue;
// do the actual work of merging the closure environments
var targetEnv = bestScope.DeclaredEnvironment;
foreach (var variable in scopeEnv.CapturedVariables)
{
targetEnv.CapturedVariables.Add(variable);
}
scope.DeclaredEnvironment = null;
foreach (var closure in closuresCapturingScope)
{
closure.CapturedEnvironments.Remove(scopeEnv);
if (!closure.CapturedEnvironments.Contains(targetEnv))
{
closure.CapturedEnvironments.Add(targetEnv);
}
if (closure.ContainingEnvironmentOpt == scopeEnv)
{
closure.ContainingEnvironmentOpt = targetEnv;
}
}
}
// cleanup
foreach (var set in closuresCapturingScopeVariables.Values)
{
set.Free();
}
closuresCapturingScopeVariables.Free();
}
internal DebugId GetTopLevelMethodId()
{
return _slotAllocatorOpt?.MethodId ?? new DebugId(_topLevelMethodOrdinal, _compilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
internal DebugId GetClosureId(SyntaxNode syntax, ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
{
Debug.Assert(syntax != null);
DebugId closureId;
DebugId previousClosureId;
if (_slotAllocatorOpt != null && _slotAllocatorOpt.TryGetPreviousClosure(syntax, out previousClosureId))
{
closureId = previousClosureId;
}
else
{
closureId = new DebugId(closureDebugInfo.Count, _compilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
int syntaxOffset = _topLevelMethod.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree);
closureDebugInfo.Add(new ClosureDebugInfo(syntaxOffset, closureId));
return closureId;
}
/// <summary>
/// Walk up the scope tree looking for a variable declaration.
/// </summary>
public static Scope GetVariableDeclarationScope(Scope startingScope, Symbol variable)
{
if (variable is ParameterSymbol p && p.IsThis)
{
return null;
}
var currentScope = startingScope;
while (currentScope != null)
{
switch (variable.Kind)
{
case SymbolKind.Parameter:
case SymbolKind.Local:
if (currentScope.DeclaredVariables.Contains(variable))
{
return currentScope;
}
break;
case SymbolKind.Method:
foreach (var function in currentScope.NestedFunctions)
{
if (function.OriginalMethodSymbol == variable)
{
return currentScope;
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(variable.Kind);
}
currentScope = currentScope.Parent;
}
return null;
}
/// <summary>
/// Find the parent <see cref="Scope"/> of the <see cref="Scope"/> corresponding to
/// the given <see cref="BoundNode"/>.
/// </summary>
public static Scope GetScopeParent(Scope treeRoot, BoundNode scopeNode)
{
var correspondingScope = GetScopeWithMatchingBoundNode(treeRoot, scopeNode);
return correspondingScope.Parent;
}
/// <summary>
/// Finds a <see cref="Scope" /> with a matching <see cref="BoundNode"/>
/// as the one given.
/// </summary>
public static Scope GetScopeWithMatchingBoundNode(Scope treeRoot, BoundNode node)
{
return Helper(treeRoot) ?? throw ExceptionUtilities.Unreachable;
Scope Helper(Scope currentScope)
{
if (currentScope.BoundNode == node)
{
return currentScope;
}
foreach (var nestedScope in currentScope.NestedScopes)
{
var found = Helper(nestedScope);
if (found != null)
{
return found;
}
}
return null;
}
}
/// <summary>
/// Walk up the scope tree looking for a nested function.
/// </summary>
/// <returns>
/// A tuple of the found <see cref="NestedFunction"/> and the <see cref="Scope"/> it was found in.
/// </returns>
public static (NestedFunction, Scope) GetVisibleNestedFunction(Scope startingScope, MethodSymbol functionSymbol)
{
var currentScope = startingScope;
while (currentScope != null)
{
foreach (var function in currentScope.NestedFunctions)
{
if (function.OriginalMethodSymbol == functionSymbol)
{
return (function, currentScope);
}
}
currentScope = currentScope.Parent;
}
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Finds a <see cref="NestedFunction"/> with a matching original symbol somewhere in the given scope or nested scopes.
/// </summary>
public static NestedFunction GetNestedFunctionInTree(Scope treeRoot, MethodSymbol functionSymbol)
{
return helper(treeRoot) ?? throw ExceptionUtilities.Unreachable;
NestedFunction helper(Scope scope)
{
foreach (var function in scope.NestedFunctions)
{
if (function.OriginalMethodSymbol == functionSymbol)
{
return function;
}
}
foreach (var nestedScope in scope.NestedScopes)
{
var found = helper(nestedScope);
if (found != null)
{
return found;
}
}
return null;
}
}
public void Free()
{
MethodsConvertedToDelegates.Free();
ScopeTree.Free();
}
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/VisualStudio/Core/Def/Implementation/AnalyzerDependency/IgnorableAssemblyNamePrefixList.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal sealed class IgnorableAssemblyNamePrefixList : IIgnorableAssemblyList
{
private readonly string _prefix;
public IgnorableAssemblyNamePrefixList(string prefix)
{
Debug.Assert(prefix != null);
_prefix = prefix;
}
public bool Includes(AssemblyIdentity assemblyIdentity)
=> assemblyIdentity.Name.StartsWith(_prefix);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal sealed class IgnorableAssemblyNamePrefixList : IIgnorableAssemblyList
{
private readonly string _prefix;
public IgnorableAssemblyNamePrefixList(string prefix)
{
Debug.Assert(prefix != null);
_prefix = prefix;
}
public bool Includes(AssemblyIdentity assemblyIdentity)
=> assemblyIdentity.Name.StartsWith(_prefix);
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/AbstractDocumentationCommentService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Linq;
using System.Threading;
using Roslyn.Utilities;
using System.Text;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal abstract class AbstractDocumentationCommentService<
TDocumentationCommentTriviaSyntax,
TXmlNodeSyntax,
TXmlAttributeSyntax,
TCrefSyntax,
TXmlElementSyntax,
TXmlTextSyntax,
TXmlEmptyElementSyntax,
TXmlCrefAttributeSyntax,
TXmlNameAttributeSyntax,
TXmlTextAttributeSyntax> : IDocumentationCommentService
where TDocumentationCommentTriviaSyntax : SyntaxNode
where TXmlNodeSyntax : SyntaxNode
where TXmlAttributeSyntax : SyntaxNode
where TCrefSyntax : SyntaxNode
where TXmlElementSyntax : TXmlNodeSyntax
where TXmlTextSyntax : TXmlNodeSyntax
where TXmlEmptyElementSyntax : TXmlNodeSyntax
where TXmlCrefAttributeSyntax : TXmlAttributeSyntax
where TXmlNameAttributeSyntax : TXmlAttributeSyntax
where TXmlTextAttributeSyntax : TXmlAttributeSyntax
{
public const string Ellipsis = "...";
private readonly ISyntaxFacts _syntaxFacts;
protected AbstractDocumentationCommentService(ISyntaxFacts syntaxFacts)
=> _syntaxFacts = syntaxFacts;
private static void AddSpaceIfNotAlreadyThere(StringBuilder sb)
{
if (sb.Length > 0 && sb[sb.Length - 1] != ' ')
{
sb.Append(' ');
}
}
private string GetDocumentationCommentPrefix(TDocumentationCommentTriviaSyntax documentationComment)
{
Contract.ThrowIfNull(documentationComment);
var leadingTrivia = documentationComment.GetLeadingTrivia();
var exteriorTrivia = leadingTrivia.Where(t => _syntaxFacts.IsDocumentationCommentExteriorTrivia(t))
.FirstOrNull();
return exteriorTrivia != null ? exteriorTrivia.Value.ToString() : string.Empty;
}
public string GetBannerText(
TDocumentationCommentTriviaSyntax documentationComment, int maxBannerLength, CancellationToken cancellationToken)
{
// TODO: Consider unifying code to extract text from an Xml Documentation Comment (https://github.com/dotnet/roslyn/issues/2290)
var summaryElement =
documentationComment.ChildNodes().OfType<TXmlElementSyntax>()
.FirstOrDefault(e => GetName(e).ToString() == "summary");
var prefix = GetDocumentationCommentPrefix(documentationComment);
string text;
if (summaryElement != null)
{
var sb = new StringBuilder(summaryElement.Span.Length);
sb.Append(prefix);
sb.Append(" <summary>");
HandleElement(summaryElement, sb);
text = sb.ToString().Trim();
}
else
{
// If a summary element isn't found, use the first line of the XML doc comment.
var syntaxTree = documentationComment.SyntaxTree;
var spanStart = documentationComment.SpanStart;
var line = syntaxTree.GetText(cancellationToken).Lines.GetLineFromPosition(spanStart);
text = prefix + " " + line.ToString().Substring(spanStart - line.Start).Trim() + " " + Ellipsis;
}
if (text.Length > maxBannerLength)
{
text = text.Substring(0, maxBannerLength) + " " + Ellipsis;
}
return text;
}
private void HandleElement(TXmlElementSyntax summaryElement, StringBuilder sb)
{
foreach (var node in summaryElement.ChildNodes())
{
HandleNode(node, sb);
}
}
private void HandleNode(SyntaxNode node, StringBuilder sb)
{
if (node.HasLeadingTrivia)
{
// Collapse all trailing trivia to a single space.
AddSpaceIfNotAlreadyThere(sb);
}
if (node is TXmlTextSyntax xmlText)
{
var textTokens = GetTextTokens(xmlText);
AppendTextTokens(sb, textTokens);
}
else if (node is TXmlElementSyntax xmlElement)
{
HandleElement(xmlElement, sb);
}
else if (node is TXmlEmptyElementSyntax xmlEmpty)
{
foreach (var attribute in GetAttributes(xmlEmpty))
{
switch (attribute)
{
case TXmlCrefAttributeSyntax xmlCref:
AddSpaceIfNotAlreadyThere(sb);
sb.Append(GetCref(xmlCref).ToString());
break;
case TXmlNameAttributeSyntax xmlName:
AddSpaceIfNotAlreadyThere(sb);
sb.Append(GetIdentifier(xmlName).Text);
break;
case TXmlTextAttributeSyntax xmlTextAttribute:
AddSpaceIfNotAlreadyThere(sb);
AppendTextTokens(sb, GetTextTokens(xmlTextAttribute));
break;
default:
Debug.Assert(false, $"Unexpected XML syntax kind {attribute.RawKind}");
break;
}
}
}
if (node.HasTrailingTrivia)
{
// Collapse all trailing trivia to a single space.
AddSpaceIfNotAlreadyThere(sb);
}
}
protected abstract SyntaxToken GetIdentifier(TXmlNameAttributeSyntax xmlName);
protected abstract TCrefSyntax GetCref(TXmlCrefAttributeSyntax xmlCref);
protected abstract SyntaxList<TXmlAttributeSyntax> GetAttributes(TXmlEmptyElementSyntax xmlEmpty);
protected abstract SyntaxTokenList GetTextTokens(TXmlTextSyntax xmlText);
protected abstract SyntaxTokenList GetTextTokens(TXmlTextAttributeSyntax xmlTextAttribute);
protected abstract SyntaxNode GetName(TXmlElementSyntax xmlElement);
private static void AppendTextTokens(StringBuilder sb, SyntaxTokenList textTokens)
{
foreach (var token in textTokens)
{
var tokenText = token.ToString();
// Collapse all preceding trivia or whitespace for this token to a single space.
if (token.LeadingTrivia.Count > 0 || HasLeadingWhitespace(tokenText))
{
AddSpaceIfNotAlreadyThere(sb);
}
sb.Append(tokenText.Trim());
// Collapse all trailing trivia or whitespace for this token to a single space.
if (token.TrailingTrivia.Count > 0 || HasTrailingWhitespace(tokenText))
{
AddSpaceIfNotAlreadyThere(sb);
}
}
}
private static bool HasLeadingWhitespace(string tokenText)
=> tokenText.Length > 0 && char.IsWhiteSpace(tokenText[0]);
private static bool HasTrailingWhitespace(string tokenText)
=> tokenText.Length > 0 && char.IsWhiteSpace(tokenText[tokenText.Length - 1]);
public string GetBannerText(SyntaxNode documentationCommentTriviaSyntax, int maxBannerLength, CancellationToken cancellationToken)
=> GetBannerText((TDocumentationCommentTriviaSyntax)documentationCommentTriviaSyntax, maxBannerLength, cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Roslyn.Utilities;
using System.Text;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal abstract class AbstractDocumentationCommentService<
TDocumentationCommentTriviaSyntax,
TXmlNodeSyntax,
TXmlAttributeSyntax,
TCrefSyntax,
TXmlElementSyntax,
TXmlTextSyntax,
TXmlEmptyElementSyntax,
TXmlCrefAttributeSyntax,
TXmlNameAttributeSyntax,
TXmlTextAttributeSyntax> : IDocumentationCommentService
where TDocumentationCommentTriviaSyntax : SyntaxNode
where TXmlNodeSyntax : SyntaxNode
where TXmlAttributeSyntax : SyntaxNode
where TCrefSyntax : SyntaxNode
where TXmlElementSyntax : TXmlNodeSyntax
where TXmlTextSyntax : TXmlNodeSyntax
where TXmlEmptyElementSyntax : TXmlNodeSyntax
where TXmlCrefAttributeSyntax : TXmlAttributeSyntax
where TXmlNameAttributeSyntax : TXmlAttributeSyntax
where TXmlTextAttributeSyntax : TXmlAttributeSyntax
{
public const string Ellipsis = "...";
private readonly ISyntaxFacts _syntaxFacts;
protected AbstractDocumentationCommentService(ISyntaxFacts syntaxFacts)
=> _syntaxFacts = syntaxFacts;
private static void AddSpaceIfNotAlreadyThere(StringBuilder sb)
{
if (sb.Length > 0 && sb[sb.Length - 1] != ' ')
{
sb.Append(' ');
}
}
private string GetDocumentationCommentPrefix(TDocumentationCommentTriviaSyntax documentationComment)
{
Contract.ThrowIfNull(documentationComment);
var leadingTrivia = documentationComment.GetLeadingTrivia();
var exteriorTrivia = leadingTrivia.Where(t => _syntaxFacts.IsDocumentationCommentExteriorTrivia(t))
.FirstOrNull();
return exteriorTrivia != null ? exteriorTrivia.Value.ToString() : string.Empty;
}
public string GetBannerText(
TDocumentationCommentTriviaSyntax documentationComment, int maxBannerLength, CancellationToken cancellationToken)
{
// TODO: Consider unifying code to extract text from an Xml Documentation Comment (https://github.com/dotnet/roslyn/issues/2290)
var summaryElement =
documentationComment.ChildNodes().OfType<TXmlElementSyntax>()
.FirstOrDefault(e => GetName(e).ToString() == "summary");
var prefix = GetDocumentationCommentPrefix(documentationComment);
string text;
if (summaryElement != null)
{
var sb = new StringBuilder(summaryElement.Span.Length);
sb.Append(prefix);
sb.Append(" <summary>");
HandleElement(summaryElement, sb);
text = sb.ToString().Trim();
}
else
{
// If a summary element isn't found, use the first line of the XML doc comment.
var syntaxTree = documentationComment.SyntaxTree;
var spanStart = documentationComment.SpanStart;
var line = syntaxTree.GetText(cancellationToken).Lines.GetLineFromPosition(spanStart);
text = prefix + " " + line.ToString().Substring(spanStart - line.Start).Trim() + " " + Ellipsis;
}
if (text.Length > maxBannerLength)
{
text = text.Substring(0, maxBannerLength) + " " + Ellipsis;
}
return text;
}
private void HandleElement(TXmlElementSyntax summaryElement, StringBuilder sb)
{
foreach (var node in summaryElement.ChildNodes())
{
HandleNode(node, sb);
}
}
private void HandleNode(SyntaxNode node, StringBuilder sb)
{
if (node.HasLeadingTrivia)
{
// Collapse all trailing trivia to a single space.
AddSpaceIfNotAlreadyThere(sb);
}
if (node is TXmlTextSyntax xmlText)
{
var textTokens = GetTextTokens(xmlText);
AppendTextTokens(sb, textTokens);
}
else if (node is TXmlElementSyntax xmlElement)
{
HandleElement(xmlElement, sb);
}
else if (node is TXmlEmptyElementSyntax xmlEmpty)
{
foreach (var attribute in GetAttributes(xmlEmpty))
{
switch (attribute)
{
case TXmlCrefAttributeSyntax xmlCref:
AddSpaceIfNotAlreadyThere(sb);
sb.Append(GetCref(xmlCref).ToString());
break;
case TXmlNameAttributeSyntax xmlName:
AddSpaceIfNotAlreadyThere(sb);
sb.Append(GetIdentifier(xmlName).Text);
break;
case TXmlTextAttributeSyntax xmlTextAttribute:
AddSpaceIfNotAlreadyThere(sb);
AppendTextTokens(sb, GetTextTokens(xmlTextAttribute));
break;
default:
Debug.Assert(false, $"Unexpected XML syntax kind {attribute.RawKind}");
break;
}
}
}
if (node.HasTrailingTrivia)
{
// Collapse all trailing trivia to a single space.
AddSpaceIfNotAlreadyThere(sb);
}
}
protected abstract SyntaxToken GetIdentifier(TXmlNameAttributeSyntax xmlName);
protected abstract TCrefSyntax GetCref(TXmlCrefAttributeSyntax xmlCref);
protected abstract SyntaxList<TXmlAttributeSyntax> GetAttributes(TXmlEmptyElementSyntax xmlEmpty);
protected abstract SyntaxTokenList GetTextTokens(TXmlTextSyntax xmlText);
protected abstract SyntaxTokenList GetTextTokens(TXmlTextAttributeSyntax xmlTextAttribute);
protected abstract SyntaxNode GetName(TXmlElementSyntax xmlElement);
private static void AppendTextTokens(StringBuilder sb, SyntaxTokenList textTokens)
{
foreach (var token in textTokens)
{
var tokenText = token.ToString();
// Collapse all preceding trivia or whitespace for this token to a single space.
if (token.LeadingTrivia.Count > 0 || HasLeadingWhitespace(tokenText))
{
AddSpaceIfNotAlreadyThere(sb);
}
sb.Append(tokenText.Trim());
// Collapse all trailing trivia or whitespace for this token to a single space.
if (token.TrailingTrivia.Count > 0 || HasTrailingWhitespace(tokenText))
{
AddSpaceIfNotAlreadyThere(sb);
}
}
}
private static bool HasLeadingWhitespace(string tokenText)
=> tokenText.Length > 0 && char.IsWhiteSpace(tokenText[0]);
private static bool HasTrailingWhitespace(string tokenText)
=> tokenText.Length > 0 && char.IsWhiteSpace(tokenText[tokenText.Length - 1]);
public string GetBannerText(SyntaxNode documentationCommentTriviaSyntax, int maxBannerLength, CancellationToken cancellationToken)
=> GetBannerText((TDocumentationCommentTriviaSyntax)documentationCommentTriviaSyntax, maxBannerLength, cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Tools/IdeCoreBenchmarks/CloudCache/IdeCoreBenchmarksCloudCacheServiceProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.CodeAnalysis.Storage.CloudCache;
using Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks;
namespace CloudCache
{
[ExportWorkspaceService(typeof(ICloudCacheStorageServiceFactory), ServiceLayer.Host), Shared]
internal class IdeCoreBenchmarksCloudCacheServiceProvider : ICloudCacheStorageServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public IdeCoreBenchmarksCloudCacheServiceProvider()
{
Console.WriteLine($"Instantiated {nameof(IdeCoreBenchmarksCloudCacheServiceProvider)}");
}
public AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService)
{
return new MockCloudCachePersistentStorageService(
locationService, @"C:\github\roslyn", cs =>
{
if (cs is IAsyncDisposable asyncDisposable)
{
asyncDisposable.DisposeAsync().AsTask().Wait();
}
else if (cs is IDisposable disposable)
{
disposable.Dispose();
}
});
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Storage;
using Microsoft.CodeAnalysis.Storage.CloudCache;
using Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks;
namespace CloudCache
{
[ExportWorkspaceService(typeof(ICloudCacheStorageServiceFactory), ServiceLayer.Host), Shared]
internal class IdeCoreBenchmarksCloudCacheServiceProvider : ICloudCacheStorageServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public IdeCoreBenchmarksCloudCacheServiceProvider()
{
Console.WriteLine($"Instantiated {nameof(IdeCoreBenchmarksCloudCacheServiceProvider)}");
}
public AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService)
{
return new MockCloudCachePersistentStorageService(
locationService, @"C:\github\roslyn", cs =>
{
if (cs is IAsyncDisposable asyncDisposable)
{
asyncDisposable.DisposeAsync().AsTask().Wait();
}
else if (cs is IDisposable disposable)
{
disposable.Dispose();
}
});
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Compilers/Core/CodeAnalysisTest/Collections/ImmutableSegmentedListTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://raw.githubusercontent.com/dotnet/runtime/v6.0.0-preview.5.21301.5/src/libraries/System.Collections.Immutable/tests/ImmutableListTest.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Collections;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public class ImmutableSegmentedListTest : ImmutableListTestBase
{
private enum Operation
{
Add,
AddRange,
Insert,
InsertRange,
RemoveAt,
RemoveRange,
Last,
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = RandomOperationsCount;
var expected = new List<int>();
var actual = ImmutableSegmentedList<int>.Empty;
int seed = unchecked((int)DateTime.Now.Ticks);
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Debug.WriteLine("Adding \"{0}\" to the list.", value);
expected.Add(value);
actual = actual.Add(value);
break;
case Operation.AddRange:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Debug.WriteLine("Adding {0} elements to the list.", inputLength);
expected.AddRange(values);
actual = actual.AddRange(values);
break;
case Operation.Insert:
int position = random.Next(expected.Count + 1);
value = random.Next();
Debug.WriteLine("Adding \"{0}\" to position {1} in the list.", value, position);
expected.Insert(position, value);
actual = actual.Insert(position, value);
break;
case Operation.InsertRange:
inputLength = random.Next(100);
values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
position = random.Next(expected.Count + 1);
Debug.WriteLine("Adding {0} elements to position {1} in the list.", inputLength, position);
expected.InsertRange(position, values);
actual = actual.InsertRange(position, values);
break;
case Operation.RemoveAt:
if (expected.Count > 0)
{
position = random.Next(expected.Count);
Debug.WriteLine("Removing element at position {0} from the list.", position);
expected.RemoveAt(position);
actual = actual.RemoveAt(position);
}
break;
case Operation.RemoveRange:
position = random.Next(expected.Count);
inputLength = random.Next(expected.Count - position);
Debug.WriteLine("Removing {0} elements starting at position {1} from the list.", inputLength, position);
expected.RemoveRange(position, inputLength);
actual = actual.RemoveRange(position, inputLength);
break;
}
Assert.Equal<int>(expected, actual);
}
}
[Fact]
public void EmptyTest()
{
var empty = ImmutableSegmentedList<GenericParameterHelper?>.Empty;
Assert.True(IsSame(empty, ImmutableSegmentedList<GenericParameterHelper>.Empty));
Assert.True(IsSame(empty, empty.Clear()));
Assert.True(IsSame(empty, ((System.Collections.Immutable.IImmutableList<GenericParameterHelper>)empty).Clear()));
Assert.True(empty.IsEmpty);
Assert.Equal(0, empty.Count);
Assert.Equal(-1, empty.IndexOf(new GenericParameterHelper()));
Assert.Equal(-1, empty.IndexOf(null));
}
[Fact]
public void GetHashCodeVariesByInstance()
{
Assert.NotEqual(ImmutableSegmentedList.Create<int>().GetHashCode(), ImmutableSegmentedList.Create(5).GetHashCode());
}
[Fact]
public void AddAndIndexerTest()
{
var list = ImmutableSegmentedList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
Assert.False(list.IsEmpty);
Assert.Equal(i, list.Count);
}
for (int i = 1; i <= 10; i++)
{
Assert.Equal(i * 10, list[i - 1]);
}
var bulkList = ImmutableSegmentedList<int>.Empty.AddRange(Enumerable.Range(1, 10).Select(i => i * 10));
Assert.Equal<int>(list.ToArray(), bulkList.ToArray());
}
[Fact]
public void AddRangeTest()
{
var list = ImmutableSegmentedList<int>.Empty;
list = list.AddRange(new[] { 1, 2, 3 });
list = list.AddRange(Enumerable.Range(4, 2));
list = list.AddRange(ImmutableSegmentedList<int>.Empty.AddRange(new[] { 6, 7, 8 }));
list = list.AddRange(new int[0]);
list = list.AddRange(ImmutableSegmentedList<int>.Empty.AddRange(Enumerable.Range(9, 1000)));
Assert.Equal(Enumerable.Range(1, 1008), list);
}
[Fact]
public void AddRange_IOrderedCollection()
{
var list = ImmutableSegmentedList<int>.Empty;
ImmutableSegmentedList<int>.Builder builder = ImmutableSegmentedList.CreateBuilder<int>();
builder.Add(1);
list = list.AddRange(builder);
Assert.Equal(new int[] { 1 }, list);
}
[Fact]
public void AddRangeOptimizationsTest()
{
// All these optimizations are tested based on filling an empty list.
var emptyList = ImmutableSegmentedList.Create<string>();
// Adding an empty list to an empty list should yield the original list.
Assert.True(IsSame(emptyList, emptyList.AddRange(new string[0])));
// Adding a non-empty immutable list to an empty one should return the added list.
var nonEmptyListDefaultComparer = ImmutableSegmentedList.Create("5");
Assert.True(IsSame(nonEmptyListDefaultComparer, emptyList.AddRange(nonEmptyListDefaultComparer)));
// Adding a Builder instance to an empty list should be seen through.
var builderOfNonEmptyListDefaultComparer = nonEmptyListDefaultComparer.ToBuilder();
Assert.True(IsSame(nonEmptyListDefaultComparer, emptyList.AddRange(builderOfNonEmptyListDefaultComparer)));
}
[Fact]
public void AddRangeBalanceTest()
{
int randSeed = unchecked((int)DateTime.Now.Ticks);
Debug.WriteLine("Random seed: {0}", randSeed);
var random = new Random(randSeed);
int expectedTotalSize = 0;
var list = ImmutableSegmentedList<int>.Empty;
// Add some small batches, verifying balance after each
for (int i = 0; i < 128; i++)
{
int batchSize = random.Next(32);
Debug.WriteLine("Adding {0} elements to the list", batchSize);
list = list.AddRange(Enumerable.Range(expectedTotalSize + 1, batchSize));
expectedTotalSize += batchSize;
}
// Add a single large batch to the end
int largeBatchSize = random.Next(32768) + 32768;
Debug.WriteLine("Adding {0} elements to the list", largeBatchSize);
list = list.AddRange(Enumerable.Range(expectedTotalSize + 1, largeBatchSize));
expectedTotalSize += largeBatchSize;
Assert.Equal(Enumerable.Range(1, expectedTotalSize), list);
}
[Fact]
public void InsertRangeRandomBalanceTest()
{
int randSeed = unchecked((int)DateTime.Now.Ticks);
Debug.WriteLine("Random seed: {0}", randSeed);
var random = new Random(randSeed);
var immutableList = ImmutableSegmentedList.CreateBuilder<int>();
var list = new List<int>();
const int maxBatchSize = 32;
int valueCounter = 0;
for (int i = 0; i < 24; i++)
{
int startPosition = random.Next(list.Count + 1);
int length = random.Next(maxBatchSize + 1);
int[] values = new int[length];
for (int j = 0; j < length; j++)
{
values[j] = ++valueCounter;
}
immutableList.InsertRange(startPosition, values);
list.InsertRange(startPosition, values);
Assert.Equal(list, immutableList);
}
}
[Fact]
public void InsertTest()
{
var list = ImmutableSegmentedList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(1, 5));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(-1, 5));
list = list.Insert(0, 10);
list = list.Insert(1, 20);
list = list.Insert(2, 30);
list = list.Insert(2, 25);
list = list.Insert(1, 15);
list = list.Insert(0, 5);
Assert.Equal(6, list.Count);
var expectedList = new[] { 5, 10, 15, 20, 25, 30 };
var actualList = list.ToArray();
Assert.Equal<int>(expectedList, actualList);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(7, 5));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(-1, 5));
}
[Fact]
public void InsertBalanceTest()
{
var list = ImmutableSegmentedList.Create(1);
list = list.Insert(0, 2);
list = list.Insert(1, 3);
}
[Fact]
public void InsertRangeTest()
{
var list = ImmutableSegmentedList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(1, new[] { 1 }));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, new[] { 1 }));
list = list.InsertRange(0, new[] { 1, 4, 5 });
list = list.InsertRange(1, new[] { 2, 3 });
list = list.InsertRange(2, new int[0]);
Assert.Equal(Enumerable.Range(1, 5), list);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(6, new[] { 1 }));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, new[] { 1 }));
}
[Fact]
public void InsertRangeImmutableTest()
{
var list = ImmutableSegmentedList<int>.Empty;
var nonEmptyList = ImmutableSegmentedList.Create(1);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(1, nonEmptyList));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, nonEmptyList));
list = list.InsertRange(0, ImmutableSegmentedList.Create(1, 104, 105));
list = list.InsertRange(1, ImmutableSegmentedList.Create(2, 3));
list = list.InsertRange(2, ImmutableSegmentedList<int>.Empty);
list = list.InsertRange(3, ImmutableSegmentedList<int>.Empty.InsertRange(0, Enumerable.Range(4, 100)));
Assert.Equal(Enumerable.Range(1, 105), list);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(106, nonEmptyList));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, nonEmptyList));
}
[Fact]
public void NullHandlingTest()
{
var list = ImmutableSegmentedList<GenericParameterHelper?>.Empty;
Assert.False(list.Contains(null));
Assert.Equal(-1, list.IndexOf(null));
list = list.Add((GenericParameterHelper?)null);
Assert.Equal(1, list.Count);
Assert.Null(list[0]);
Assert.True(list.Contains(null));
Assert.Equal(0, list.IndexOf(null));
list = list.Remove((GenericParameterHelper?)null);
Assert.Equal(0, list.Count);
Assert.True(list.IsEmpty);
Assert.False(list.Contains(null));
Assert.Equal(-1, list.IndexOf(null));
}
[Fact]
public void Remove_NullEqualityComparer()
{
var collection = ImmutableSegmentedList.Create(1, 2, 3);
var modified = collection.Remove(2, null);
Assert.Equal(new[] { 1, 3 }, modified);
// Try again through the explicit interface implementation.
System.Collections.Immutable.IImmutableList<int> collectionIface = collection;
var modified2 = collectionIface.Remove(2, null);
Assert.Equal(new[] { 1, 3 }, modified2);
}
[Fact]
public void RemoveTest()
{
ImmutableSegmentedList<int> list = ImmutableSegmentedList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
}
list = list.Remove(30);
Assert.Equal(9, list.Count);
Assert.False(list.Contains(30));
list = list.Remove(100);
Assert.Equal(8, list.Count);
Assert.False(list.Contains(100));
list = list.Remove(10);
Assert.Equal(7, list.Count);
Assert.False(list.Contains(10));
var removeList = new int[] { 20, 70 };
list = list.RemoveAll(removeList.Contains);
Assert.Equal(5, list.Count);
Assert.False(list.Contains(20));
Assert.False(list.Contains(70));
System.Collections.Immutable.IImmutableList<int> list2 = ImmutableSegmentedList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list2 = list2.Add(i * 10);
}
list2 = System.Collections.Immutable.ImmutableList.Remove(list2, 30);
Assert.Equal(9, list2.Count);
Assert.False(list2.Contains(30));
list2 = System.Collections.Immutable.ImmutableList.Remove(list2, 100);
Assert.Equal(8, list2.Count);
Assert.False(list2.Contains(100));
list2 = System.Collections.Immutable.ImmutableList.Remove(list2, 10);
Assert.Equal(7, list2.Count);
Assert.False(list2.Contains(10));
list2 = list2.RemoveAll(removeList.Contains);
Assert.Equal(5, list2.Count);
Assert.False(list2.Contains(20));
Assert.False(list2.Contains(70));
}
[Fact]
public void RemoveNonExistentKeepsReference()
{
var list = ImmutableSegmentedList<int>.Empty;
Assert.True(IsSame(list, list.Remove(3)));
}
/// <summary>
/// Verifies that RemoveRange does not enumerate its argument if the list is empty
/// and therefore could not possibly have any elements to remove anyway.
/// </summary>
/// <remarks>
/// While this would seem an implementation detail and simply an optimization,
/// it turns out that changing this behavior now *could* represent a breaking change
/// because if the enumerable were to throw an exception, that exception would not be
/// observed previously, but would start to be thrown if this behavior changed.
/// So this is a test to lock the behavior in place.
/// </remarks>
/// <!--<seealso cref="ImmutableSetTest.ExceptDoesEnumerateSequenceIfThisIsEmpty"/>-->
[Fact]
public void RemoveRangeDoesNotEnumerateSequenceIfThisIsEmpty()
{
var list = ImmutableSegmentedList<int>.Empty;
list.RemoveRange(Enumerable.Range(1, 1).Select<int, int>(n => { throw ExceptionUtilities.Unreachable; }));
}
[Fact]
public void RemoveAtTest()
{
var list = ImmutableSegmentedList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveAt(1));
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
}
list = list.RemoveAt(2);
Assert.Equal(9, list.Count);
Assert.False(list.Contains(30));
list = list.RemoveAt(8);
Assert.Equal(8, list.Count);
Assert.False(list.Contains(100));
list = list.RemoveAt(0);
Assert.Equal(7, list.Count);
Assert.False(list.Contains(10));
}
[Fact]
public void IndexOfAndContainsTest()
{
var expectedList = new List<string>(new[] { "Microsoft", "Windows", "Bing", "Visual Studio", "Comics", "Computers", "Laptops" });
var list = ImmutableSegmentedList<string>.Empty;
foreach (string newElement in expectedList)
{
Assert.False(list.Contains(newElement));
list = list.Add(newElement);
Assert.True(list.Contains(newElement));
Assert.Equal(expectedList.IndexOf(newElement), list.IndexOf(newElement));
Assert.Equal(expectedList.IndexOf(newElement), System.Collections.Immutable.ImmutableList.IndexOf(list, newElement.ToUpperInvariant(), StringComparer.OrdinalIgnoreCase));
Assert.Equal(-1, list.IndexOf(newElement.ToUpperInvariant()));
foreach (string existingElement in expectedList.TakeWhile(v => v != newElement))
{
Assert.True(list.Contains(existingElement));
Assert.Equal(expectedList.IndexOf(existingElement), list.IndexOf(existingElement));
Assert.Equal(expectedList.IndexOf(existingElement), System.Collections.Immutable.ImmutableList.IndexOf(list, existingElement.ToUpperInvariant(), StringComparer.OrdinalIgnoreCase));
Assert.Equal(-1, list.IndexOf(existingElement.ToUpperInvariant()));
}
}
}
[Fact]
public void Indexer()
{
var list = ImmutableSegmentedList.CreateRange(Enumerable.Range(1, 3));
Assert.Equal(1, list[0]);
Assert.Equal(2, list[1]);
Assert.Equal(3, list[2]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list[3]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list[-1]);
Assert.Equal(3, ((IList)list)[2]);
Assert.Equal(3, ((IList<int>)list)[2]);
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableSegmentedList.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => System.Collections.Immutable.ImmutableList.IndexOf(b, v, i),
(b, v, i, c) => System.Collections.Immutable.ImmutableList.IndexOf(b, v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
IndexOfTests.IndexOfTest(
seq => (System.Collections.Immutable.IImmutableList<int>)ImmutableSegmentedList.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => System.Collections.Immutable.ImmutableList.IndexOf(b, v, i),
(b, v, i, c) => System.Collections.Immutable.ImmutableList.IndexOf(b, v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableSegmentedList.CreateRange(seq),
(b, v) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v),
(b, v, eq) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, eq),
(b, v, i) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, i),
(b, v, i, c) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
IndexOfTests.LastIndexOfTest(
seq => (System.Collections.Immutable.IImmutableList<int>)ImmutableSegmentedList.CreateRange(seq),
(b, v) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v),
(b, v, eq) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, eq),
(b, v, i) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, i),
(b, v, i, c) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void ReplaceTest()
{
// Verify replace at beginning, middle, and end.
var list = ImmutableSegmentedList<int>.Empty.Add(3).Add(5).Add(8);
Assert.Equal<int>(new[] { 4, 5, 8 }, list.Replace(3, 4));
Assert.Equal<int>(new[] { 3, 6, 8 }, list.Replace(5, 6));
Assert.Equal<int>(new[] { 3, 5, 9 }, list.Replace(8, 9));
Assert.Equal<int>(new[] { 4, 5, 8 }, System.Collections.Immutable.ImmutableList.Replace((System.Collections.Immutable.IImmutableList<int>)list, 3, 4));
Assert.Equal<int>(new[] { 3, 6, 8 }, System.Collections.Immutable.ImmutableList.Replace((System.Collections.Immutable.IImmutableList<int>)list, 5, 6));
Assert.Equal<int>(new[] { 3, 5, 9 }, System.Collections.Immutable.ImmutableList.Replace((System.Collections.Immutable.IImmutableList<int>)list, 8, 9));
// Verify replacement of first element when there are duplicates.
list = ImmutableSegmentedList<int>.Empty.Add(3).Add(3).Add(5);
Assert.Equal<int>(new[] { 4, 3, 5 }, list.Replace(3, 4));
Assert.Equal<int>(new[] { 4, 4, 5 }, list.Replace(3, 4).Replace(3, 4));
Assert.Equal<int>(new[] { 4, 3, 5 }, System.Collections.Immutable.ImmutableList.Replace((System.Collections.Immutable.IImmutableList<int>)list, 3, 4));
Assert.Equal<int>(new[] { 4, 4, 5 }, System.Collections.Immutable.ImmutableList.Replace(System.Collections.Immutable.ImmutableList.Replace((System.Collections.Immutable.IImmutableList<int>)list, 3, 4), 3, 4));
}
[Fact]
public void ReplaceWithEqualityComparerTest()
{
var list = ImmutableSegmentedList.Create(new Person { Name = "Andrew", Age = 20 });
var newAge = new Person { Name = "Andrew", Age = 21 };
var updatedList = list.Replace(newAge, newAge, new NameOnlyEqualityComparer());
Assert.Equal(newAge.Age, updatedList[0].Age);
// Try again with a null equality comparer, which should use the default EQ.
updatedList = list.Replace(list[0], newAge);
Assert.False(IsSame(list, updatedList));
// Finally, try one last time using the interface implementation.
System.Collections.Immutable.IImmutableList<Person> iface = list;
var updatedIface = System.Collections.Immutable.ImmutableList.Replace(iface, list[0], newAge);
Assert.NotSame(iface, updatedIface);
}
[Fact]
public void ReplaceMissingThrowsTest()
{
Assert.Throws<ArgumentException>("oldValue", () => ImmutableSegmentedList<int>.Empty.Replace(5, 3));
}
[Fact]
public void EqualsTest()
{
Assert.False(ImmutableSegmentedList<int>.Empty.Equals(null));
Assert.False(ImmutableSegmentedList<int>.Empty.Equals("hi"));
Assert.True(ImmutableSegmentedList<int>.Empty.Equals(ImmutableSegmentedList<int>.Empty));
Assert.False(ImmutableSegmentedList<int>.Empty.Add(3).Equals(ImmutableSegmentedList<int>.Empty.Add(3)));
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
ImmutableSegmentedList<string> list = ImmutableSegmentedList.Create<string>();
Assert.Equal(0, list.Count);
list = ImmutableSegmentedList.Create("a");
Assert.Equal(1, list.Count);
list = ImmutableSegmentedList.Create("a", "b");
Assert.Equal(2, list.Count);
list = ImmutableSegmentedList.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, list.Count);
}
[Fact]
public void ToImmutableList()
{
ImmutableSegmentedList<string> list = new[] { "a", "b" }.ToImmutableSegmentedList();
Assert.Equal(2, list.Count);
list = new[] { "a", "b" }.ToImmutableSegmentedList();
Assert.Equal(2, list.Count);
}
[Fact]
public void ToImmutableListOfSameType()
{
var list = ImmutableSegmentedList.Create("a");
Assert.True(IsSame(list, list.ToImmutableSegmentedList()));
}
[Fact]
public void RemoveAllNullTest()
{
Assert.Throws<ArgumentNullException>("match", () => ImmutableSegmentedList<int>.Empty.RemoveAll(null!));
}
[Fact]
public void RemoveRangeArrayTest()
{
Assert.True(ImmutableSegmentedList<int>.Empty.RemoveRange(0, 0).IsEmpty);
var list = ImmutableSegmentedList.Create(1, 2, 3);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveRange(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>("count", () => list.RemoveRange(0, -1));
Assert.Throws<ArgumentException>(() => list.RemoveRange(4, 0));
Assert.Throws<ArgumentException>(() => list.RemoveRange(0, 4));
Assert.Throws<ArgumentException>(() => list.RemoveRange(2, 2));
Assert.Equal(list, list.RemoveRange(3, 0));
}
[Fact]
public void RemoveRange_EnumerableEqualityComparer_AcceptsNullEQ()
{
var list = ImmutableSegmentedList.Create(1, 2, 3);
var removed2eq = list.RemoveRange(new[] { 2 }, null);
Assert.Equal(2, removed2eq.Count);
Assert.Equal(new[] { 1, 3 }, removed2eq);
}
[Fact]
public void RemoveRangeEnumerableTest()
{
var list = ImmutableSegmentedList.Create(1, 2, 3);
Assert.Throws<ArgumentNullException>("items", () => list.RemoveRange(null!));
ImmutableSegmentedList<int> removed2 = list.RemoveRange(new[] { 2 });
Assert.Equal(2, removed2.Count);
Assert.Equal(new[] { 1, 3 }, removed2);
ImmutableSegmentedList<int> removed13 = list.RemoveRange(new[] { 1, 3, 5 });
Assert.Equal(1, removed13.Count);
Assert.Equal(new[] { 2 }, removed13);
Assert.Equal(new[] { 2 }, System.Collections.Immutable.ImmutableList.RemoveRange((System.Collections.Immutable.IImmutableList<int>)list, new[] { 1, 3, 5 }));
Assert.True(IsSame(list, list.RemoveRange(new[] { 5 })));
Assert.True(IsSame(ImmutableSegmentedList.Create<int>(), ImmutableSegmentedList.Create<int>().RemoveRange(new[] { 1 })));
var listWithDuplicates = ImmutableSegmentedList.Create(1, 2, 2, 3);
Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(new[] { 2 }));
Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2 }));
Assert.Throws<ArgumentNullException>("items", () => System.Collections.Immutable.ImmutableList.RemoveRange((System.Collections.Immutable.IImmutableList<int>)ImmutableSegmentedList.Create(1, 2, 3), null!));
Assert.Equal(new[] { 1, 3 }, System.Collections.Immutable.ImmutableList.RemoveRange((System.Collections.Immutable.IImmutableList<int>)ImmutableSegmentedList.Create(1, 2, 3), new[] { 2 }));
}
[Fact]
public void EnumeratorTest()
{
var list = ImmutableSegmentedList.Create("a");
var enumerator = list.GetEnumerator();
Assert.Null(enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Null(enumerator.Current);
enumerator.Reset();
Assert.Null(enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Null(enumerator.Current);
enumerator.Dispose();
enumerator.Reset();
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSegmentedList.Create(1);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
enumerator.Dispose();
Assert.False(enumerator.MoveNext());
enumerator.Reset();
Assert.Equal(0, enumerator.Current);
Assert.True(enumeratorCopy.MoveNext());
enumeratorCopy.Reset();
Assert.Equal(0, enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(collection[0], enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void ReverseTest2()
{
var emptyList = ImmutableSegmentedList.Create<int>();
Assert.True(IsSame(emptyList, emptyList.Reverse()));
var populatedList = ImmutableSegmentedList.Create(3, 2, 1);
Assert.Equal(Enumerable.Range(1, 3), populatedList.Reverse());
}
[Fact]
public void SetItem()
{
var emptyList = ImmutableSegmentedList.Create<int>();
Assert.Throws<ArgumentOutOfRangeException>("index", () => emptyList[-1]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => emptyList[0]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => emptyList[1]);
var listOfOne = emptyList.Add(5);
Assert.Throws<ArgumentOutOfRangeException>("index", () => listOfOne[-1]);
Assert.Equal(5, listOfOne[0]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => listOfOne[1]);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = ImmutableSegmentedList.Create<int>();
Assert.True(collection.IsSynchronized);
}
[Fact]
public void IListIsReadOnly()
{
IList list = ImmutableSegmentedList.Create<int>();
Assert.True(list.IsReadOnly);
Assert.True(list.IsFixedSize);
Assert.Throws<NotSupportedException>(() => list.Add(1));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => list.Remove(1));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list[0] = 1);
}
[Fact]
public void IListOfTIsReadOnly()
{
IList<int> list = ImmutableSegmentedList.Create<int>();
Assert.True(list.IsReadOnly);
Assert.Throws<NotSupportedException>(() => list.Add(1));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => list.Remove(1));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list[0] = 1);
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/54429")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSegmentedList.Create<int>());
ImmutableSegmentedList<double> list = ImmutableSegmentedList.Create<double>(1, 2, 3);
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(list);
object? rootNode = DebuggerAttributes.GetFieldValue(ImmutableSegmentedList.Create<string>("1", "2", "3"), "_root")!;
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>()!.State == DebuggerBrowsableState.RootHidden);
double[]? items = itemProperty.GetValue(info.Instance) as double[];
Assert.Equal(list, items);
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/54429")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSegmentedList.Create<double>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object?)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
#if NETCOREAPP
[Fact]
public void UsableWithCollectibleAssemblies()
{
var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("dynamic_assembly"), AssemblyBuilderAccess.RunAndCollect);
var module = assembly.DefineDynamicModule("dynamic");
var typeBuilder = module.DefineType("Dummy");
typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);
var dummType = typeBuilder.CreateTypeInfo();
var createMethod = typeof(ImmutableSegmentedList).GetMethods().Where(m => m.Name == "Create" && m.GetParameters().Length == 0).Single().MakeGenericMethod(dummType!.AsType());
var list = Assert.IsAssignableFrom<IEnumerable>(createMethod.Invoke(null, null));
var addMethod = list.GetType().GetMethod("Add");
list = Assert.IsAssignableFrom<IEnumerable>(addMethod!.Invoke(list, new object?[] { Activator.CreateInstance(dummType.AsType()) }));
list.GetEnumerator(); // ensure this doesn't throw
}
#endif
[Fact]
public void ItemRef()
{
var list = new[] { 1, 2, 3 }.ToImmutableSegmentedList();
ref readonly var safeRef = ref list.ItemRef(1);
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(2, list.ItemRef(1));
unsafeRef = 4;
Assert.Equal(4, list.ItemRef(1));
}
[Fact]
public void ItemRef_OutOfBounds()
{
var list = new[] { 1, 2, 3 }.ToImmutableSegmentedList();
Assert.Throws<ArgumentOutOfRangeException>(() => list.ItemRef(5));
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableSegmentedList<T>.Empty.AddRange(contents);
}
private protected override void RemoveAllTestHelper<T>(ImmutableSegmentedList<T> list, Predicate<T> test)
{
var expected = list.ToList();
expected.RemoveAll(test);
var actual = list.RemoveAll(test);
Assert.Equal<T>(expected, actual.ToList());
}
private protected override void ReverseTestHelper<T>(ImmutableSegmentedList<T> list, int index, int count)
{
var expected = list.ToList();
expected.Reverse(index, count);
var actual = list.Reverse(index, count);
Assert.Equal<T>(expected, actual.ToList());
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list)
{
return list.Sort().ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, Comparison<T> comparison)
{
return list.Sort(comparison).ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, IComparer<T>? comparer)
{
return list.Sort(comparer).ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, int index, int count, IComparer<T>? comparer)
{
return list.Sort(index, count, comparer).ToList();
}
internal override IReadOnlyList<T> GetListQuery<T>(ImmutableSegmentedList<T> list)
{
return list;
}
private protected override ImmutableSegmentedList<TOutput> ConvertAllImpl<T, TOutput>(ImmutableSegmentedList<T> list, Converter<T, TOutput> converter)
=> list.ConvertAll(converter);
private protected override void ForEachImpl<T>(ImmutableSegmentedList<T> list, Action<T> action)
=> list.ForEach(action);
private protected override ImmutableSegmentedList<T> GetRangeImpl<T>(ImmutableSegmentedList<T> list, int index, int count)
=> list.GetRange(index, count);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, T[] array)
=> list.CopyTo(array);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, T[] array, int arrayIndex)
=> list.CopyTo(array, arrayIndex);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, int index, T[] array, int arrayIndex, int count)
=> list.CopyTo(index, array, arrayIndex, count);
private protected override bool ExistsImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.Exists(match);
private protected override T? FindImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
where T : default
=> list.Find(match);
private protected override ImmutableSegmentedList<T> FindAllImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.FindAll(match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.FindIndex(match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, Predicate<T> match)
=> list.FindIndex(startIndex, match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, int count, Predicate<T> match)
=> list.FindIndex(startIndex, count, match);
private protected override T? FindLastImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
where T : default
=> list.FindLast(match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.FindLastIndex(match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, Predicate<T> match)
=> list.FindLastIndex(startIndex, match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, int count, Predicate<T> match)
=> list.FindLastIndex(startIndex, count, match);
private protected override bool TrueForAllImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> test)
=> list.TrueForAll(test);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, T item)
=> list.BinarySearch(item);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, T item, IComparer<T>? comparer)
=> list.BinarySearch(item, comparer);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, int index, int count, T item, IComparer<T>? comparer)
=> list.BinarySearch(index, count, item, comparer);
private struct Person
{
public string Name { get; set; }
public int Age { get; set; }
}
private class NameOnlyEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.Name == y.Name;
}
public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://raw.githubusercontent.com/dotnet/runtime/v6.0.0-preview.5.21301.5/src/libraries/System.Collections.Immutable/tests/ImmutableListTest.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Collections;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public class ImmutableSegmentedListTest : ImmutableListTestBase
{
private enum Operation
{
Add,
AddRange,
Insert,
InsertRange,
RemoveAt,
RemoveRange,
Last,
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = RandomOperationsCount;
var expected = new List<int>();
var actual = ImmutableSegmentedList<int>.Empty;
int seed = unchecked((int)DateTime.Now.Ticks);
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Debug.WriteLine("Adding \"{0}\" to the list.", value);
expected.Add(value);
actual = actual.Add(value);
break;
case Operation.AddRange:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Debug.WriteLine("Adding {0} elements to the list.", inputLength);
expected.AddRange(values);
actual = actual.AddRange(values);
break;
case Operation.Insert:
int position = random.Next(expected.Count + 1);
value = random.Next();
Debug.WriteLine("Adding \"{0}\" to position {1} in the list.", value, position);
expected.Insert(position, value);
actual = actual.Insert(position, value);
break;
case Operation.InsertRange:
inputLength = random.Next(100);
values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
position = random.Next(expected.Count + 1);
Debug.WriteLine("Adding {0} elements to position {1} in the list.", inputLength, position);
expected.InsertRange(position, values);
actual = actual.InsertRange(position, values);
break;
case Operation.RemoveAt:
if (expected.Count > 0)
{
position = random.Next(expected.Count);
Debug.WriteLine("Removing element at position {0} from the list.", position);
expected.RemoveAt(position);
actual = actual.RemoveAt(position);
}
break;
case Operation.RemoveRange:
position = random.Next(expected.Count);
inputLength = random.Next(expected.Count - position);
Debug.WriteLine("Removing {0} elements starting at position {1} from the list.", inputLength, position);
expected.RemoveRange(position, inputLength);
actual = actual.RemoveRange(position, inputLength);
break;
}
Assert.Equal<int>(expected, actual);
}
}
[Fact]
public void EmptyTest()
{
var empty = ImmutableSegmentedList<GenericParameterHelper?>.Empty;
Assert.True(IsSame(empty, ImmutableSegmentedList<GenericParameterHelper>.Empty));
Assert.True(IsSame(empty, empty.Clear()));
Assert.True(IsSame(empty, ((System.Collections.Immutable.IImmutableList<GenericParameterHelper>)empty).Clear()));
Assert.True(empty.IsEmpty);
Assert.Equal(0, empty.Count);
Assert.Equal(-1, empty.IndexOf(new GenericParameterHelper()));
Assert.Equal(-1, empty.IndexOf(null));
}
[Fact]
public void GetHashCodeVariesByInstance()
{
Assert.NotEqual(ImmutableSegmentedList.Create<int>().GetHashCode(), ImmutableSegmentedList.Create(5).GetHashCode());
}
[Fact]
public void AddAndIndexerTest()
{
var list = ImmutableSegmentedList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
Assert.False(list.IsEmpty);
Assert.Equal(i, list.Count);
}
for (int i = 1; i <= 10; i++)
{
Assert.Equal(i * 10, list[i - 1]);
}
var bulkList = ImmutableSegmentedList<int>.Empty.AddRange(Enumerable.Range(1, 10).Select(i => i * 10));
Assert.Equal<int>(list.ToArray(), bulkList.ToArray());
}
[Fact]
public void AddRangeTest()
{
var list = ImmutableSegmentedList<int>.Empty;
list = list.AddRange(new[] { 1, 2, 3 });
list = list.AddRange(Enumerable.Range(4, 2));
list = list.AddRange(ImmutableSegmentedList<int>.Empty.AddRange(new[] { 6, 7, 8 }));
list = list.AddRange(new int[0]);
list = list.AddRange(ImmutableSegmentedList<int>.Empty.AddRange(Enumerable.Range(9, 1000)));
Assert.Equal(Enumerable.Range(1, 1008), list);
}
[Fact]
public void AddRange_IOrderedCollection()
{
var list = ImmutableSegmentedList<int>.Empty;
ImmutableSegmentedList<int>.Builder builder = ImmutableSegmentedList.CreateBuilder<int>();
builder.Add(1);
list = list.AddRange(builder);
Assert.Equal(new int[] { 1 }, list);
}
[Fact]
public void AddRangeOptimizationsTest()
{
// All these optimizations are tested based on filling an empty list.
var emptyList = ImmutableSegmentedList.Create<string>();
// Adding an empty list to an empty list should yield the original list.
Assert.True(IsSame(emptyList, emptyList.AddRange(new string[0])));
// Adding a non-empty immutable list to an empty one should return the added list.
var nonEmptyListDefaultComparer = ImmutableSegmentedList.Create("5");
Assert.True(IsSame(nonEmptyListDefaultComparer, emptyList.AddRange(nonEmptyListDefaultComparer)));
// Adding a Builder instance to an empty list should be seen through.
var builderOfNonEmptyListDefaultComparer = nonEmptyListDefaultComparer.ToBuilder();
Assert.True(IsSame(nonEmptyListDefaultComparer, emptyList.AddRange(builderOfNonEmptyListDefaultComparer)));
}
[Fact]
public void AddRangeBalanceTest()
{
int randSeed = unchecked((int)DateTime.Now.Ticks);
Debug.WriteLine("Random seed: {0}", randSeed);
var random = new Random(randSeed);
int expectedTotalSize = 0;
var list = ImmutableSegmentedList<int>.Empty;
// Add some small batches, verifying balance after each
for (int i = 0; i < 128; i++)
{
int batchSize = random.Next(32);
Debug.WriteLine("Adding {0} elements to the list", batchSize);
list = list.AddRange(Enumerable.Range(expectedTotalSize + 1, batchSize));
expectedTotalSize += batchSize;
}
// Add a single large batch to the end
int largeBatchSize = random.Next(32768) + 32768;
Debug.WriteLine("Adding {0} elements to the list", largeBatchSize);
list = list.AddRange(Enumerable.Range(expectedTotalSize + 1, largeBatchSize));
expectedTotalSize += largeBatchSize;
Assert.Equal(Enumerable.Range(1, expectedTotalSize), list);
}
[Fact]
public void InsertRangeRandomBalanceTest()
{
int randSeed = unchecked((int)DateTime.Now.Ticks);
Debug.WriteLine("Random seed: {0}", randSeed);
var random = new Random(randSeed);
var immutableList = ImmutableSegmentedList.CreateBuilder<int>();
var list = new List<int>();
const int maxBatchSize = 32;
int valueCounter = 0;
for (int i = 0; i < 24; i++)
{
int startPosition = random.Next(list.Count + 1);
int length = random.Next(maxBatchSize + 1);
int[] values = new int[length];
for (int j = 0; j < length; j++)
{
values[j] = ++valueCounter;
}
immutableList.InsertRange(startPosition, values);
list.InsertRange(startPosition, values);
Assert.Equal(list, immutableList);
}
}
[Fact]
public void InsertTest()
{
var list = ImmutableSegmentedList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(1, 5));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(-1, 5));
list = list.Insert(0, 10);
list = list.Insert(1, 20);
list = list.Insert(2, 30);
list = list.Insert(2, 25);
list = list.Insert(1, 15);
list = list.Insert(0, 5);
Assert.Equal(6, list.Count);
var expectedList = new[] { 5, 10, 15, 20, 25, 30 };
var actualList = list.ToArray();
Assert.Equal<int>(expectedList, actualList);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(7, 5));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(-1, 5));
}
[Fact]
public void InsertBalanceTest()
{
var list = ImmutableSegmentedList.Create(1);
list = list.Insert(0, 2);
list = list.Insert(1, 3);
}
[Fact]
public void InsertRangeTest()
{
var list = ImmutableSegmentedList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(1, new[] { 1 }));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, new[] { 1 }));
list = list.InsertRange(0, new[] { 1, 4, 5 });
list = list.InsertRange(1, new[] { 2, 3 });
list = list.InsertRange(2, new int[0]);
Assert.Equal(Enumerable.Range(1, 5), list);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(6, new[] { 1 }));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, new[] { 1 }));
}
[Fact]
public void InsertRangeImmutableTest()
{
var list = ImmutableSegmentedList<int>.Empty;
var nonEmptyList = ImmutableSegmentedList.Create(1);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(1, nonEmptyList));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, nonEmptyList));
list = list.InsertRange(0, ImmutableSegmentedList.Create(1, 104, 105));
list = list.InsertRange(1, ImmutableSegmentedList.Create(2, 3));
list = list.InsertRange(2, ImmutableSegmentedList<int>.Empty);
list = list.InsertRange(3, ImmutableSegmentedList<int>.Empty.InsertRange(0, Enumerable.Range(4, 100)));
Assert.Equal(Enumerable.Range(1, 105), list);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(106, nonEmptyList));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, nonEmptyList));
}
[Fact]
public void NullHandlingTest()
{
var list = ImmutableSegmentedList<GenericParameterHelper?>.Empty;
Assert.False(list.Contains(null));
Assert.Equal(-1, list.IndexOf(null));
list = list.Add((GenericParameterHelper?)null);
Assert.Equal(1, list.Count);
Assert.Null(list[0]);
Assert.True(list.Contains(null));
Assert.Equal(0, list.IndexOf(null));
list = list.Remove((GenericParameterHelper?)null);
Assert.Equal(0, list.Count);
Assert.True(list.IsEmpty);
Assert.False(list.Contains(null));
Assert.Equal(-1, list.IndexOf(null));
}
[Fact]
public void Remove_NullEqualityComparer()
{
var collection = ImmutableSegmentedList.Create(1, 2, 3);
var modified = collection.Remove(2, null);
Assert.Equal(new[] { 1, 3 }, modified);
// Try again through the explicit interface implementation.
System.Collections.Immutable.IImmutableList<int> collectionIface = collection;
var modified2 = collectionIface.Remove(2, null);
Assert.Equal(new[] { 1, 3 }, modified2);
}
[Fact]
public void RemoveTest()
{
ImmutableSegmentedList<int> list = ImmutableSegmentedList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
}
list = list.Remove(30);
Assert.Equal(9, list.Count);
Assert.False(list.Contains(30));
list = list.Remove(100);
Assert.Equal(8, list.Count);
Assert.False(list.Contains(100));
list = list.Remove(10);
Assert.Equal(7, list.Count);
Assert.False(list.Contains(10));
var removeList = new int[] { 20, 70 };
list = list.RemoveAll(removeList.Contains);
Assert.Equal(5, list.Count);
Assert.False(list.Contains(20));
Assert.False(list.Contains(70));
System.Collections.Immutable.IImmutableList<int> list2 = ImmutableSegmentedList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list2 = list2.Add(i * 10);
}
list2 = System.Collections.Immutable.ImmutableList.Remove(list2, 30);
Assert.Equal(9, list2.Count);
Assert.False(list2.Contains(30));
list2 = System.Collections.Immutable.ImmutableList.Remove(list2, 100);
Assert.Equal(8, list2.Count);
Assert.False(list2.Contains(100));
list2 = System.Collections.Immutable.ImmutableList.Remove(list2, 10);
Assert.Equal(7, list2.Count);
Assert.False(list2.Contains(10));
list2 = list2.RemoveAll(removeList.Contains);
Assert.Equal(5, list2.Count);
Assert.False(list2.Contains(20));
Assert.False(list2.Contains(70));
}
[Fact]
public void RemoveNonExistentKeepsReference()
{
var list = ImmutableSegmentedList<int>.Empty;
Assert.True(IsSame(list, list.Remove(3)));
}
/// <summary>
/// Verifies that RemoveRange does not enumerate its argument if the list is empty
/// and therefore could not possibly have any elements to remove anyway.
/// </summary>
/// <remarks>
/// While this would seem an implementation detail and simply an optimization,
/// it turns out that changing this behavior now *could* represent a breaking change
/// because if the enumerable were to throw an exception, that exception would not be
/// observed previously, but would start to be thrown if this behavior changed.
/// So this is a test to lock the behavior in place.
/// </remarks>
/// <!--<seealso cref="ImmutableSetTest.ExceptDoesEnumerateSequenceIfThisIsEmpty"/>-->
[Fact]
public void RemoveRangeDoesNotEnumerateSequenceIfThisIsEmpty()
{
var list = ImmutableSegmentedList<int>.Empty;
list.RemoveRange(Enumerable.Range(1, 1).Select<int, int>(n => { throw ExceptionUtilities.Unreachable; }));
}
[Fact]
public void RemoveAtTest()
{
var list = ImmutableSegmentedList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveAt(1));
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
}
list = list.RemoveAt(2);
Assert.Equal(9, list.Count);
Assert.False(list.Contains(30));
list = list.RemoveAt(8);
Assert.Equal(8, list.Count);
Assert.False(list.Contains(100));
list = list.RemoveAt(0);
Assert.Equal(7, list.Count);
Assert.False(list.Contains(10));
}
[Fact]
public void IndexOfAndContainsTest()
{
var expectedList = new List<string>(new[] { "Microsoft", "Windows", "Bing", "Visual Studio", "Comics", "Computers", "Laptops" });
var list = ImmutableSegmentedList<string>.Empty;
foreach (string newElement in expectedList)
{
Assert.False(list.Contains(newElement));
list = list.Add(newElement);
Assert.True(list.Contains(newElement));
Assert.Equal(expectedList.IndexOf(newElement), list.IndexOf(newElement));
Assert.Equal(expectedList.IndexOf(newElement), System.Collections.Immutable.ImmutableList.IndexOf(list, newElement.ToUpperInvariant(), StringComparer.OrdinalIgnoreCase));
Assert.Equal(-1, list.IndexOf(newElement.ToUpperInvariant()));
foreach (string existingElement in expectedList.TakeWhile(v => v != newElement))
{
Assert.True(list.Contains(existingElement));
Assert.Equal(expectedList.IndexOf(existingElement), list.IndexOf(existingElement));
Assert.Equal(expectedList.IndexOf(existingElement), System.Collections.Immutable.ImmutableList.IndexOf(list, existingElement.ToUpperInvariant(), StringComparer.OrdinalIgnoreCase));
Assert.Equal(-1, list.IndexOf(existingElement.ToUpperInvariant()));
}
}
}
[Fact]
public void Indexer()
{
var list = ImmutableSegmentedList.CreateRange(Enumerable.Range(1, 3));
Assert.Equal(1, list[0]);
Assert.Equal(2, list[1]);
Assert.Equal(3, list[2]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list[3]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list[-1]);
Assert.Equal(3, ((IList)list)[2]);
Assert.Equal(3, ((IList<int>)list)[2]);
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableSegmentedList.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => System.Collections.Immutable.ImmutableList.IndexOf(b, v, i),
(b, v, i, c) => System.Collections.Immutable.ImmutableList.IndexOf(b, v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
IndexOfTests.IndexOfTest(
seq => (System.Collections.Immutable.IImmutableList<int>)ImmutableSegmentedList.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => System.Collections.Immutable.ImmutableList.IndexOf(b, v, i),
(b, v, i, c) => System.Collections.Immutable.ImmutableList.IndexOf(b, v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableSegmentedList.CreateRange(seq),
(b, v) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v),
(b, v, eq) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, eq),
(b, v, i) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, i),
(b, v, i, c) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
IndexOfTests.LastIndexOfTest(
seq => (System.Collections.Immutable.IImmutableList<int>)ImmutableSegmentedList.CreateRange(seq),
(b, v) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v),
(b, v, eq) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, eq),
(b, v, i) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, i),
(b, v, i, c) => System.Collections.Immutable.ImmutableList.LastIndexOf(b, v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void ReplaceTest()
{
// Verify replace at beginning, middle, and end.
var list = ImmutableSegmentedList<int>.Empty.Add(3).Add(5).Add(8);
Assert.Equal<int>(new[] { 4, 5, 8 }, list.Replace(3, 4));
Assert.Equal<int>(new[] { 3, 6, 8 }, list.Replace(5, 6));
Assert.Equal<int>(new[] { 3, 5, 9 }, list.Replace(8, 9));
Assert.Equal<int>(new[] { 4, 5, 8 }, System.Collections.Immutable.ImmutableList.Replace((System.Collections.Immutable.IImmutableList<int>)list, 3, 4));
Assert.Equal<int>(new[] { 3, 6, 8 }, System.Collections.Immutable.ImmutableList.Replace((System.Collections.Immutable.IImmutableList<int>)list, 5, 6));
Assert.Equal<int>(new[] { 3, 5, 9 }, System.Collections.Immutable.ImmutableList.Replace((System.Collections.Immutable.IImmutableList<int>)list, 8, 9));
// Verify replacement of first element when there are duplicates.
list = ImmutableSegmentedList<int>.Empty.Add(3).Add(3).Add(5);
Assert.Equal<int>(new[] { 4, 3, 5 }, list.Replace(3, 4));
Assert.Equal<int>(new[] { 4, 4, 5 }, list.Replace(3, 4).Replace(3, 4));
Assert.Equal<int>(new[] { 4, 3, 5 }, System.Collections.Immutable.ImmutableList.Replace((System.Collections.Immutable.IImmutableList<int>)list, 3, 4));
Assert.Equal<int>(new[] { 4, 4, 5 }, System.Collections.Immutable.ImmutableList.Replace(System.Collections.Immutable.ImmutableList.Replace((System.Collections.Immutable.IImmutableList<int>)list, 3, 4), 3, 4));
}
[Fact]
public void ReplaceWithEqualityComparerTest()
{
var list = ImmutableSegmentedList.Create(new Person { Name = "Andrew", Age = 20 });
var newAge = new Person { Name = "Andrew", Age = 21 };
var updatedList = list.Replace(newAge, newAge, new NameOnlyEqualityComparer());
Assert.Equal(newAge.Age, updatedList[0].Age);
// Try again with a null equality comparer, which should use the default EQ.
updatedList = list.Replace(list[0], newAge);
Assert.False(IsSame(list, updatedList));
// Finally, try one last time using the interface implementation.
System.Collections.Immutable.IImmutableList<Person> iface = list;
var updatedIface = System.Collections.Immutable.ImmutableList.Replace(iface, list[0], newAge);
Assert.NotSame(iface, updatedIface);
}
[Fact]
public void ReplaceMissingThrowsTest()
{
Assert.Throws<ArgumentException>("oldValue", () => ImmutableSegmentedList<int>.Empty.Replace(5, 3));
}
[Fact]
public void EqualsTest()
{
Assert.False(ImmutableSegmentedList<int>.Empty.Equals(null));
Assert.False(ImmutableSegmentedList<int>.Empty.Equals("hi"));
Assert.True(ImmutableSegmentedList<int>.Empty.Equals(ImmutableSegmentedList<int>.Empty));
Assert.False(ImmutableSegmentedList<int>.Empty.Add(3).Equals(ImmutableSegmentedList<int>.Empty.Add(3)));
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
ImmutableSegmentedList<string> list = ImmutableSegmentedList.Create<string>();
Assert.Equal(0, list.Count);
list = ImmutableSegmentedList.Create("a");
Assert.Equal(1, list.Count);
list = ImmutableSegmentedList.Create("a", "b");
Assert.Equal(2, list.Count);
list = ImmutableSegmentedList.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, list.Count);
}
[Fact]
public void ToImmutableList()
{
ImmutableSegmentedList<string> list = new[] { "a", "b" }.ToImmutableSegmentedList();
Assert.Equal(2, list.Count);
list = new[] { "a", "b" }.ToImmutableSegmentedList();
Assert.Equal(2, list.Count);
}
[Fact]
public void ToImmutableListOfSameType()
{
var list = ImmutableSegmentedList.Create("a");
Assert.True(IsSame(list, list.ToImmutableSegmentedList()));
}
[Fact]
public void RemoveAllNullTest()
{
Assert.Throws<ArgumentNullException>("match", () => ImmutableSegmentedList<int>.Empty.RemoveAll(null!));
}
[Fact]
public void RemoveRangeArrayTest()
{
Assert.True(ImmutableSegmentedList<int>.Empty.RemoveRange(0, 0).IsEmpty);
var list = ImmutableSegmentedList.Create(1, 2, 3);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveRange(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>("count", () => list.RemoveRange(0, -1));
Assert.Throws<ArgumentException>(() => list.RemoveRange(4, 0));
Assert.Throws<ArgumentException>(() => list.RemoveRange(0, 4));
Assert.Throws<ArgumentException>(() => list.RemoveRange(2, 2));
Assert.Equal(list, list.RemoveRange(3, 0));
}
[Fact]
public void RemoveRange_EnumerableEqualityComparer_AcceptsNullEQ()
{
var list = ImmutableSegmentedList.Create(1, 2, 3);
var removed2eq = list.RemoveRange(new[] { 2 }, null);
Assert.Equal(2, removed2eq.Count);
Assert.Equal(new[] { 1, 3 }, removed2eq);
}
[Fact]
public void RemoveRangeEnumerableTest()
{
var list = ImmutableSegmentedList.Create(1, 2, 3);
Assert.Throws<ArgumentNullException>("items", () => list.RemoveRange(null!));
ImmutableSegmentedList<int> removed2 = list.RemoveRange(new[] { 2 });
Assert.Equal(2, removed2.Count);
Assert.Equal(new[] { 1, 3 }, removed2);
ImmutableSegmentedList<int> removed13 = list.RemoveRange(new[] { 1, 3, 5 });
Assert.Equal(1, removed13.Count);
Assert.Equal(new[] { 2 }, removed13);
Assert.Equal(new[] { 2 }, System.Collections.Immutable.ImmutableList.RemoveRange((System.Collections.Immutable.IImmutableList<int>)list, new[] { 1, 3, 5 }));
Assert.True(IsSame(list, list.RemoveRange(new[] { 5 })));
Assert.True(IsSame(ImmutableSegmentedList.Create<int>(), ImmutableSegmentedList.Create<int>().RemoveRange(new[] { 1 })));
var listWithDuplicates = ImmutableSegmentedList.Create(1, 2, 2, 3);
Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(new[] { 2 }));
Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2 }));
Assert.Throws<ArgumentNullException>("items", () => System.Collections.Immutable.ImmutableList.RemoveRange((System.Collections.Immutable.IImmutableList<int>)ImmutableSegmentedList.Create(1, 2, 3), null!));
Assert.Equal(new[] { 1, 3 }, System.Collections.Immutable.ImmutableList.RemoveRange((System.Collections.Immutable.IImmutableList<int>)ImmutableSegmentedList.Create(1, 2, 3), new[] { 2 }));
}
[Fact]
public void EnumeratorTest()
{
var list = ImmutableSegmentedList.Create("a");
var enumerator = list.GetEnumerator();
Assert.Null(enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Null(enumerator.Current);
enumerator.Reset();
Assert.Null(enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Null(enumerator.Current);
enumerator.Dispose();
enumerator.Reset();
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSegmentedList.Create(1);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
enumerator.Dispose();
Assert.False(enumerator.MoveNext());
enumerator.Reset();
Assert.Equal(0, enumerator.Current);
Assert.True(enumeratorCopy.MoveNext());
enumeratorCopy.Reset();
Assert.Equal(0, enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(collection[0], enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void ReverseTest2()
{
var emptyList = ImmutableSegmentedList.Create<int>();
Assert.True(IsSame(emptyList, emptyList.Reverse()));
var populatedList = ImmutableSegmentedList.Create(3, 2, 1);
Assert.Equal(Enumerable.Range(1, 3), populatedList.Reverse());
}
[Fact]
public void SetItem()
{
var emptyList = ImmutableSegmentedList.Create<int>();
Assert.Throws<ArgumentOutOfRangeException>("index", () => emptyList[-1]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => emptyList[0]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => emptyList[1]);
var listOfOne = emptyList.Add(5);
Assert.Throws<ArgumentOutOfRangeException>("index", () => listOfOne[-1]);
Assert.Equal(5, listOfOne[0]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => listOfOne[1]);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = ImmutableSegmentedList.Create<int>();
Assert.True(collection.IsSynchronized);
}
[Fact]
public void IListIsReadOnly()
{
IList list = ImmutableSegmentedList.Create<int>();
Assert.True(list.IsReadOnly);
Assert.True(list.IsFixedSize);
Assert.Throws<NotSupportedException>(() => list.Add(1));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => list.Remove(1));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list[0] = 1);
}
[Fact]
public void IListOfTIsReadOnly()
{
IList<int> list = ImmutableSegmentedList.Create<int>();
Assert.True(list.IsReadOnly);
Assert.Throws<NotSupportedException>(() => list.Add(1));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => list.Remove(1));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list[0] = 1);
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/54429")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSegmentedList.Create<int>());
ImmutableSegmentedList<double> list = ImmutableSegmentedList.Create<double>(1, 2, 3);
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(list);
object? rootNode = DebuggerAttributes.GetFieldValue(ImmutableSegmentedList.Create<string>("1", "2", "3"), "_root")!;
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>()!.State == DebuggerBrowsableState.RootHidden);
double[]? items = itemProperty.GetValue(info.Instance) as double[];
Assert.Equal(list, items);
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/54429")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSegmentedList.Create<double>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object?)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
#if NETCOREAPP
[Fact]
public void UsableWithCollectibleAssemblies()
{
var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("dynamic_assembly"), AssemblyBuilderAccess.RunAndCollect);
var module = assembly.DefineDynamicModule("dynamic");
var typeBuilder = module.DefineType("Dummy");
typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);
var dummType = typeBuilder.CreateTypeInfo();
var createMethod = typeof(ImmutableSegmentedList).GetMethods().Where(m => m.Name == "Create" && m.GetParameters().Length == 0).Single().MakeGenericMethod(dummType!.AsType());
var list = Assert.IsAssignableFrom<IEnumerable>(createMethod.Invoke(null, null));
var addMethod = list.GetType().GetMethod("Add");
list = Assert.IsAssignableFrom<IEnumerable>(addMethod!.Invoke(list, new object?[] { Activator.CreateInstance(dummType.AsType()) }));
list.GetEnumerator(); // ensure this doesn't throw
}
#endif
[Fact]
public void ItemRef()
{
var list = new[] { 1, 2, 3 }.ToImmutableSegmentedList();
ref readonly var safeRef = ref list.ItemRef(1);
ref var unsafeRef = ref Unsafe.AsRef(safeRef);
Assert.Equal(2, list.ItemRef(1));
unsafeRef = 4;
Assert.Equal(4, list.ItemRef(1));
}
[Fact]
public void ItemRef_OutOfBounds()
{
var list = new[] { 1, 2, 3 }.ToImmutableSegmentedList();
Assert.Throws<ArgumentOutOfRangeException>(() => list.ItemRef(5));
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableSegmentedList<T>.Empty.AddRange(contents);
}
private protected override void RemoveAllTestHelper<T>(ImmutableSegmentedList<T> list, Predicate<T> test)
{
var expected = list.ToList();
expected.RemoveAll(test);
var actual = list.RemoveAll(test);
Assert.Equal<T>(expected, actual.ToList());
}
private protected override void ReverseTestHelper<T>(ImmutableSegmentedList<T> list, int index, int count)
{
var expected = list.ToList();
expected.Reverse(index, count);
var actual = list.Reverse(index, count);
Assert.Equal<T>(expected, actual.ToList());
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list)
{
return list.Sort().ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, Comparison<T> comparison)
{
return list.Sort(comparison).ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, IComparer<T>? comparer)
{
return list.Sort(comparer).ToList();
}
private protected override List<T> SortTestHelper<T>(ImmutableSegmentedList<T> list, int index, int count, IComparer<T>? comparer)
{
return list.Sort(index, count, comparer).ToList();
}
internal override IReadOnlyList<T> GetListQuery<T>(ImmutableSegmentedList<T> list)
{
return list;
}
private protected override ImmutableSegmentedList<TOutput> ConvertAllImpl<T, TOutput>(ImmutableSegmentedList<T> list, Converter<T, TOutput> converter)
=> list.ConvertAll(converter);
private protected override void ForEachImpl<T>(ImmutableSegmentedList<T> list, Action<T> action)
=> list.ForEach(action);
private protected override ImmutableSegmentedList<T> GetRangeImpl<T>(ImmutableSegmentedList<T> list, int index, int count)
=> list.GetRange(index, count);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, T[] array)
=> list.CopyTo(array);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, T[] array, int arrayIndex)
=> list.CopyTo(array, arrayIndex);
private protected override void CopyToImpl<T>(ImmutableSegmentedList<T> list, int index, T[] array, int arrayIndex, int count)
=> list.CopyTo(index, array, arrayIndex, count);
private protected override bool ExistsImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.Exists(match);
private protected override T? FindImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
where T : default
=> list.Find(match);
private protected override ImmutableSegmentedList<T> FindAllImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.FindAll(match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.FindIndex(match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, Predicate<T> match)
=> list.FindIndex(startIndex, match);
private protected override int FindIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, int count, Predicate<T> match)
=> list.FindIndex(startIndex, count, match);
private protected override T? FindLastImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
where T : default
=> list.FindLast(match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> match)
=> list.FindLastIndex(match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, Predicate<T> match)
=> list.FindLastIndex(startIndex, match);
private protected override int FindLastIndexImpl<T>(ImmutableSegmentedList<T> list, int startIndex, int count, Predicate<T> match)
=> list.FindLastIndex(startIndex, count, match);
private protected override bool TrueForAllImpl<T>(ImmutableSegmentedList<T> list, Predicate<T> test)
=> list.TrueForAll(test);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, T item)
=> list.BinarySearch(item);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, T item, IComparer<T>? comparer)
=> list.BinarySearch(item, comparer);
private protected override int BinarySearchImpl<T>(ImmutableSegmentedList<T> list, int index, int count, T item, IComparer<T>? comparer)
=> list.BinarySearch(index, count, item, comparer);
private struct Person
{
public string Name { get; set; }
public int Age { get; set; }
}
private class NameOnlyEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.Name == y.Name;
}
public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionConstants.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.ConvertSwitchStatementToExpression
{
internal static class ConvertSwitchStatementToExpressionConstants
{
public const string NodeToGenerateKey = nameof(NodeToGenerateKey);
public const string ShouldRemoveNextStatementKey = nameof(ShouldRemoveNextStatementKey);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.ConvertSwitchStatementToExpression
{
internal static class ConvertSwitchStatementToExpressionConstants
{
public const string NodeToGenerateKey = nameof(NodeToGenerateKey);
public const string ShouldRemoveNextStatementKey = nameof(ShouldRemoveNextStatementKey);
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/TypeImportCompletionServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
[ExportLanguageServiceFactory(typeof(ITypeImportCompletionService), LanguageNames.CSharp), Shared]
internal sealed class TypeImportCompletionServiceFactory : ILanguageServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TypeImportCompletionServiceFactory()
{
}
public ILanguageService CreateLanguageService(HostLanguageServices languageServices)
=> new CSharpTypeImportCompletionService(languageServices.WorkspaceServices.Workspace);
private class CSharpTypeImportCompletionService : AbstractTypeImportCompletionService
{
public CSharpTypeImportCompletionService(Workspace workspace)
: base(workspace)
{
}
protected override string GenericTypeSuffix
=> "<>";
protected override bool IsCaseSensitive => true;
protected override string Language => 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.Composition;
using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
[ExportLanguageServiceFactory(typeof(ITypeImportCompletionService), LanguageNames.CSharp), Shared]
internal sealed class TypeImportCompletionServiceFactory : ILanguageServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TypeImportCompletionServiceFactory()
{
}
public ILanguageService CreateLanguageService(HostLanguageServices languageServices)
=> new CSharpTypeImportCompletionService(languageServices.WorkspaceServices.Workspace);
private class CSharpTypeImportCompletionService : AbstractTypeImportCompletionService
{
public CSharpTypeImportCompletionService(Workspace workspace)
: base(workspace)
{
}
protected override string GenericTypeSuffix
=> "<>";
protected override bool IsCaseSensitive => true;
protected override string Language => LanguageNames.CSharp;
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Workspaces/Core/Portable/Options/OptionsHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.CodeStyle;
namespace Microsoft.CodeAnalysis.Options
{
internal static class OptionsHelpers
{
public static T GetOption<T>(Option<T> option, Func<OptionKey, object?> getOption)
=> GetOption<T>(new OptionKey(option), getOption);
public static T GetOption<T>(Option2<T> option, Func<OptionKey, object?> getOption)
=> GetOption<T>(new OptionKey(option), getOption);
public static T GetOption<T>(PerLanguageOption<T> option, string? language, Func<OptionKey, object?> getOption)
=> GetOption<T>(new OptionKey(option, language), getOption);
public static T GetOption<T>(PerLanguageOption2<T> option, string? language, Func<OptionKey, object?> getOption)
=> GetOption<T>(new OptionKey(option, language), getOption);
public static T GetOption<T>(OptionKey2 optionKey, Func<OptionKey, object?> getOption)
=> GetOption<T>(new OptionKey(optionKey.Option, optionKey.Language), getOption);
public static T GetOption<T>(OptionKey optionKey, Func<OptionKey, object?> getOption)
{
var value = getOption(optionKey);
if (value is ICodeStyleOption codeStyleOption)
{
return (T)codeStyleOption.AsCodeStyleOption<T>();
}
return (T)value!;
}
public static object? GetPublicOption(OptionKey optionKey, Func<OptionKey, object?> getOption)
{
var value = getOption(optionKey);
if (value is ICodeStyleOption codeStyleOption)
{
return codeStyleOption.AsPublicCodeStyleOption();
}
return value;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.CodeStyle;
namespace Microsoft.CodeAnalysis.Options
{
internal static class OptionsHelpers
{
public static T GetOption<T>(Option<T> option, Func<OptionKey, object?> getOption)
=> GetOption<T>(new OptionKey(option), getOption);
public static T GetOption<T>(Option2<T> option, Func<OptionKey, object?> getOption)
=> GetOption<T>(new OptionKey(option), getOption);
public static T GetOption<T>(PerLanguageOption<T> option, string? language, Func<OptionKey, object?> getOption)
=> GetOption<T>(new OptionKey(option, language), getOption);
public static T GetOption<T>(PerLanguageOption2<T> option, string? language, Func<OptionKey, object?> getOption)
=> GetOption<T>(new OptionKey(option, language), getOption);
public static T GetOption<T>(OptionKey2 optionKey, Func<OptionKey, object?> getOption)
=> GetOption<T>(new OptionKey(optionKey.Option, optionKey.Language), getOption);
public static T GetOption<T>(OptionKey optionKey, Func<OptionKey, object?> getOption)
{
var value = getOption(optionKey);
if (value is ICodeStyleOption codeStyleOption)
{
return (T)codeStyleOption.AsCodeStyleOption<T>();
}
return (T)value!;
}
public static object? GetPublicOption(OptionKey optionKey, Func<OptionKey, object?> getOption)
{
var value = getOption(optionKey);
if (value is ICodeStyleOption codeStyleOption)
{
return codeStyleOption.AsPublicCodeStyleOption();
}
return value;
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Compilers/CSharp/Portable/BoundTree/BoundNode_Source.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract partial class BoundNode
{
#if DEBUG
/// <summary>
/// Gives an approximate printout of a bound node as C# code.
/// </summary>
internal string DumpSource()
{
int indentSize = 4;
var builder = new StringBuilder();
appendSourceCore(this, indent: 0, tempIdentifiers: new Dictionary<SynthesizedLocal, int>());
return builder.ToString();
void appendSourceCore(BoundNode node, int indent, Dictionary<SynthesizedLocal, int> tempIdentifiers)
{
switch (node)
{
case BoundTryStatement tryStatement:
{
appendLine("try");
appendSource(tryStatement.TryBlock);
var catchBlocks = tryStatement.CatchBlocks;
if (catchBlocks != null)
{
foreach (var catchBlock in catchBlocks)
{
append("catch (");
append(catchBlock.ExceptionTypeOpt?.Name);
append(") ");
if (catchBlock.ExceptionFilterOpt != null)
{
append("... exception filter omitted ...");
}
appendLine("");
appendSource(catchBlock.Body);
}
}
var finallyBlock = tryStatement.FinallyBlockOpt;
if (finallyBlock != null)
{
appendLine("finally");
appendSource(finallyBlock);
}
break;
}
case BoundThrowStatement throwStatement:
{
append("throw ");
if (throwStatement.ExpressionOpt != null)
{
appendSource(throwStatement.ExpressionOpt);
}
appendLine(";");
break;
}
case BoundBlock block:
{
var statements = block.Statements;
if (statements.Length == 1 && block.Locals.IsEmpty)
{
appendSource(statements[0]);
break;
}
appendLine("{");
foreach (var local in block.Locals)
{
if (local is SynthesizedLocal synthesized)
{
appendLine($"{local.TypeWithAnnotations.ToDisplayString()} {name(synthesized)};");
}
else
{
appendLine($"({local.GetDebuggerDisplay()});");
}
}
foreach (var statement in statements)
{
appendSource(statement);
}
appendLine("}");
break;
}
case BoundStateMachineScope stateMachineScope:
{
appendSource(stateMachineScope.Statement);
break;
}
case BoundSequencePoint seqPoint:
{
var statement = seqPoint.StatementOpt;
if (statement != null)
{
appendSource(statement);
}
break;
}
case BoundSequencePointExpression seqPoint:
{
var expression = seqPoint.Expression;
appendSource(expression);
break;
}
case BoundSequencePointWithSpan seqPoint:
{
var statement = seqPoint.StatementOpt;
if (statement != null)
{
appendSource(statement);
}
break;
}
case BoundYieldReturnStatement yieldStatement:
{
append("yield return ");
appendSource(yieldStatement.Expression);
appendLine(";");
break;
}
case BoundReturnStatement returnStatement:
{
append("return");
var value = returnStatement.ExpressionOpt;
if (value != null)
{
append(" ");
appendSource(value);
}
appendLine(";");
break;
}
case BoundGotoStatement gotoStatement:
{
append("goto ");
append(gotoStatement.Label.ToString());
appendLine(";");
break;
}
case BoundConditionalGoto gotoStatement:
{
append("if (");
append(gotoStatement.JumpIfTrue ? "" : "!");
appendSource(gotoStatement.Condition);
append(") ");
append("goto ");
append(gotoStatement.Label.ToString());
appendLine(";");
break;
}
case BoundLabelStatement label:
{
append(label.Label.ToString());
appendLine(": ;");
break;
}
case BoundTypeExpression type:
{
append(type.Type.Name);
break;
}
case BoundLocal local:
{
var symbol = local.LocalSymbol;
appendLocal(symbol);
break;
}
case BoundNoOpStatement noop:
{
break;
}
case BoundExpressionStatement expressionStatement:
{
appendSource(expressionStatement.Expression);
appendLine(";");
break;
}
case BoundAwaitExpression awaitExpression:
{
append("await ");
appendSource(awaitExpression.Expression);
break;
}
case BoundCall call:
{
var receiver = call.ReceiverOpt;
if (receiver != null)
{
appendSource(receiver);
append(".");
}
append(call.Method.Name);
append("(");
bool first = true;
foreach (var argument in call.Arguments)
{
if (!first)
{
append(", ");
}
first = false;
appendSource(argument);
}
append(")");
break;
}
case BoundLiteral literal:
{
var value = literal.ConstantValue?.Value?.ToString();
if (value is null)
{
append("null");
break;
}
switch (literal.ConstantValue?.Discriminator)
{
case ConstantValueTypeDiscriminator.String:
append($@"""{value}""");
break;
default:
append(value);
break;
}
break;
}
case BoundAssignmentOperator assignment:
{
appendSource(assignment.Left);
append(" = ");
appendSource(assignment.Right);
break;
}
case BoundThisReference thisReference:
{
append("this");
break;
}
case BoundFieldAccess fieldAccess:
{
var receiver = fieldAccess.ReceiverOpt;
if (receiver != null)
{
appendSource(receiver);
append(".");
}
append(fieldAccess.FieldSymbol.Name);
break;
}
case BoundSwitchStatement switchStatement:
{
append("switch (");
appendSource(switchStatement.Expression);
appendLine(")");
appendLine("{");
foreach (BoundSwitchSection section in switchStatement.SwitchSections)
{
foreach (var label in section.SwitchLabels)
{
append("case ");
appendSource(label);
appendLine(":");
}
incrementIndent();
foreach (var statement in section.Statements)
{
appendSource(statement);
}
appendLine("break;");
decrementIndent();
}
appendLine("}");
break;
}
case BoundSwitchLabel label:
{
appendSource(label.Pattern);
break;
}
case BoundUnaryOperator unary:
{
append($" {unary.OperatorKind.ToString()} ");
appendSource(unary.Operand);
break;
}
case BoundStatementList list:
{
foreach (var statement in list.Statements)
{
appendSource(statement);
}
break;
}
case BoundSequence sequence:
{
append("{ ");
foreach (var effect in sequence.SideEffects)
{
appendSource(effect);
append("; ");
}
appendSource(sequence.Value);
append(" }");
break;
}
case BoundDefaultLiteral _:
case BoundDefaultExpression _:
{
append("default");
break;
}
case BoundBinaryOperator binary:
{
appendSource(binary.Left);
append(" ");
append(binary.OperatorKind.ToString());
append(" ");
appendSource(binary.Right);
break;
}
default:
appendLine(node.Kind.ToString());
break;
}
void appendSource(BoundNode? n)
{
if (n is null)
{
append("NULL");
}
else
{
appendSourceCore(n, indent, tempIdentifiers);
}
}
void append(string? s)
{
builder.Append(s);
}
void incrementIndent()
{
indent += indentSize;
builder.Append(' ', indentSize);
}
void decrementIndent()
{
indent -= indentSize;
builder.Remove(builder.Length - indentSize, indentSize);
}
void appendLine(string s)
{
if (s == "{")
{
indent += indentSize;
builder.AppendLine(s);
builder.Append(' ', indent);
}
else if (s == "}")
{
builder.Remove(builder.Length - indentSize, indentSize);
builder.AppendLine(s);
indent -= indentSize;
builder.Append(' ', indent);
}
else
{
builder.AppendLine(s);
builder.Append(' ', indent);
}
}
string name(SynthesizedLocal local)
{
if (!tempIdentifiers.TryGetValue(local, out int identifier))
{
identifier = tempIdentifiers.Count + 1;
tempIdentifiers.Add(local, identifier);
}
return "temp" + identifier.ToString();
}
void appendLocal(LocalSymbol symbol)
{
if (symbol is SynthesizedLocal synthesized)
{
append(name(synthesized));
}
else
{
append($"({symbol.GetDebuggerDisplay()})");
}
}
}
}
#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.Collections.Generic;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract partial class BoundNode
{
#if DEBUG
/// <summary>
/// Gives an approximate printout of a bound node as C# code.
/// </summary>
internal string DumpSource()
{
int indentSize = 4;
var builder = new StringBuilder();
appendSourceCore(this, indent: 0, tempIdentifiers: new Dictionary<SynthesizedLocal, int>());
return builder.ToString();
void appendSourceCore(BoundNode node, int indent, Dictionary<SynthesizedLocal, int> tempIdentifiers)
{
switch (node)
{
case BoundTryStatement tryStatement:
{
appendLine("try");
appendSource(tryStatement.TryBlock);
var catchBlocks = tryStatement.CatchBlocks;
if (catchBlocks != null)
{
foreach (var catchBlock in catchBlocks)
{
append("catch (");
append(catchBlock.ExceptionTypeOpt?.Name);
append(") ");
if (catchBlock.ExceptionFilterOpt != null)
{
append("... exception filter omitted ...");
}
appendLine("");
appendSource(catchBlock.Body);
}
}
var finallyBlock = tryStatement.FinallyBlockOpt;
if (finallyBlock != null)
{
appendLine("finally");
appendSource(finallyBlock);
}
break;
}
case BoundThrowStatement throwStatement:
{
append("throw ");
if (throwStatement.ExpressionOpt != null)
{
appendSource(throwStatement.ExpressionOpt);
}
appendLine(";");
break;
}
case BoundBlock block:
{
var statements = block.Statements;
if (statements.Length == 1 && block.Locals.IsEmpty)
{
appendSource(statements[0]);
break;
}
appendLine("{");
foreach (var local in block.Locals)
{
if (local is SynthesizedLocal synthesized)
{
appendLine($"{local.TypeWithAnnotations.ToDisplayString()} {name(synthesized)};");
}
else
{
appendLine($"({local.GetDebuggerDisplay()});");
}
}
foreach (var statement in statements)
{
appendSource(statement);
}
appendLine("}");
break;
}
case BoundStateMachineScope stateMachineScope:
{
appendSource(stateMachineScope.Statement);
break;
}
case BoundSequencePoint seqPoint:
{
var statement = seqPoint.StatementOpt;
if (statement != null)
{
appendSource(statement);
}
break;
}
case BoundSequencePointExpression seqPoint:
{
var expression = seqPoint.Expression;
appendSource(expression);
break;
}
case BoundSequencePointWithSpan seqPoint:
{
var statement = seqPoint.StatementOpt;
if (statement != null)
{
appendSource(statement);
}
break;
}
case BoundYieldReturnStatement yieldStatement:
{
append("yield return ");
appendSource(yieldStatement.Expression);
appendLine(";");
break;
}
case BoundReturnStatement returnStatement:
{
append("return");
var value = returnStatement.ExpressionOpt;
if (value != null)
{
append(" ");
appendSource(value);
}
appendLine(";");
break;
}
case BoundGotoStatement gotoStatement:
{
append("goto ");
append(gotoStatement.Label.ToString());
appendLine(";");
break;
}
case BoundConditionalGoto gotoStatement:
{
append("if (");
append(gotoStatement.JumpIfTrue ? "" : "!");
appendSource(gotoStatement.Condition);
append(") ");
append("goto ");
append(gotoStatement.Label.ToString());
appendLine(";");
break;
}
case BoundLabelStatement label:
{
append(label.Label.ToString());
appendLine(": ;");
break;
}
case BoundTypeExpression type:
{
append(type.Type.Name);
break;
}
case BoundLocal local:
{
var symbol = local.LocalSymbol;
appendLocal(symbol);
break;
}
case BoundNoOpStatement noop:
{
break;
}
case BoundExpressionStatement expressionStatement:
{
appendSource(expressionStatement.Expression);
appendLine(";");
break;
}
case BoundAwaitExpression awaitExpression:
{
append("await ");
appendSource(awaitExpression.Expression);
break;
}
case BoundCall call:
{
var receiver = call.ReceiverOpt;
if (receiver != null)
{
appendSource(receiver);
append(".");
}
append(call.Method.Name);
append("(");
bool first = true;
foreach (var argument in call.Arguments)
{
if (!first)
{
append(", ");
}
first = false;
appendSource(argument);
}
append(")");
break;
}
case BoundLiteral literal:
{
var value = literal.ConstantValue?.Value?.ToString();
if (value is null)
{
append("null");
break;
}
switch (literal.ConstantValue?.Discriminator)
{
case ConstantValueTypeDiscriminator.String:
append($@"""{value}""");
break;
default:
append(value);
break;
}
break;
}
case BoundAssignmentOperator assignment:
{
appendSource(assignment.Left);
append(" = ");
appendSource(assignment.Right);
break;
}
case BoundThisReference thisReference:
{
append("this");
break;
}
case BoundFieldAccess fieldAccess:
{
var receiver = fieldAccess.ReceiverOpt;
if (receiver != null)
{
appendSource(receiver);
append(".");
}
append(fieldAccess.FieldSymbol.Name);
break;
}
case BoundSwitchStatement switchStatement:
{
append("switch (");
appendSource(switchStatement.Expression);
appendLine(")");
appendLine("{");
foreach (BoundSwitchSection section in switchStatement.SwitchSections)
{
foreach (var label in section.SwitchLabels)
{
append("case ");
appendSource(label);
appendLine(":");
}
incrementIndent();
foreach (var statement in section.Statements)
{
appendSource(statement);
}
appendLine("break;");
decrementIndent();
}
appendLine("}");
break;
}
case BoundSwitchLabel label:
{
appendSource(label.Pattern);
break;
}
case BoundUnaryOperator unary:
{
append($" {unary.OperatorKind.ToString()} ");
appendSource(unary.Operand);
break;
}
case BoundStatementList list:
{
foreach (var statement in list.Statements)
{
appendSource(statement);
}
break;
}
case BoundSequence sequence:
{
append("{ ");
foreach (var effect in sequence.SideEffects)
{
appendSource(effect);
append("; ");
}
appendSource(sequence.Value);
append(" }");
break;
}
case BoundDefaultLiteral _:
case BoundDefaultExpression _:
{
append("default");
break;
}
case BoundBinaryOperator binary:
{
appendSource(binary.Left);
append(" ");
append(binary.OperatorKind.ToString());
append(" ");
appendSource(binary.Right);
break;
}
default:
appendLine(node.Kind.ToString());
break;
}
void appendSource(BoundNode? n)
{
if (n is null)
{
append("NULL");
}
else
{
appendSourceCore(n, indent, tempIdentifiers);
}
}
void append(string? s)
{
builder.Append(s);
}
void incrementIndent()
{
indent += indentSize;
builder.Append(' ', indentSize);
}
void decrementIndent()
{
indent -= indentSize;
builder.Remove(builder.Length - indentSize, indentSize);
}
void appendLine(string s)
{
if (s == "{")
{
indent += indentSize;
builder.AppendLine(s);
builder.Append(' ', indent);
}
else if (s == "}")
{
builder.Remove(builder.Length - indentSize, indentSize);
builder.AppendLine(s);
indent -= indentSize;
builder.Append(' ', indent);
}
else
{
builder.AppendLine(s);
builder.Append(' ', indent);
}
}
string name(SynthesizedLocal local)
{
if (!tempIdentifiers.TryGetValue(local, out int identifier))
{
identifier = tempIdentifiers.Count + 1;
tempIdentifiers.Add(local, identifier);
}
return "temp" + identifier.ToString();
}
void appendLocal(LocalSymbol symbol)
{
if (symbol is SynthesizedLocal synthesized)
{
append(name(synthesized));
}
else
{
append($"({symbol.GetDebuggerDisplay()})");
}
}
}
}
#endif
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Compilers/CSharp/Portable/BoundTree/Expression.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class BoundObjectCreationExpression : IBoundInvalidNode
{
internal static ImmutableArray<BoundExpression> GetChildInitializers(BoundExpression? objectOrCollectionInitializer)
{
var objectInitializerExpression = objectOrCollectionInitializer as BoundObjectInitializerExpression;
if (objectInitializerExpression != null)
{
return objectInitializerExpression.Initializers;
}
var collectionInitializerExpression = objectOrCollectionInitializer as BoundCollectionInitializerExpression;
if (collectionInitializerExpression != null)
{
return collectionInitializerExpression.Initializers;
}
return ImmutableArray<BoundExpression>.Empty;
}
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(receiverOpt: null, Arguments, InitializerExpressionOpt);
}
internal sealed partial class BoundObjectInitializerMember : IBoundInvalidNode
{
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => StaticCast<BoundNode>.From(Arguments);
}
internal sealed partial class BoundCollectionElementInitializer : IBoundInvalidNode
{
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(ImplicitReceiverOpt, Arguments);
}
internal sealed partial class BoundDeconstructionAssignmentOperator : BoundExpression
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Left, this.Right);
}
internal partial class BoundBadExpression : IBoundInvalidNode
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.ChildBoundNodes);
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => StaticCast<BoundNode>.From(this.ChildBoundNodes);
}
internal partial class BoundCall : IBoundInvalidNode
{
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(ReceiverOpt, Arguments);
}
internal partial class BoundIndexerAccess : IBoundInvalidNode
{
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(ReceiverOpt, Arguments);
}
internal partial class BoundDynamicIndexerAccess
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.Arguments.Insert(0, this.Receiver));
}
internal partial class BoundAnonymousObjectCreationExpression
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.Arguments);
}
internal partial class BoundAttribute
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.ConstructorArguments.AddRange(StaticCast<BoundExpression>.From(this.NamedArguments)));
}
internal partial class BoundQueryClause
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Value);
}
internal partial class BoundArgListOperator
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.Arguments);
}
internal partial class BoundNameOfOperator
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Argument);
}
internal partial class BoundPointerElementAccess
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Expression, this.Index);
}
internal partial class BoundRefTypeOperator
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Operand);
}
internal partial class BoundDynamicMemberAccess
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Receiver);
}
internal partial class BoundMakeRefOperator
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Operand);
}
internal partial class BoundRefValueOperator
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Operand);
}
internal partial class BoundDynamicInvocation
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.Arguments.Insert(0, this.Expression));
}
internal partial class BoundFixedLocalCollectionInitializer
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Expression);
}
internal partial class BoundStackAllocArrayCreationBase
{
internal static ImmutableArray<BoundExpression> GetChildInitializers(BoundArrayInitialization? arrayInitializer)
{
return arrayInitializer?.Initializers ?? ImmutableArray<BoundExpression>.Empty;
}
}
internal partial class BoundStackAllocArrayCreation
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(GetChildInitializers(this.InitializerOpt).Insert(0, this.Count));
}
internal partial class BoundConvertedStackAllocExpression
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(GetChildInitializers(this.InitializerOpt).Insert(0, this.Count));
}
internal partial class BoundDynamicObjectCreationExpression
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.Arguments.AddRange(BoundObjectCreationExpression.GetChildInitializers(this.InitializerExpressionOpt)));
}
partial class BoundThrowExpression
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Expression);
}
internal abstract partial class BoundMethodOrPropertyGroup
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.ReceiverOpt);
}
internal partial class BoundSequence
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.SideEffects.Add(this.Value));
}
internal partial class BoundStatementList
{
protected override ImmutableArray<BoundNode?> Children =>
(this.Kind == BoundKind.StatementList || this.Kind == BoundKind.Scope) ? StaticCast<BoundNode?>.From(this.Statements) : ImmutableArray<BoundNode?>.Empty;
}
internal partial class BoundPassByCopy
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Expression);
}
internal partial class BoundIndexOrRangePatternIndexerAccess
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(Receiver, Argument);
}
internal partial class BoundFunctionPointerInvocation : IBoundInvalidNode
{
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(receiverOpt: this.InvokedExpression, Arguments);
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(((IBoundInvalidNode)this).InvalidNodeChildren);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class BoundObjectCreationExpression : IBoundInvalidNode
{
internal static ImmutableArray<BoundExpression> GetChildInitializers(BoundExpression? objectOrCollectionInitializer)
{
var objectInitializerExpression = objectOrCollectionInitializer as BoundObjectInitializerExpression;
if (objectInitializerExpression != null)
{
return objectInitializerExpression.Initializers;
}
var collectionInitializerExpression = objectOrCollectionInitializer as BoundCollectionInitializerExpression;
if (collectionInitializerExpression != null)
{
return collectionInitializerExpression.Initializers;
}
return ImmutableArray<BoundExpression>.Empty;
}
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(receiverOpt: null, Arguments, InitializerExpressionOpt);
}
internal sealed partial class BoundObjectInitializerMember : IBoundInvalidNode
{
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => StaticCast<BoundNode>.From(Arguments);
}
internal sealed partial class BoundCollectionElementInitializer : IBoundInvalidNode
{
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(ImplicitReceiverOpt, Arguments);
}
internal sealed partial class BoundDeconstructionAssignmentOperator : BoundExpression
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Left, this.Right);
}
internal partial class BoundBadExpression : IBoundInvalidNode
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.ChildBoundNodes);
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => StaticCast<BoundNode>.From(this.ChildBoundNodes);
}
internal partial class BoundCall : IBoundInvalidNode
{
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(ReceiverOpt, Arguments);
}
internal partial class BoundIndexerAccess : IBoundInvalidNode
{
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(ReceiverOpt, Arguments);
}
internal partial class BoundDynamicIndexerAccess
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.Arguments.Insert(0, this.Receiver));
}
internal partial class BoundAnonymousObjectCreationExpression
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.Arguments);
}
internal partial class BoundAttribute
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.ConstructorArguments.AddRange(StaticCast<BoundExpression>.From(this.NamedArguments)));
}
internal partial class BoundQueryClause
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Value);
}
internal partial class BoundArgListOperator
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.Arguments);
}
internal partial class BoundNameOfOperator
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Argument);
}
internal partial class BoundPointerElementAccess
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Expression, this.Index);
}
internal partial class BoundRefTypeOperator
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Operand);
}
internal partial class BoundDynamicMemberAccess
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Receiver);
}
internal partial class BoundMakeRefOperator
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Operand);
}
internal partial class BoundRefValueOperator
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Operand);
}
internal partial class BoundDynamicInvocation
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.Arguments.Insert(0, this.Expression));
}
internal partial class BoundFixedLocalCollectionInitializer
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Expression);
}
internal partial class BoundStackAllocArrayCreationBase
{
internal static ImmutableArray<BoundExpression> GetChildInitializers(BoundArrayInitialization? arrayInitializer)
{
return arrayInitializer?.Initializers ?? ImmutableArray<BoundExpression>.Empty;
}
}
internal partial class BoundStackAllocArrayCreation
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(GetChildInitializers(this.InitializerOpt).Insert(0, this.Count));
}
internal partial class BoundConvertedStackAllocExpression
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(GetChildInitializers(this.InitializerOpt).Insert(0, this.Count));
}
internal partial class BoundDynamicObjectCreationExpression
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.Arguments.AddRange(BoundObjectCreationExpression.GetChildInitializers(this.InitializerExpressionOpt)));
}
partial class BoundThrowExpression
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Expression);
}
internal abstract partial class BoundMethodOrPropertyGroup
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.ReceiverOpt);
}
internal partial class BoundSequence
{
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(this.SideEffects.Add(this.Value));
}
internal partial class BoundStatementList
{
protected override ImmutableArray<BoundNode?> Children =>
(this.Kind == BoundKind.StatementList || this.Kind == BoundKind.Scope) ? StaticCast<BoundNode?>.From(this.Statements) : ImmutableArray<BoundNode?>.Empty;
}
internal partial class BoundPassByCopy
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(this.Expression);
}
internal partial class BoundIndexOrRangePatternIndexerAccess
{
protected override ImmutableArray<BoundNode?> Children => ImmutableArray.Create<BoundNode?>(Receiver, Argument);
}
internal partial class BoundFunctionPointerInvocation : IBoundInvalidNode
{
ImmutableArray<BoundNode> IBoundInvalidNode.InvalidNodeChildren => CSharpOperationFactory.CreateInvalidChildrenFromArgumentsExpression(receiverOpt: this.InvokedExpression, Arguments);
protected override ImmutableArray<BoundNode?> Children => StaticCast<BoundNode?>.From(((IBoundInvalidNode)this).InvalidNodeChildren);
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Workspaces/Core/Portable/Indentation/AbstractIndentationService.Indenter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Indentation
{
internal abstract partial class AbstractIndentationService<TSyntaxRoot>
{
protected struct Indenter
{
private readonly AbstractIndentationService<TSyntaxRoot> _service;
public readonly OptionSet OptionSet;
public readonly IOptionService OptionService;
public readonly TextLine LineToBeIndented;
public readonly CancellationToken CancellationToken;
public readonly SyntacticDocument Document;
public readonly TSyntaxRoot Root;
public readonly IEnumerable<AbstractFormattingRule> Rules;
public readonly BottomUpBaseIndentationFinder Finder;
private readonly ISyntaxFactsService _syntaxFacts;
private readonly int _tabSize;
public readonly SyntaxTree Tree => Document.SyntaxTree;
public readonly SourceText Text => Document.Text;
public Indenter(
AbstractIndentationService<TSyntaxRoot> service,
SyntacticDocument document,
IEnumerable<AbstractFormattingRule> rules,
OptionSet optionSet,
TextLine lineToBeIndented,
CancellationToken cancellationToken)
{
Document = document;
_service = service;
_syntaxFacts = document.Document.GetRequiredLanguageService<ISyntaxFactsService>();
OptionSet = optionSet;
OptionService = document.Document.Project.Solution.Workspace.Services.GetRequiredService<IOptionService>();
Root = (TSyntaxRoot)document.Root;
LineToBeIndented = lineToBeIndented;
_tabSize = this.OptionSet.GetOption(FormattingOptions.TabSize, Root.Language);
CancellationToken = cancellationToken;
Rules = rules;
Finder = new BottomUpBaseIndentationFinder(
new ChainedFormattingRules(this.Rules, OptionSet.AsAnalyzerConfigOptions(OptionService, Root.Language)),
_tabSize,
this.OptionSet.GetOption(FormattingOptions.IndentationSize, Root.Language),
tokenStream: null,
_syntaxFacts);
}
public IndentationResult? GetDesiredIndentation(FormattingOptions.IndentStyle indentStyle)
{
// If the caller wants no indent, then we'll return an effective '0' indent.
if (indentStyle == FormattingOptions.IndentStyle.None)
return null;
// If the user has explicitly set 'block' indentation, or they're in an inactive preprocessor region,
// then just do simple block indentation.
if (indentStyle == FormattingOptions.IndentStyle.Block ||
_syntaxFacts.IsInInactiveRegion(Document.SyntaxTree, LineToBeIndented.Start, this.CancellationToken))
{
return GetDesiredBlockIndentation();
}
Debug.Assert(indentStyle == FormattingOptions.IndentStyle.Smart);
return GetDesiredSmartIndentation();
}
private readonly IndentationResult? GetDesiredSmartIndentation()
{
// For smart indent, we generally will be computing from either the previous token in the code, or in a
// few special cases, the previous trivia.
var token = TryGetPrecedingVisibleToken();
// Look to see if we're immediately following some visible piece of trivia. There may
// be some cases where we'll base our indent off of that. However, we only do this as
// long as we're immediately after the trivia. If there are any blank lines between us
// then we consider that unimportant for indentation.
var trivia = TryGetImmediatelyPrecedingVisibleTrivia();
if (token == null && trivia == null)
return null;
return _service.GetDesiredIndentationWorker(this, token, trivia);
}
private readonly SyntaxTrivia? TryGetImmediatelyPrecedingVisibleTrivia()
{
if (LineToBeIndented.LineNumber == 0)
return null;
var previousLine = this.Text.Lines[LineToBeIndented.LineNumber - 1];
var lastPos = previousLine.GetLastNonWhitespacePosition();
if (lastPos == null)
return null;
var trivia = Root.FindTrivia(lastPos.Value);
if (trivia == default)
return null;
return trivia;
}
private readonly SyntaxToken? TryGetPrecedingVisibleToken()
{
var token = Root.FindToken(LineToBeIndented.Start);
// we'll either be after the token at the end of a line, or before a token. We compute indentation
// based on the preceding token. So if we're before a token, look back to the previous token to
// determine what our indentation is based off of.
if (token.SpanStart >= LineToBeIndented.Start)
{
token = token.GetPreviousToken();
// Skip past preceding blank tokens. This can happen in VB for example where there can be
// whitespace tokens in things like xml literals. We want to get the first visible token that we
// would actually anch would anchor indentation off of.
while (token != default && string.IsNullOrWhiteSpace(token.ToString()))
token = token.GetPreviousToken();
}
if (token == default)
return null;
return token;
}
private IndentationResult? GetDesiredBlockIndentation()
{
// Block indentation is simple, we keep walking back lines until we find a line with any sort of
// text on it. We then set our indentation to whatever the indentation of that line was.
for (var currentLine = this.LineToBeIndented.LineNumber - 1; currentLine >= 0; currentLine--)
{
var line = this.Document.Text.Lines[currentLine];
var offset = line.GetFirstNonWhitespaceOffset();
if (offset == null)
continue;
// Found the previous non-blank line. indent to the same level that it is at
return new IndentationResult(basePosition: line.Start + offset.Value, offset: 0);
}
// Couldn't find a previous non-blank line.
return null;
}
public bool TryGetSmartTokenIndentation(out IndentationResult indentationResult)
{
if (_service.ShouldUseTokenIndenter(this, out var token))
{
// var root = document.GetSyntaxRootSynchronously(cancellationToken);
var sourceText = Tree.GetText(CancellationToken);
var formatter = _service.CreateSmartTokenFormatter(this);
var changes = formatter.FormatTokenAsync(Document.Project.Solution.Workspace, token, CancellationToken)
.WaitAndGetResult(CancellationToken);
var updatedSourceText = sourceText.WithChanges(changes);
if (LineToBeIndented.LineNumber < updatedSourceText.Lines.Count)
{
var updatedLine = updatedSourceText.Lines[LineToBeIndented.LineNumber];
var nonWhitespaceOffset = updatedLine.GetFirstNonWhitespaceOffset();
if (nonWhitespaceOffset != null)
{
// 'nonWhitespaceOffset' is simply an int indicating how many
// *characters* of indentation to include. For example, an indentation
// string of \t\t\t would just count for nonWhitespaceOffset of '3' (one
// for each tab char).
//
// However, what we want is the true columnar offset for the line.
// That's what our caller (normally the editor) needs to determine where
// to actually put the caret and what whitespace needs to proceed it.
//
// This can be computed with GetColumnFromLineOffset which again looks
// at the contents of the line, but this time evaluates how \t characters
// should translate to column chars.
var offset = updatedLine.GetColumnFromLineOffset(nonWhitespaceOffset.Value, _tabSize);
indentationResult = new IndentationResult(basePosition: LineToBeIndented.Start, offset: offset);
return true;
}
}
}
indentationResult = default;
return false;
}
public IndentationResult IndentFromStartOfLine(int addedSpaces)
=> new(this.LineToBeIndented.Start, addedSpaces);
public IndentationResult GetIndentationOfToken(SyntaxToken token)
=> GetIndentationOfToken(token, addedSpaces: 0);
public IndentationResult GetIndentationOfToken(SyntaxToken token, int addedSpaces)
=> GetIndentationOfPosition(token.SpanStart, addedSpaces);
public IndentationResult GetIndentationOfLine(TextLine lineToMatch)
=> GetIndentationOfLine(lineToMatch, addedSpaces: 0);
public IndentationResult GetIndentationOfLine(TextLine lineToMatch, int addedSpaces)
{
var firstNonWhitespace = lineToMatch.GetFirstNonWhitespacePosition();
firstNonWhitespace ??= lineToMatch.End;
return GetIndentationOfPosition(firstNonWhitespace.Value, addedSpaces);
}
private IndentationResult GetIndentationOfPosition(int position, int addedSpaces)
{
if (this.Tree.OverlapsHiddenPosition(GetNormalizedSpan(position), CancellationToken))
{
// Oops, the line we want to line up to is either hidden, or is in a different
// visible region.
var token = Root.FindTokenFromEnd(LineToBeIndented.Start);
var indentation = Finder.GetIndentationOfCurrentPosition(this.Tree, token, LineToBeIndented.Start, CancellationToken.None);
return new IndentationResult(LineToBeIndented.Start, indentation);
}
return new IndentationResult(position, addedSpaces);
}
private TextSpan GetNormalizedSpan(int position)
{
if (LineToBeIndented.Start < position)
{
return TextSpan.FromBounds(LineToBeIndented.Start, position);
}
return TextSpan.FromBounds(position, LineToBeIndented.Start);
}
public int GetCurrentPositionNotBelongToEndOfFileToken(int position)
=> Math.Min(Root.EndOfFileToken.FullSpan.Start, position);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Indentation
{
internal abstract partial class AbstractIndentationService<TSyntaxRoot>
{
protected struct Indenter
{
private readonly AbstractIndentationService<TSyntaxRoot> _service;
public readonly OptionSet OptionSet;
public readonly IOptionService OptionService;
public readonly TextLine LineToBeIndented;
public readonly CancellationToken CancellationToken;
public readonly SyntacticDocument Document;
public readonly TSyntaxRoot Root;
public readonly IEnumerable<AbstractFormattingRule> Rules;
public readonly BottomUpBaseIndentationFinder Finder;
private readonly ISyntaxFactsService _syntaxFacts;
private readonly int _tabSize;
public readonly SyntaxTree Tree => Document.SyntaxTree;
public readonly SourceText Text => Document.Text;
public Indenter(
AbstractIndentationService<TSyntaxRoot> service,
SyntacticDocument document,
IEnumerable<AbstractFormattingRule> rules,
OptionSet optionSet,
TextLine lineToBeIndented,
CancellationToken cancellationToken)
{
Document = document;
_service = service;
_syntaxFacts = document.Document.GetRequiredLanguageService<ISyntaxFactsService>();
OptionSet = optionSet;
OptionService = document.Document.Project.Solution.Workspace.Services.GetRequiredService<IOptionService>();
Root = (TSyntaxRoot)document.Root;
LineToBeIndented = lineToBeIndented;
_tabSize = this.OptionSet.GetOption(FormattingOptions.TabSize, Root.Language);
CancellationToken = cancellationToken;
Rules = rules;
Finder = new BottomUpBaseIndentationFinder(
new ChainedFormattingRules(this.Rules, OptionSet.AsAnalyzerConfigOptions(OptionService, Root.Language)),
_tabSize,
this.OptionSet.GetOption(FormattingOptions.IndentationSize, Root.Language),
tokenStream: null,
_syntaxFacts);
}
public IndentationResult? GetDesiredIndentation(FormattingOptions.IndentStyle indentStyle)
{
// If the caller wants no indent, then we'll return an effective '0' indent.
if (indentStyle == FormattingOptions.IndentStyle.None)
return null;
// If the user has explicitly set 'block' indentation, or they're in an inactive preprocessor region,
// then just do simple block indentation.
if (indentStyle == FormattingOptions.IndentStyle.Block ||
_syntaxFacts.IsInInactiveRegion(Document.SyntaxTree, LineToBeIndented.Start, this.CancellationToken))
{
return GetDesiredBlockIndentation();
}
Debug.Assert(indentStyle == FormattingOptions.IndentStyle.Smart);
return GetDesiredSmartIndentation();
}
private readonly IndentationResult? GetDesiredSmartIndentation()
{
// For smart indent, we generally will be computing from either the previous token in the code, or in a
// few special cases, the previous trivia.
var token = TryGetPrecedingVisibleToken();
// Look to see if we're immediately following some visible piece of trivia. There may
// be some cases where we'll base our indent off of that. However, we only do this as
// long as we're immediately after the trivia. If there are any blank lines between us
// then we consider that unimportant for indentation.
var trivia = TryGetImmediatelyPrecedingVisibleTrivia();
if (token == null && trivia == null)
return null;
return _service.GetDesiredIndentationWorker(this, token, trivia);
}
private readonly SyntaxTrivia? TryGetImmediatelyPrecedingVisibleTrivia()
{
if (LineToBeIndented.LineNumber == 0)
return null;
var previousLine = this.Text.Lines[LineToBeIndented.LineNumber - 1];
var lastPos = previousLine.GetLastNonWhitespacePosition();
if (lastPos == null)
return null;
var trivia = Root.FindTrivia(lastPos.Value);
if (trivia == default)
return null;
return trivia;
}
private readonly SyntaxToken? TryGetPrecedingVisibleToken()
{
var token = Root.FindToken(LineToBeIndented.Start);
// we'll either be after the token at the end of a line, or before a token. We compute indentation
// based on the preceding token. So if we're before a token, look back to the previous token to
// determine what our indentation is based off of.
if (token.SpanStart >= LineToBeIndented.Start)
{
token = token.GetPreviousToken();
// Skip past preceding blank tokens. This can happen in VB for example where there can be
// whitespace tokens in things like xml literals. We want to get the first visible token that we
// would actually anch would anchor indentation off of.
while (token != default && string.IsNullOrWhiteSpace(token.ToString()))
token = token.GetPreviousToken();
}
if (token == default)
return null;
return token;
}
private IndentationResult? GetDesiredBlockIndentation()
{
// Block indentation is simple, we keep walking back lines until we find a line with any sort of
// text on it. We then set our indentation to whatever the indentation of that line was.
for (var currentLine = this.LineToBeIndented.LineNumber - 1; currentLine >= 0; currentLine--)
{
var line = this.Document.Text.Lines[currentLine];
var offset = line.GetFirstNonWhitespaceOffset();
if (offset == null)
continue;
// Found the previous non-blank line. indent to the same level that it is at
return new IndentationResult(basePosition: line.Start + offset.Value, offset: 0);
}
// Couldn't find a previous non-blank line.
return null;
}
public bool TryGetSmartTokenIndentation(out IndentationResult indentationResult)
{
if (_service.ShouldUseTokenIndenter(this, out var token))
{
// var root = document.GetSyntaxRootSynchronously(cancellationToken);
var sourceText = Tree.GetText(CancellationToken);
var formatter = _service.CreateSmartTokenFormatter(this);
var changes = formatter.FormatTokenAsync(Document.Project.Solution.Workspace, token, CancellationToken)
.WaitAndGetResult(CancellationToken);
var updatedSourceText = sourceText.WithChanges(changes);
if (LineToBeIndented.LineNumber < updatedSourceText.Lines.Count)
{
var updatedLine = updatedSourceText.Lines[LineToBeIndented.LineNumber];
var nonWhitespaceOffset = updatedLine.GetFirstNonWhitespaceOffset();
if (nonWhitespaceOffset != null)
{
// 'nonWhitespaceOffset' is simply an int indicating how many
// *characters* of indentation to include. For example, an indentation
// string of \t\t\t would just count for nonWhitespaceOffset of '3' (one
// for each tab char).
//
// However, what we want is the true columnar offset for the line.
// That's what our caller (normally the editor) needs to determine where
// to actually put the caret and what whitespace needs to proceed it.
//
// This can be computed with GetColumnFromLineOffset which again looks
// at the contents of the line, but this time evaluates how \t characters
// should translate to column chars.
var offset = updatedLine.GetColumnFromLineOffset(nonWhitespaceOffset.Value, _tabSize);
indentationResult = new IndentationResult(basePosition: LineToBeIndented.Start, offset: offset);
return true;
}
}
}
indentationResult = default;
return false;
}
public IndentationResult IndentFromStartOfLine(int addedSpaces)
=> new(this.LineToBeIndented.Start, addedSpaces);
public IndentationResult GetIndentationOfToken(SyntaxToken token)
=> GetIndentationOfToken(token, addedSpaces: 0);
public IndentationResult GetIndentationOfToken(SyntaxToken token, int addedSpaces)
=> GetIndentationOfPosition(token.SpanStart, addedSpaces);
public IndentationResult GetIndentationOfLine(TextLine lineToMatch)
=> GetIndentationOfLine(lineToMatch, addedSpaces: 0);
public IndentationResult GetIndentationOfLine(TextLine lineToMatch, int addedSpaces)
{
var firstNonWhitespace = lineToMatch.GetFirstNonWhitespacePosition();
firstNonWhitespace ??= lineToMatch.End;
return GetIndentationOfPosition(firstNonWhitespace.Value, addedSpaces);
}
private IndentationResult GetIndentationOfPosition(int position, int addedSpaces)
{
if (this.Tree.OverlapsHiddenPosition(GetNormalizedSpan(position), CancellationToken))
{
// Oops, the line we want to line up to is either hidden, or is in a different
// visible region.
var token = Root.FindTokenFromEnd(LineToBeIndented.Start);
var indentation = Finder.GetIndentationOfCurrentPosition(this.Tree, token, LineToBeIndented.Start, CancellationToken.None);
return new IndentationResult(LineToBeIndented.Start, indentation);
}
return new IndentationResult(position, addedSpaces);
}
private TextSpan GetNormalizedSpan(int position)
{
if (LineToBeIndented.Start < position)
{
return TextSpan.FromBounds(LineToBeIndented.Start, position);
}
return TextSpan.FromBounds(position, LineToBeIndented.Start);
}
public int GetCurrentPositionNotBelongToEndOfFileToken(int position)
=> Math.Min(Root.EndOfFileToken.FullSpan.Start, position);
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Compilers/Core/Portable/Text/TextLineCollection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// Abstract base class for <see cref="TextLine"/> collections.
/// </summary>
public abstract class TextLineCollection : IReadOnlyList<TextLine>
{
/// <summary>
/// The count of <see cref="TextLine"/> items in the collection
/// </summary>
public abstract int Count { get; }
/// <summary>
/// Gets the <see cref="TextLine"/> item at the specified index.
/// </summary>
public abstract TextLine this[int index] { get; }
/// <summary>
/// The index of the TextLine that encompasses the character position.
/// </summary>
public abstract int IndexOf(int position);
/// <summary>
/// Gets a <see cref="TextLine"/> that encompasses the character position.
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public virtual TextLine GetLineFromPosition(int position)
{
return this[this.IndexOf(position)];
}
/// <summary>
/// Gets a <see cref="LinePosition"/> corresponding to a character position.
/// </summary>
public virtual LinePosition GetLinePosition(int position)
{
var line = GetLineFromPosition(position);
return new LinePosition(line.LineNumber, position - line.Start);
}
/// <summary>
/// Convert a <see cref="TextSpan"/> to a <see cref="LinePositionSpan"/>.
/// </summary>
public LinePositionSpan GetLinePositionSpan(TextSpan span)
{
return new LinePositionSpan(GetLinePosition(span.Start), GetLinePosition(span.End));
}
/// <summary>
/// Convert a <see cref="LinePosition"/> to a position.
/// </summary>
public int GetPosition(LinePosition position)
{
return this[position.Line].Start + position.Character;
}
/// <summary>
/// Convert a <see cref="LinePositionSpan"/> to <see cref="TextSpan"/>.
/// </summary>
public TextSpan GetTextSpan(LinePositionSpan span)
{
return TextSpan.FromBounds(GetPosition(span.Start), GetPosition(span.End));
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<TextLine> IEnumerable<TextLine>.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
[SuppressMessage("Performance", "CA1067", Justification = "Equality not actually implemented")]
public struct Enumerator : IEnumerator<TextLine>, IEnumerator
{
private readonly TextLineCollection _lines;
private int _index;
internal Enumerator(TextLineCollection lines, int index = -1)
{
_lines = lines;
_index = index;
}
public TextLine Current
{
get
{
var ndx = _index;
if (ndx >= 0 && ndx < _lines.Count)
{
return _lines[ndx];
}
else
{
return default(TextLine);
}
}
}
public bool MoveNext()
{
if (_index < _lines.Count - 1)
{
_index = _index + 1;
return true;
}
return false;
}
object IEnumerator.Current
{
get { return this.Current; }
}
bool IEnumerator.MoveNext()
{
return this.MoveNext();
}
void IEnumerator.Reset()
{
}
void IDisposable.Dispose()
{
}
public override bool Equals(object? obj)
{
throw new NotSupportedException();
}
public override int GetHashCode()
{
throw new NotSupportedException();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Text
{
/// <summary>
/// Abstract base class for <see cref="TextLine"/> collections.
/// </summary>
public abstract class TextLineCollection : IReadOnlyList<TextLine>
{
/// <summary>
/// The count of <see cref="TextLine"/> items in the collection
/// </summary>
public abstract int Count { get; }
/// <summary>
/// Gets the <see cref="TextLine"/> item at the specified index.
/// </summary>
public abstract TextLine this[int index] { get; }
/// <summary>
/// The index of the TextLine that encompasses the character position.
/// </summary>
public abstract int IndexOf(int position);
/// <summary>
/// Gets a <see cref="TextLine"/> that encompasses the character position.
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public virtual TextLine GetLineFromPosition(int position)
{
return this[this.IndexOf(position)];
}
/// <summary>
/// Gets a <see cref="LinePosition"/> corresponding to a character position.
/// </summary>
public virtual LinePosition GetLinePosition(int position)
{
var line = GetLineFromPosition(position);
return new LinePosition(line.LineNumber, position - line.Start);
}
/// <summary>
/// Convert a <see cref="TextSpan"/> to a <see cref="LinePositionSpan"/>.
/// </summary>
public LinePositionSpan GetLinePositionSpan(TextSpan span)
{
return new LinePositionSpan(GetLinePosition(span.Start), GetLinePosition(span.End));
}
/// <summary>
/// Convert a <see cref="LinePosition"/> to a position.
/// </summary>
public int GetPosition(LinePosition position)
{
return this[position.Line].Start + position.Character;
}
/// <summary>
/// Convert a <see cref="LinePositionSpan"/> to <see cref="TextSpan"/>.
/// </summary>
public TextSpan GetTextSpan(LinePositionSpan span)
{
return TextSpan.FromBounds(GetPosition(span.Start), GetPosition(span.End));
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<TextLine> IEnumerable<TextLine>.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
[SuppressMessage("Performance", "CA1067", Justification = "Equality not actually implemented")]
public struct Enumerator : IEnumerator<TextLine>, IEnumerator
{
private readonly TextLineCollection _lines;
private int _index;
internal Enumerator(TextLineCollection lines, int index = -1)
{
_lines = lines;
_index = index;
}
public TextLine Current
{
get
{
var ndx = _index;
if (ndx >= 0 && ndx < _lines.Count)
{
return _lines[ndx];
}
else
{
return default(TextLine);
}
}
}
public bool MoveNext()
{
if (_index < _lines.Count - 1)
{
_index = _index + 1;
return true;
}
return false;
}
object IEnumerator.Current
{
get { return this.Current; }
}
bool IEnumerator.MoveNext()
{
return this.MoveNext();
}
void IEnumerator.Reset()
{
}
void IDisposable.Dispose()
{
}
public override bool Equals(object? obj)
{
throw new NotSupportedException();
}
public override int GetHashCode()
{
throw new NotSupportedException();
}
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/VisualStudio/Core/Def/Implementation/AnalyzerDependency/AnalyzerDependencyResults.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal sealed class AnalyzerDependencyResults
{
public static readonly AnalyzerDependencyResults Empty = new(ImmutableArray<AnalyzerDependencyConflict>.Empty, ImmutableArray<MissingAnalyzerDependency>.Empty);
public AnalyzerDependencyResults(ImmutableArray<AnalyzerDependencyConflict> conflicts, ImmutableArray<MissingAnalyzerDependency> missingDependencies)
{
Debug.Assert(conflicts != default);
Debug.Assert(missingDependencies != default);
Conflicts = conflicts;
MissingDependencies = missingDependencies;
}
public ImmutableArray<AnalyzerDependencyConflict> Conflicts { get; }
public ImmutableArray<MissingAnalyzerDependency> MissingDependencies { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal sealed class AnalyzerDependencyResults
{
public static readonly AnalyzerDependencyResults Empty = new(ImmutableArray<AnalyzerDependencyConflict>.Empty, ImmutableArray<MissingAnalyzerDependency>.Empty);
public AnalyzerDependencyResults(ImmutableArray<AnalyzerDependencyConflict> conflicts, ImmutableArray<MissingAnalyzerDependency> missingDependencies)
{
Debug.Assert(conflicts != default);
Debug.Assert(missingDependencies != default);
Conflicts = conflicts;
MissingDependencies = missingDependencies;
}
public ImmutableArray<AnalyzerDependencyConflict> Conflicts { get; }
public ImmutableArray<MissingAnalyzerDependency> MissingDependencies { get; }
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractMergeConsecutiveIfStatementsCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeActions;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements
{
internal abstract class AbstractMergeConsecutiveIfStatementsCodeRefactoringProvider
: AbstractMergeIfStatementsCodeRefactoringProvider
{
// Converts:
// if (a)
// Console.WriteLine();
// else if (b)
// Console.WriteLine();
//
// To:
// if (a || b)
// Console.WriteLine();
// Converts:
// if (a)
// return;
// if (b)
// return;
//
// To:
// if (a || b)
// return;
// The body statements need to be equivalent. In the second case, control flow must quit from inside the body.
protected sealed override CodeAction CreateCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, MergeDirection direction, string ifKeywordText)
{
var resourceText = direction == MergeDirection.Up ? FeaturesResources.Merge_with_previous_0_statement : FeaturesResources.Merge_with_next_0_statement;
return new MyCodeAction(string.Format(resourceText, ifKeywordText), createChangedDocument);
}
protected sealed override Task<bool> CanBeMergedUpAsync(
Document document, SyntaxNode ifOrElseIf, CancellationToken cancellationToken, out SyntaxNode firstIfOrElseIf)
{
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>();
if (CanBeMergedWithParent(syntaxFacts, ifGenerator, ifOrElseIf, out firstIfOrElseIf))
return SpecializedTasks.True;
return CanBeMergedWithPreviousStatementAsync(document, syntaxFacts, ifGenerator, ifOrElseIf, cancellationToken, out firstIfOrElseIf);
}
protected sealed override Task<bool> CanBeMergedDownAsync(
Document document, SyntaxNode ifOrElseIf, CancellationToken cancellationToken, out SyntaxNode secondIfOrElseIf)
{
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>();
if (CanBeMergedWithElseIf(syntaxFacts, ifGenerator, ifOrElseIf, out secondIfOrElseIf))
return SpecializedTasks.True;
return CanBeMergedWithNextStatementAsync(document, syntaxFacts, ifGenerator, ifOrElseIf, cancellationToken, out secondIfOrElseIf);
}
protected sealed override SyntaxNode GetChangedRoot(Document document, SyntaxNode root, SyntaxNode firstIfOrElseIf, SyntaxNode secondIfOrElseIf)
{
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>();
var generator = document.GetLanguageService<SyntaxGenerator>();
var newCondition = generator.LogicalOrExpression(
ifGenerator.GetCondition(firstIfOrElseIf),
ifGenerator.GetCondition(secondIfOrElseIf));
newCondition = newCondition.WithAdditionalAnnotations(Formatter.Annotation);
var editor = new SyntaxEditor(root, generator);
editor.ReplaceNode(firstIfOrElseIf, (currentNode, _) => ifGenerator.WithCondition(currentNode, newCondition));
if (ifGenerator.IsElseIfClause(secondIfOrElseIf, out _))
{
// We have:
// if (a)
// Console.WriteLine();
// else if (b)
// Console.WriteLine();
// Remove the else-if clause and preserve any subsequent clauses.
ifGenerator.RemoveElseIfClause(editor, secondIfOrElseIf);
}
else
{
// We have:
// if (a)
// return;
// if (b)
// return;
// At this point, ifLikeStatement must be a standalone if statement, possibly with an else clause (there won't
// be any on the first statement though). We'll move any else-if and else clauses to the first statement
// and then remove the second one.
// The opposite refactoring (SplitIntoConsecutiveIfStatements) never generates a separate statement
// with an else clause but we support it anyway (in inserts an else-if instead).
Debug.Assert(syntaxFacts.IsExecutableStatement(secondIfOrElseIf));
Debug.Assert(syntaxFacts.IsExecutableStatement(firstIfOrElseIf));
Debug.Assert(ifGenerator.GetElseIfAndElseClauses(firstIfOrElseIf).Length == 0);
editor.ReplaceNode(
firstIfOrElseIf,
(currentNode, _) => ifGenerator.WithElseIfAndElseClausesOf(currentNode, secondIfOrElseIf));
editor.RemoveNode(secondIfOrElseIf);
}
return editor.GetChangedRoot();
}
private static bool CanBeMergedWithParent(
ISyntaxFactsService syntaxFacts,
IIfLikeStatementGenerator ifGenerator,
SyntaxNode ifOrElseIf,
out SyntaxNode parentIfOrElseIf)
{
return ifGenerator.IsElseIfClause(ifOrElseIf, out parentIfOrElseIf) &&
ContainEquivalentStatements(syntaxFacts, ifOrElseIf, parentIfOrElseIf, out _);
}
private static bool CanBeMergedWithElseIf(
ISyntaxFactsService syntaxFacts,
IIfLikeStatementGenerator ifGenerator,
SyntaxNode ifOrElseIf,
out SyntaxNode elseIfClause)
{
return ifGenerator.HasElseIfClause(ifOrElseIf, out elseIfClause) &&
ContainEquivalentStatements(syntaxFacts, ifOrElseIf, elseIfClause, out _);
}
private static Task<bool> CanBeMergedWithPreviousStatementAsync(
Document document,
ISyntaxFactsService syntaxFacts,
IIfLikeStatementGenerator ifGenerator,
SyntaxNode ifOrElseIf,
CancellationToken cancellationToken,
out SyntaxNode previousStatement)
{
return TryGetSiblingStatement(syntaxFacts, ifOrElseIf, relativeIndex: -1, out previousStatement)
? CanStatementsBeMergedAsync(document, syntaxFacts, ifGenerator, previousStatement, ifOrElseIf, cancellationToken)
: SpecializedTasks.False;
}
private static Task<bool> CanBeMergedWithNextStatementAsync(
Document document,
ISyntaxFactsService syntaxFacts,
IIfLikeStatementGenerator ifGenerator,
SyntaxNode ifOrElseIf,
CancellationToken cancellationToken,
out SyntaxNode nextStatement)
{
return TryGetSiblingStatement(syntaxFacts, ifOrElseIf, relativeIndex: 1, out nextStatement)
? CanStatementsBeMergedAsync(document, syntaxFacts, ifGenerator, ifOrElseIf, nextStatement, cancellationToken)
: SpecializedTasks.False;
}
private static async Task<bool> CanStatementsBeMergedAsync(
Document document,
ISyntaxFactsService syntaxFacts,
IIfLikeStatementGenerator ifGenerator,
SyntaxNode firstStatement,
SyntaxNode secondStatement,
CancellationToken cancellationToken)
{
// We don't support cases where the previous if statement has any else-if or else clauses. In order for that
// to be mergable, the control flow would have to quit from inside every branch, which is getting a little complex.
if (!ifGenerator.IsIfOrElseIf(firstStatement) || ifGenerator.GetElseIfAndElseClauses(firstStatement).Length > 0)
return false;
if (!ifGenerator.IsIfOrElseIf(secondStatement))
return false;
if (!ContainEquivalentStatements(syntaxFacts, firstStatement, secondStatement, out var insideStatements))
return false;
if (insideStatements.Count == 0)
{
// Even though there are no statements inside, we still can't merge these into one statement
// because it would change the semantics from always evaluating the second condition to short-circuiting.
return false;
}
else
{
// There are statements inside. We can merge these into one statement if
// control flow can't reach the end of these statements (otherwise, it would change from running
// the second 'if' in the case that both conditions are true to only running the statements once).
// This will typically look like a single return, break, continue or a throw statement.
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var controlFlow = semanticModel.AnalyzeControlFlow(insideStatements[0], insideStatements[insideStatements.Count - 1]);
return !controlFlow.EndPointIsReachable;
}
}
private static bool TryGetSiblingStatement(
ISyntaxFactsService syntaxFacts, SyntaxNode ifOrElseIf, int relativeIndex, out SyntaxNode statement)
{
if (syntaxFacts.IsExecutableStatement(ifOrElseIf) &&
syntaxFacts.IsExecutableBlock(ifOrElseIf.Parent))
{
var blockStatements = syntaxFacts.GetExecutableBlockStatements(ifOrElseIf.Parent);
statement = blockStatements.ElementAtOrDefault(blockStatements.IndexOf(ifOrElseIf) + relativeIndex);
return statement != null;
}
statement = null;
return false;
}
private static bool ContainEquivalentStatements(
ISyntaxFactsService syntaxFacts,
SyntaxNode ifStatement1,
SyntaxNode ifStatement2,
out IReadOnlyList<SyntaxNode> statements)
{
var statements1 = WalkDownScopeBlocks(syntaxFacts, syntaxFacts.GetStatementContainerStatements(ifStatement1));
var statements2 = WalkDownScopeBlocks(syntaxFacts, syntaxFacts.GetStatementContainerStatements(ifStatement2));
statements = statements1;
return statements1.SequenceEqual(statements2, syntaxFacts.AreEquivalent);
}
private sealed class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements
{
internal abstract class AbstractMergeConsecutiveIfStatementsCodeRefactoringProvider
: AbstractMergeIfStatementsCodeRefactoringProvider
{
// Converts:
// if (a)
// Console.WriteLine();
// else if (b)
// Console.WriteLine();
//
// To:
// if (a || b)
// Console.WriteLine();
// Converts:
// if (a)
// return;
// if (b)
// return;
//
// To:
// if (a || b)
// return;
// The body statements need to be equivalent. In the second case, control flow must quit from inside the body.
protected sealed override CodeAction CreateCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, MergeDirection direction, string ifKeywordText)
{
var resourceText = direction == MergeDirection.Up ? FeaturesResources.Merge_with_previous_0_statement : FeaturesResources.Merge_with_next_0_statement;
return new MyCodeAction(string.Format(resourceText, ifKeywordText), createChangedDocument);
}
protected sealed override Task<bool> CanBeMergedUpAsync(
Document document, SyntaxNode ifOrElseIf, CancellationToken cancellationToken, out SyntaxNode firstIfOrElseIf)
{
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>();
if (CanBeMergedWithParent(syntaxFacts, ifGenerator, ifOrElseIf, out firstIfOrElseIf))
return SpecializedTasks.True;
return CanBeMergedWithPreviousStatementAsync(document, syntaxFacts, ifGenerator, ifOrElseIf, cancellationToken, out firstIfOrElseIf);
}
protected sealed override Task<bool> CanBeMergedDownAsync(
Document document, SyntaxNode ifOrElseIf, CancellationToken cancellationToken, out SyntaxNode secondIfOrElseIf)
{
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>();
if (CanBeMergedWithElseIf(syntaxFacts, ifGenerator, ifOrElseIf, out secondIfOrElseIf))
return SpecializedTasks.True;
return CanBeMergedWithNextStatementAsync(document, syntaxFacts, ifGenerator, ifOrElseIf, cancellationToken, out secondIfOrElseIf);
}
protected sealed override SyntaxNode GetChangedRoot(Document document, SyntaxNode root, SyntaxNode firstIfOrElseIf, SyntaxNode secondIfOrElseIf)
{
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>();
var generator = document.GetLanguageService<SyntaxGenerator>();
var newCondition = generator.LogicalOrExpression(
ifGenerator.GetCondition(firstIfOrElseIf),
ifGenerator.GetCondition(secondIfOrElseIf));
newCondition = newCondition.WithAdditionalAnnotations(Formatter.Annotation);
var editor = new SyntaxEditor(root, generator);
editor.ReplaceNode(firstIfOrElseIf, (currentNode, _) => ifGenerator.WithCondition(currentNode, newCondition));
if (ifGenerator.IsElseIfClause(secondIfOrElseIf, out _))
{
// We have:
// if (a)
// Console.WriteLine();
// else if (b)
// Console.WriteLine();
// Remove the else-if clause and preserve any subsequent clauses.
ifGenerator.RemoveElseIfClause(editor, secondIfOrElseIf);
}
else
{
// We have:
// if (a)
// return;
// if (b)
// return;
// At this point, ifLikeStatement must be a standalone if statement, possibly with an else clause (there won't
// be any on the first statement though). We'll move any else-if and else clauses to the first statement
// and then remove the second one.
// The opposite refactoring (SplitIntoConsecutiveIfStatements) never generates a separate statement
// with an else clause but we support it anyway (in inserts an else-if instead).
Debug.Assert(syntaxFacts.IsExecutableStatement(secondIfOrElseIf));
Debug.Assert(syntaxFacts.IsExecutableStatement(firstIfOrElseIf));
Debug.Assert(ifGenerator.GetElseIfAndElseClauses(firstIfOrElseIf).Length == 0);
editor.ReplaceNode(
firstIfOrElseIf,
(currentNode, _) => ifGenerator.WithElseIfAndElseClausesOf(currentNode, secondIfOrElseIf));
editor.RemoveNode(secondIfOrElseIf);
}
return editor.GetChangedRoot();
}
private static bool CanBeMergedWithParent(
ISyntaxFactsService syntaxFacts,
IIfLikeStatementGenerator ifGenerator,
SyntaxNode ifOrElseIf,
out SyntaxNode parentIfOrElseIf)
{
return ifGenerator.IsElseIfClause(ifOrElseIf, out parentIfOrElseIf) &&
ContainEquivalentStatements(syntaxFacts, ifOrElseIf, parentIfOrElseIf, out _);
}
private static bool CanBeMergedWithElseIf(
ISyntaxFactsService syntaxFacts,
IIfLikeStatementGenerator ifGenerator,
SyntaxNode ifOrElseIf,
out SyntaxNode elseIfClause)
{
return ifGenerator.HasElseIfClause(ifOrElseIf, out elseIfClause) &&
ContainEquivalentStatements(syntaxFacts, ifOrElseIf, elseIfClause, out _);
}
private static Task<bool> CanBeMergedWithPreviousStatementAsync(
Document document,
ISyntaxFactsService syntaxFacts,
IIfLikeStatementGenerator ifGenerator,
SyntaxNode ifOrElseIf,
CancellationToken cancellationToken,
out SyntaxNode previousStatement)
{
return TryGetSiblingStatement(syntaxFacts, ifOrElseIf, relativeIndex: -1, out previousStatement)
? CanStatementsBeMergedAsync(document, syntaxFacts, ifGenerator, previousStatement, ifOrElseIf, cancellationToken)
: SpecializedTasks.False;
}
private static Task<bool> CanBeMergedWithNextStatementAsync(
Document document,
ISyntaxFactsService syntaxFacts,
IIfLikeStatementGenerator ifGenerator,
SyntaxNode ifOrElseIf,
CancellationToken cancellationToken,
out SyntaxNode nextStatement)
{
return TryGetSiblingStatement(syntaxFacts, ifOrElseIf, relativeIndex: 1, out nextStatement)
? CanStatementsBeMergedAsync(document, syntaxFacts, ifGenerator, ifOrElseIf, nextStatement, cancellationToken)
: SpecializedTasks.False;
}
private static async Task<bool> CanStatementsBeMergedAsync(
Document document,
ISyntaxFactsService syntaxFacts,
IIfLikeStatementGenerator ifGenerator,
SyntaxNode firstStatement,
SyntaxNode secondStatement,
CancellationToken cancellationToken)
{
// We don't support cases where the previous if statement has any else-if or else clauses. In order for that
// to be mergable, the control flow would have to quit from inside every branch, which is getting a little complex.
if (!ifGenerator.IsIfOrElseIf(firstStatement) || ifGenerator.GetElseIfAndElseClauses(firstStatement).Length > 0)
return false;
if (!ifGenerator.IsIfOrElseIf(secondStatement))
return false;
if (!ContainEquivalentStatements(syntaxFacts, firstStatement, secondStatement, out var insideStatements))
return false;
if (insideStatements.Count == 0)
{
// Even though there are no statements inside, we still can't merge these into one statement
// because it would change the semantics from always evaluating the second condition to short-circuiting.
return false;
}
else
{
// There are statements inside. We can merge these into one statement if
// control flow can't reach the end of these statements (otherwise, it would change from running
// the second 'if' in the case that both conditions are true to only running the statements once).
// This will typically look like a single return, break, continue or a throw statement.
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var controlFlow = semanticModel.AnalyzeControlFlow(insideStatements[0], insideStatements[insideStatements.Count - 1]);
return !controlFlow.EndPointIsReachable;
}
}
private static bool TryGetSiblingStatement(
ISyntaxFactsService syntaxFacts, SyntaxNode ifOrElseIf, int relativeIndex, out SyntaxNode statement)
{
if (syntaxFacts.IsExecutableStatement(ifOrElseIf) &&
syntaxFacts.IsExecutableBlock(ifOrElseIf.Parent))
{
var blockStatements = syntaxFacts.GetExecutableBlockStatements(ifOrElseIf.Parent);
statement = blockStatements.ElementAtOrDefault(blockStatements.IndexOf(ifOrElseIf) + relativeIndex);
return statement != null;
}
statement = null;
return false;
}
private static bool ContainEquivalentStatements(
ISyntaxFactsService syntaxFacts,
SyntaxNode ifStatement1,
SyntaxNode ifStatement2,
out IReadOnlyList<SyntaxNode> statements)
{
var statements1 = WalkDownScopeBlocks(syntaxFacts, syntaxFacts.GetStatementContainerStatements(ifStatement1));
var statements2 = WalkDownScopeBlocks(syntaxFacts, syntaxFacts.GetStatementContainerStatements(ifStatement2));
statements = statements1;
return statements1.SequenceEqual(statements2, syntaxFacts.AreEquivalent);
}
private sealed class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TryStatement.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
BoundBlock? tryBlock = (BoundBlock?)this.Visit(node.TryBlock);
Debug.Assert(tryBlock is { });
var origSawAwait = _sawAwait;
_sawAwait = false;
var optimizing = _compilation.Options.OptimizationLevel == OptimizationLevel.Release;
ImmutableArray<BoundCatchBlock> catchBlocks =
// When optimizing and we have a try block without side-effects, we can discard the catch blocks.
(optimizing && !HasSideEffects(tryBlock)) ? ImmutableArray<BoundCatchBlock>.Empty
: this.VisitList(node.CatchBlocks);
BoundBlock? finallyBlockOpt = (BoundBlock?)this.Visit(node.FinallyBlockOpt);
_sawAwaitInExceptionHandler |= _sawAwait;
_sawAwait |= origSawAwait;
if (optimizing && !HasSideEffects(finallyBlockOpt))
{
finallyBlockOpt = null;
}
return (catchBlocks.IsDefaultOrEmpty && finallyBlockOpt == null)
? (BoundNode)tryBlock
: (BoundNode)node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.FinallyLabelOpt, node.PreferFaultHandler);
}
/// <summary>
/// Is there any code to execute in the given statement that could have side-effects,
/// such as throwing an exception? This implementation is conservative, in the sense
/// that it may return true when the statement actually may have no side effects.
/// </summary>
private static bool HasSideEffects([NotNullWhen(true)] BoundStatement? statement)
{
if (statement == null) return false;
switch (statement.Kind)
{
case BoundKind.NoOpStatement:
return false;
case BoundKind.Block:
{
var block = (BoundBlock)statement;
foreach (var stmt in block.Statements)
{
if (HasSideEffects(stmt)) return true;
}
return false;
}
case BoundKind.SequencePoint:
{
var sequence = (BoundSequencePoint)statement;
return HasSideEffects(sequence.StatementOpt);
}
case BoundKind.SequencePointWithSpan:
{
var sequence = (BoundSequencePointWithSpan)statement;
return HasSideEffects(sequence.StatementOpt);
}
default:
return true;
}
}
public override BoundNode? VisitCatchBlock(BoundCatchBlock node)
{
if (node.ExceptionFilterOpt == null)
{
return base.VisitCatchBlock(node);
}
if (node.ExceptionFilterOpt.ConstantValue?.BooleanValue == false)
{
return null;
}
BoundExpression? rewrittenExceptionSourceOpt = (BoundExpression?)this.Visit(node.ExceptionSourceOpt);
BoundStatementList? rewrittenFilterPrologue = (BoundStatementList?)this.Visit(node.ExceptionFilterPrologueOpt);
BoundExpression? rewrittenFilter = (BoundExpression?)this.Visit(node.ExceptionFilterOpt);
BoundBlock? rewrittenBody = (BoundBlock?)this.Visit(node.Body);
Debug.Assert(rewrittenBody is { });
TypeSymbol? rewrittenExceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt);
// EnC: We need to insert a hidden sequence point to handle function remapping in case
// the containing method is edited while methods invoked in the condition are being executed.
if (rewrittenFilter != null && !node.WasCompilerGenerated && this.Instrument)
{
rewrittenFilter = _instrumenter.InstrumentCatchClauseFilter(node, rewrittenFilter, _factory);
}
return node.Update(
node.Locals,
rewrittenExceptionSourceOpt,
rewrittenExceptionTypeOpt,
rewrittenFilterPrologue,
rewrittenFilter,
rewrittenBody,
node.IsSynthesizedAsyncCatchAll);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
BoundBlock? tryBlock = (BoundBlock?)this.Visit(node.TryBlock);
Debug.Assert(tryBlock is { });
var origSawAwait = _sawAwait;
_sawAwait = false;
var optimizing = _compilation.Options.OptimizationLevel == OptimizationLevel.Release;
ImmutableArray<BoundCatchBlock> catchBlocks =
// When optimizing and we have a try block without side-effects, we can discard the catch blocks.
(optimizing && !HasSideEffects(tryBlock)) ? ImmutableArray<BoundCatchBlock>.Empty
: this.VisitList(node.CatchBlocks);
BoundBlock? finallyBlockOpt = (BoundBlock?)this.Visit(node.FinallyBlockOpt);
_sawAwaitInExceptionHandler |= _sawAwait;
_sawAwait |= origSawAwait;
if (optimizing && !HasSideEffects(finallyBlockOpt))
{
finallyBlockOpt = null;
}
return (catchBlocks.IsDefaultOrEmpty && finallyBlockOpt == null)
? (BoundNode)tryBlock
: (BoundNode)node.Update(tryBlock, catchBlocks, finallyBlockOpt, node.FinallyLabelOpt, node.PreferFaultHandler);
}
/// <summary>
/// Is there any code to execute in the given statement that could have side-effects,
/// such as throwing an exception? This implementation is conservative, in the sense
/// that it may return true when the statement actually may have no side effects.
/// </summary>
private static bool HasSideEffects([NotNullWhen(true)] BoundStatement? statement)
{
if (statement == null) return false;
switch (statement.Kind)
{
case BoundKind.NoOpStatement:
return false;
case BoundKind.Block:
{
var block = (BoundBlock)statement;
foreach (var stmt in block.Statements)
{
if (HasSideEffects(stmt)) return true;
}
return false;
}
case BoundKind.SequencePoint:
{
var sequence = (BoundSequencePoint)statement;
return HasSideEffects(sequence.StatementOpt);
}
case BoundKind.SequencePointWithSpan:
{
var sequence = (BoundSequencePointWithSpan)statement;
return HasSideEffects(sequence.StatementOpt);
}
default:
return true;
}
}
public override BoundNode? VisitCatchBlock(BoundCatchBlock node)
{
if (node.ExceptionFilterOpt == null)
{
return base.VisitCatchBlock(node);
}
if (node.ExceptionFilterOpt.ConstantValue?.BooleanValue == false)
{
return null;
}
BoundExpression? rewrittenExceptionSourceOpt = (BoundExpression?)this.Visit(node.ExceptionSourceOpt);
BoundStatementList? rewrittenFilterPrologue = (BoundStatementList?)this.Visit(node.ExceptionFilterPrologueOpt);
BoundExpression? rewrittenFilter = (BoundExpression?)this.Visit(node.ExceptionFilterOpt);
BoundBlock? rewrittenBody = (BoundBlock?)this.Visit(node.Body);
Debug.Assert(rewrittenBody is { });
TypeSymbol? rewrittenExceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt);
// EnC: We need to insert a hidden sequence point to handle function remapping in case
// the containing method is edited while methods invoked in the condition are being executed.
if (rewrittenFilter != null && !node.WasCompilerGenerated && this.Instrument)
{
rewrittenFilter = _instrumenter.InstrumentCatchClauseFilter(node, rewrittenFilter, _factory);
}
return node.Update(
node.Locals,
rewrittenExceptionSourceOpt,
rewrittenExceptionTypeOpt,
rewrittenFilterPrologue,
rewrittenFilter,
rewrittenBody,
node.IsSynthesizedAsyncCatchAll);
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/VisualStudio/CSharp/Test/Interactive/TestInteractiveEvaluator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Tasks;
using Microsoft.CodeAnalysis.Editor.Interactive;
using Microsoft.VisualStudio.InteractiveWindow;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive
{
internal sealed class TestInteractiveEvaluator : IInteractiveEvaluator, IResettableInteractiveEvaluator
{
internal event EventHandler<string> OnExecute;
public IInteractiveWindow CurrentWindow { get; set; }
public InteractiveEvaluatorResetOptions ResetOptions { get; set; }
public void Dispose()
{
}
public Task<ExecutionResult> InitializeAsync()
=> Task.FromResult(ExecutionResult.Success);
public Task<ExecutionResult> ResetAsync(bool initialize = true)
=> Task.FromResult(ExecutionResult.Success);
public bool CanExecuteCode(string text)
=> true;
public Task<ExecutionResult> ExecuteCodeAsync(string text)
{
OnExecute?.Invoke(this, text);
return Task.FromResult(ExecutionResult.Success);
}
public string FormatClipboard()
=> null;
public void AbortExecution()
{
}
public string GetConfiguration()
=> "config";
public string GetPrompt()
=> "> ";
public Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory)
=> Task.CompletedTask;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Interactive;
using Microsoft.VisualStudio.InteractiveWindow;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Interactive
{
internal sealed class TestInteractiveEvaluator : IInteractiveEvaluator, IResettableInteractiveEvaluator
{
internal event EventHandler<string> OnExecute;
public IInteractiveWindow CurrentWindow { get; set; }
public InteractiveEvaluatorResetOptions ResetOptions { get; set; }
public void Dispose()
{
}
public Task<ExecutionResult> InitializeAsync()
=> Task.FromResult(ExecutionResult.Success);
public Task<ExecutionResult> ResetAsync(bool initialize = true)
=> Task.FromResult(ExecutionResult.Success);
public bool CanExecuteCode(string text)
=> true;
public Task<ExecutionResult> ExecuteCodeAsync(string text)
{
OnExecute?.Invoke(this, text);
return Task.FromResult(ExecutionResult.Success);
}
public string FormatClipboard()
=> null;
public void AbortExecution()
{
}
public string GetConfiguration()
=> "config";
public string GetPrompt()
=> "> ";
public Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory)
=> Task.CompletedTask;
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/EditorFeatures/VisualBasicTest/Organizing/OrganizeModifiersTests.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.
#If False Then
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Roslyn.Services.Editor.VisualBasic.UnitTests.Organizing
Public Class OrganizeModifiersTests
Inherits AbstractOrganizerTests
<WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)>
Public Sub TestMethods1()
Dim initial =
<element>class C
shared public sub F()
end sub
end class</element>.Value
Dim final =
<element>class C
public shared sub F()
end sub
end class</element>.Value
Check(initial, final)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)>
Public Sub TestMethods2()
Dim initial =
<element>class D
public shared sub S()
end sub
end class</element>.Value
Dim final =
<element>class D
public shared sub S()
end sub
end class</element>.Value
Check(initial, final)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)>
Public Sub TestMethods3()
Dim initial =
<element>class E
public shared partial sub S()
end sub
end class</element>.Value
Dim final =
<element>class E
public shared partial sub S()
end sub
end class</element>.Value
Check(initial, final)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)>
Public Sub TestMethods4()
Dim initial =
<element>class F
shared public partial sub S()
end sub
end class</element>.Value
Dim final =
<element>class F
public shared partial sub S()
end sub
end class</element>.Value
Check(initial, final)
End Sub
End Class
End Namespace
#End If
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
#If False Then
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Roslyn.Services.Editor.VisualBasic.UnitTests.Organizing
Public Class OrganizeModifiersTests
Inherits AbstractOrganizerTests
<WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)>
Public Sub TestMethods1()
Dim initial =
<element>class C
shared public sub F()
end sub
end class</element>.Value
Dim final =
<element>class C
public shared sub F()
end sub
end class</element>.Value
Check(initial, final)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)>
Public Sub TestMethods2()
Dim initial =
<element>class D
public shared sub S()
end sub
end class</element>.Value
Dim final =
<element>class D
public shared sub S()
end sub
end class</element>.Value
Check(initial, final)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)>
Public Sub TestMethods3()
Dim initial =
<element>class E
public shared partial sub S()
end sub
end class</element>.Value
Dim final =
<element>class E
public shared partial sub S()
end sub
end class</element>.Value
Check(initial, final)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)>
Public Sub TestMethods4()
Dim initial =
<element>class F
shared public partial sub S()
end sub
end class</element>.Value
Dim final =
<element>class F
public shared partial sub S()
end sub
end class</element>.Value
Check(initial, final)
End Sub
End Class
End Namespace
#End If
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Workspaces/CSharp/Portable/LinkedFiles/CSharpLinkedFileMergeConflictCommentAdditionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp
{
[ExportLanguageService(typeof(ILinkedFileMergeConflictCommentAdditionService), LanguageNames.CSharp), Shared]
internal sealed class CSharpLinkedFileMergeConflictCommentAdditionService : AbstractLinkedFileMergeConflictCommentAdditionService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpLinkedFileMergeConflictCommentAdditionService()
{
}
internal override string GetConflictCommentText(string header, string beforeString, string afterString)
{
if (beforeString == null && afterString == null)
{
// Whitespace only
return null;
}
else if (beforeString == null)
{
// New code
return string.Format(@"
/* {0}
{1}
{2}
*/
",
header,
WorkspacesResources.Added_colon,
afterString);
}
else if (afterString == null)
{
// Removed code
return string.Format(@"
/* {0}
{1}
{2}
*/
",
header,
WorkspacesResources.Removed_colon,
beforeString);
}
else
{
// Changed code
return string.Format(@"
/* {0}
{1}
{2}
{3}
{4}
*/
",
header,
WorkspacesResources.Before_colon,
beforeString,
WorkspacesResources.After_colon,
afterString);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp
{
[ExportLanguageService(typeof(ILinkedFileMergeConflictCommentAdditionService), LanguageNames.CSharp), Shared]
internal sealed class CSharpLinkedFileMergeConflictCommentAdditionService : AbstractLinkedFileMergeConflictCommentAdditionService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpLinkedFileMergeConflictCommentAdditionService()
{
}
internal override string GetConflictCommentText(string header, string beforeString, string afterString)
{
if (beforeString == null && afterString == null)
{
// Whitespace only
return null;
}
else if (beforeString == null)
{
// New code
return string.Format(@"
/* {0}
{1}
{2}
*/
",
header,
WorkspacesResources.Added_colon,
afterString);
}
else if (afterString == null)
{
// Removed code
return string.Format(@"
/* {0}
{1}
{2}
*/
",
header,
WorkspacesResources.Removed_colon,
beforeString);
}
else
{
// Changed code
return string.Format(@"
/* {0}
{1}
{2}
{3}
{4}
*/
",
header,
WorkspacesResources.Before_colon,
beforeString,
WorkspacesResources.After_colon,
afterString);
}
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/EditorFeatures/CSharpTest2/Recommendations/WithKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class WithKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterWith()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = goo with $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExpr()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = goo $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDottedName()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = goo.Current $$"));
}
[WorkItem(543041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543041")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterVarInForLoop()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"for (var $$"));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeFirstStringHole()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = ""\{0}$$\{1}\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBetweenStringHoles()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = ""\{0}\{1}$$\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStringHoles()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}$$"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLastStringHole()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}"" $$"));
}
[WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotWithinNumericLiteral()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = .$$0;"));
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsync()
{
await VerifyAbsenceAsync(
@"
using System;
class C
{
void Goo()
{
Bar(async $$
}
void Bar(Func<int, string> f)
{
}
}");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterMethodReference()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
var v = Console.WriteLine $$");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAnonymousMethod()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
Action a = delegate { } $$");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterLambda1()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
Action b = (() => 0) $$");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterLambda2()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
Action b = () => {} $$");
}
[WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMissingAfterNumericLiteral()
{
await VerifyAbsenceAsync(
@"
class C
{
void M()
{
var x = 1$$
}
}");
}
[WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMissingAfterNumericLiteralAndDot()
{
await VerifyAbsenceAsync(
@"
class C
{
void M()
{
var x = 1.$$
}
}");
}
[WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMissingAfterNumericLiteralDotAndSpace()
{
await VerifyAbsenceAsync(
@"
class C
{
void M()
{
var x = 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class WithKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterWith()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = goo with $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExpr()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = goo $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDottedName()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = goo.Current $$"));
}
[WorkItem(543041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543041")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterVarInForLoop()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"for (var $$"));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeFirstStringHole()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = ""\{0}$$\{1}\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBetweenStringHoles()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = ""\{0}\{1}$$\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStringHoles()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}$$"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLastStringHole()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}"" $$"));
}
[WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotWithinNumericLiteral()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = .$$0;"));
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsync()
{
await VerifyAbsenceAsync(
@"
using System;
class C
{
void Goo()
{
Bar(async $$
}
void Bar(Func<int, string> f)
{
}
}");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterMethodReference()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
var v = Console.WriteLine $$");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAnonymousMethod()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
Action a = delegate { } $$");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterLambda1()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
Action b = (() => 0) $$");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterLambda2()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
Action b = () => {} $$");
}
[WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMissingAfterNumericLiteral()
{
await VerifyAbsenceAsync(
@"
class C
{
void M()
{
var x = 1$$
}
}");
}
[WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMissingAfterNumericLiteralAndDot()
{
await VerifyAbsenceAsync(
@"
class C
{
void M()
{
var x = 1.$$
}
}");
}
[WorkItem(48573, "https://github.com/dotnet/roslyn/issues/48573")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestMissingAfterNumericLiteralDotAndSpace()
{
await VerifyAbsenceAsync(
@"
class C
{
void M()
{
var x = 1. $$
}
}");
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Workspaces/CSharp/Portable/Indentation/CSharpIndentationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Indentation
{
[ExportLanguageService(typeof(IIndentationService), LanguageNames.CSharp), Shared]
internal sealed partial class CSharpIndentationService : AbstractIndentationService<CompilationUnitSyntax>
{
public static readonly CSharpIndentationService Instance = new();
private static readonly AbstractFormattingRule s_instance = new FormattingRule();
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")]
public CSharpIndentationService()
{
}
protected override AbstractFormattingRule GetSpecializedIndentationFormattingRule(FormattingOptions.IndentStyle indentStyle)
=> s_instance;
public static bool ShouldUseSmartTokenFormatterInsteadOfIndenter(
IEnumerable<AbstractFormattingRule> formattingRules,
CompilationUnitSyntax root,
TextLine line,
IOptionService optionService,
OptionSet optionSet,
out SyntaxToken token)
{
Contract.ThrowIfNull(formattingRules);
Contract.ThrowIfNull(root);
token = default;
if (!optionSet.GetOption(FormattingOptions.AutoFormattingOnReturn, LanguageNames.CSharp))
{
return false;
}
if (optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) != FormattingOptions.IndentStyle.Smart)
{
return false;
}
var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition();
if (!firstNonWhitespacePosition.HasValue)
{
return false;
}
token = root.FindToken(firstNonWhitespacePosition.Value);
if (IsInvalidToken(token))
{
return false;
}
if (token.IsKind(SyntaxKind.None) ||
token.SpanStart != firstNonWhitespacePosition)
{
return false;
}
// first see whether there is a line operation for current token
var previousToken = token.GetPreviousToken(includeZeroWidth: true);
// only use smart token formatter when we have two visible tokens.
if (previousToken.Kind() == SyntaxKind.None || previousToken.IsMissing)
{
return false;
}
var lineOperation = FormattingOperations.GetAdjustNewLinesOperation(formattingRules, previousToken, token, optionSet.AsAnalyzerConfigOptions(optionService, LanguageNames.CSharp));
if (lineOperation == null || lineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine)
{
// no indentation operation, nothing to do for smart token formatter
return false;
}
// We're pressing enter between two tokens, have the formatter figure out hte appropriate
// indentation.
return true;
}
private static bool IsInvalidToken(SyntaxToken token)
{
// invalid token to be formatted
return token.IsKind(SyntaxKind.None) ||
token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
token.IsKind(SyntaxKind.EndOfFileToken);
}
private class FormattingRule : AbstractFormattingRule
{
public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation)
{
// these nodes should be from syntax tree from ITextSnapshot.
Debug.Assert(node.SyntaxTree != null);
Debug.Assert(node.SyntaxTree.GetText() != null);
nextOperation.Invoke();
ReplaceCaseIndentationRules(list, node);
if (node is BaseParameterListSyntax ||
node is TypeArgumentListSyntax ||
node is TypeParameterListSyntax ||
node.IsKind(SyntaxKind.Interpolation))
{
AddIndentBlockOperations(list, node);
return;
}
if (node is BaseArgumentListSyntax argument &&
!argument.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) &&
!IsBracketedArgumentListMissingBrackets(argument as BracketedArgumentListSyntax))
{
AddIndentBlockOperations(list, argument);
return;
}
// only valid if the user has started to actually type a constructor initializer
if (node is ConstructorInitializerSyntax constructorInitializer &&
constructorInitializer.ArgumentList.OpenParenToken.Kind() != SyntaxKind.None &&
!constructorInitializer.ThisOrBaseKeyword.IsMissing)
{
var text = node.SyntaxTree.GetText();
// 3 different cases
// first case : this or base is the first token on line
// second case : colon is the first token on line
var colonIsFirstTokenOnLine = !constructorInitializer.ColonToken.IsMissing && constructorInitializer.ColonToken.IsFirstTokenOnLine(text);
var thisOrBaseIsFirstTokenOnLine = !constructorInitializer.ThisOrBaseKeyword.IsMissing && constructorInitializer.ThisOrBaseKeyword.IsFirstTokenOnLine(text);
if (colonIsFirstTokenOnLine || thisOrBaseIsFirstTokenOnLine)
{
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
constructorInitializer.ThisOrBaseKeyword,
constructorInitializer.ArgumentList.OpenParenToken.GetNextToken(includeZeroWidth: true),
constructorInitializer.ArgumentList.CloseParenToken.GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativePosition));
}
else
{
// third case : none of them are the first token on the line
AddIndentBlockOperations(list, constructorInitializer.ArgumentList);
}
}
}
private static bool IsBracketedArgumentListMissingBrackets(BracketedArgumentListSyntax? node)
=> node != null && node.OpenBracketToken.IsMissing && node.CloseBracketToken.IsMissing;
private static void ReplaceCaseIndentationRules(List<IndentBlockOperation> list, SyntaxNode node)
{
if (!(node is SwitchSectionSyntax section) || section.Statements.Count == 0)
{
return;
}
var startToken = section.Statements.First().GetFirstToken(includeZeroWidth: true);
var endToken = section.Statements.Last().GetLastToken(includeZeroWidth: true);
for (var i = 0; i < list.Count; i++)
{
var operation = list[i];
if (operation.StartToken == startToken && operation.EndToken == endToken)
{
// replace operation
list[i] = FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: 1, option: IndentBlockOption.RelativePosition);
}
}
}
private static void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node)
{
RoslynDebug.AssertNotNull(node.Parent);
// only add indent block operation if the base token is the first token on line
var baseToken = node.Parent.GetFirstToken(includeZeroWidth: true);
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
baseToken,
node.GetFirstToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true),
node.GetLastToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Indentation
{
[ExportLanguageService(typeof(IIndentationService), LanguageNames.CSharp), Shared]
internal sealed partial class CSharpIndentationService : AbstractIndentationService<CompilationUnitSyntax>
{
public static readonly CSharpIndentationService Instance = new();
private static readonly AbstractFormattingRule s_instance = new FormattingRule();
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")]
public CSharpIndentationService()
{
}
protected override AbstractFormattingRule GetSpecializedIndentationFormattingRule(FormattingOptions.IndentStyle indentStyle)
=> s_instance;
public static bool ShouldUseSmartTokenFormatterInsteadOfIndenter(
IEnumerable<AbstractFormattingRule> formattingRules,
CompilationUnitSyntax root,
TextLine line,
IOptionService optionService,
OptionSet optionSet,
out SyntaxToken token)
{
Contract.ThrowIfNull(formattingRules);
Contract.ThrowIfNull(root);
token = default;
if (!optionSet.GetOption(FormattingOptions.AutoFormattingOnReturn, LanguageNames.CSharp))
{
return false;
}
if (optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) != FormattingOptions.IndentStyle.Smart)
{
return false;
}
var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition();
if (!firstNonWhitespacePosition.HasValue)
{
return false;
}
token = root.FindToken(firstNonWhitespacePosition.Value);
if (IsInvalidToken(token))
{
return false;
}
if (token.IsKind(SyntaxKind.None) ||
token.SpanStart != firstNonWhitespacePosition)
{
return false;
}
// first see whether there is a line operation for current token
var previousToken = token.GetPreviousToken(includeZeroWidth: true);
// only use smart token formatter when we have two visible tokens.
if (previousToken.Kind() == SyntaxKind.None || previousToken.IsMissing)
{
return false;
}
var lineOperation = FormattingOperations.GetAdjustNewLinesOperation(formattingRules, previousToken, token, optionSet.AsAnalyzerConfigOptions(optionService, LanguageNames.CSharp));
if (lineOperation == null || lineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine)
{
// no indentation operation, nothing to do for smart token formatter
return false;
}
// We're pressing enter between two tokens, have the formatter figure out hte appropriate
// indentation.
return true;
}
private static bool IsInvalidToken(SyntaxToken token)
{
// invalid token to be formatted
return token.IsKind(SyntaxKind.None) ||
token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
token.IsKind(SyntaxKind.EndOfFileToken);
}
private class FormattingRule : AbstractFormattingRule
{
public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation)
{
// these nodes should be from syntax tree from ITextSnapshot.
Debug.Assert(node.SyntaxTree != null);
Debug.Assert(node.SyntaxTree.GetText() != null);
nextOperation.Invoke();
ReplaceCaseIndentationRules(list, node);
if (node is BaseParameterListSyntax ||
node is TypeArgumentListSyntax ||
node is TypeParameterListSyntax ||
node.IsKind(SyntaxKind.Interpolation))
{
AddIndentBlockOperations(list, node);
return;
}
if (node is BaseArgumentListSyntax argument &&
!argument.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) &&
!IsBracketedArgumentListMissingBrackets(argument as BracketedArgumentListSyntax))
{
AddIndentBlockOperations(list, argument);
return;
}
// only valid if the user has started to actually type a constructor initializer
if (node is ConstructorInitializerSyntax constructorInitializer &&
constructorInitializer.ArgumentList.OpenParenToken.Kind() != SyntaxKind.None &&
!constructorInitializer.ThisOrBaseKeyword.IsMissing)
{
var text = node.SyntaxTree.GetText();
// 3 different cases
// first case : this or base is the first token on line
// second case : colon is the first token on line
var colonIsFirstTokenOnLine = !constructorInitializer.ColonToken.IsMissing && constructorInitializer.ColonToken.IsFirstTokenOnLine(text);
var thisOrBaseIsFirstTokenOnLine = !constructorInitializer.ThisOrBaseKeyword.IsMissing && constructorInitializer.ThisOrBaseKeyword.IsFirstTokenOnLine(text);
if (colonIsFirstTokenOnLine || thisOrBaseIsFirstTokenOnLine)
{
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
constructorInitializer.ThisOrBaseKeyword,
constructorInitializer.ArgumentList.OpenParenToken.GetNextToken(includeZeroWidth: true),
constructorInitializer.ArgumentList.CloseParenToken.GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativePosition));
}
else
{
// third case : none of them are the first token on the line
AddIndentBlockOperations(list, constructorInitializer.ArgumentList);
}
}
}
private static bool IsBracketedArgumentListMissingBrackets(BracketedArgumentListSyntax? node)
=> node != null && node.OpenBracketToken.IsMissing && node.CloseBracketToken.IsMissing;
private static void ReplaceCaseIndentationRules(List<IndentBlockOperation> list, SyntaxNode node)
{
if (!(node is SwitchSectionSyntax section) || section.Statements.Count == 0)
{
return;
}
var startToken = section.Statements.First().GetFirstToken(includeZeroWidth: true);
var endToken = section.Statements.Last().GetLastToken(includeZeroWidth: true);
for (var i = 0; i < list.Count; i++)
{
var operation = list[i];
if (operation.StartToken == startToken && operation.EndToken == endToken)
{
// replace operation
list[i] = FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: 1, option: IndentBlockOption.RelativePosition);
}
}
}
private static void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node)
{
RoslynDebug.AssertNotNull(node.Parent);
// only add indent block operation if the base token is the first token on line
var baseToken = node.Parent.GetFirstToken(includeZeroWidth: true);
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
baseToken,
node.GetFirstToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true),
node.GetLastToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine));
}
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/VisualStudio/CSharp/Impl/Options/Formatting/StyleViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Windows.Data;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting
{
/// <summary>
/// This is the view model for CodeStyle options page.
/// </summary>
/// <remarks>
/// The codestyle options page is defined in <see cref="CodeStylePage"/>
/// </remarks>
internal class StyleViewModel : AbstractOptionPreviewViewModel
{
#region "Preview Text"
private const string s_fieldDeclarationPreviewTrue = @"
class C{
int capacity;
void Method()
{
//[
this.capacity = 0;
//]
}
}";
private const string s_fieldDeclarationPreviewFalse = @"
class C{
int capacity;
void Method()
{
//[
capacity = 0;
//]
}
}";
private const string s_propertyDeclarationPreviewTrue = @"
class C{
public int Id { get; set; }
void Method()
{
//[
this.Id = 0;
//]
}
}";
private const string s_propertyDeclarationPreviewFalse = @"
class C{
public int Id { get; set; }
void Method()
{
//[
Id = 0;
//]
}
}";
private const string s_eventDeclarationPreviewTrue = @"
using System;
class C{
event EventHandler Elapsed;
void Handler(object sender, EventArgs args)
{
//[
this.Elapsed += Handler;
//]
}
}";
private const string s_eventDeclarationPreviewFalse = @"
using System;
class C{
event EventHandler Elapsed;
void Handler(object sender, EventArgs args)
{
//[
Elapsed += Handler;
//]
}
}";
private const string s_methodDeclarationPreviewTrue = @"
using System;
class C{
void Display()
{
//[
this.Display();
//]
}
}";
private const string s_methodDeclarationPreviewFalse = @"
using System;
class C{
void Display()
{
//[
Display();
//]
}
}";
private const string s_intrinsicPreviewDeclarationTrue = @"
class Program
{
//[
private int _member;
static void M(int argument)
{
int local;
}
//]
}";
private const string s_intrinsicPreviewDeclarationFalse = @"
using System;
class Program
{
//[
private Int32 _member;
static void M(Int32 argument)
{
Int32 local;
}
//]
}";
private const string s_intrinsicPreviewMemberAccessTrue = @"
class Program
{
//[
static void M()
{
var local = int.MaxValue;
}
//]
}";
private const string s_intrinsicPreviewMemberAccessFalse = @"
using System;
class Program
{
//[
static void M()
{
var local = Int32.MaxValue;
}
//]
}";
private static readonly string s_varForIntrinsicsPreviewFalse = $@"
using System;
class C{{
void Method()
{{
//[
int x = 5; // {ServicesVSResources.built_in_types}
//]
}}
}}";
private static readonly string s_varForIntrinsicsPreviewTrue = $@"
using System;
class C{{
void Method()
{{
//[
var x = 5; // {ServicesVSResources.built_in_types}
//]
}}
}}";
private static readonly string s_varWhereApparentPreviewFalse = $@"
using System;
class C{{
void Method()
{{
//[
C cobj = new C(); // {ServicesVSResources.type_is_apparent_from_assignment_expression}
//]
}}
}}";
private static readonly string s_varWhereApparentPreviewTrue = $@"
using System;
class C{{
void Method()
{{
//[
var cobj = new C(); // {ServicesVSResources.type_is_apparent_from_assignment_expression}
//]
}}
}}";
private static readonly string s_varWherePossiblePreviewFalse = $@"
using System;
class C{{
void Init()
{{
//[
Action f = this.Init(); // {ServicesVSResources.everywhere_else}
//]
}}
}}";
private static readonly string s_varWherePossiblePreviewTrue = $@"
using System;
class C{{
void Init()
{{
//[
var f = this.Init(); // {ServicesVSResources.everywhere_else}
//]
}}
}}";
private static readonly string s_preferThrowExpression = $@"
using System;
class C
{{
private string s;
void M1(string s)
{{
//[
// {ServicesVSResources.Prefer_colon}
this.s = s ?? throw new ArgumentNullException(nameof(s));
//]
}}
void M2(string s)
{{
//[
// {ServicesVSResources.Over_colon}
if (s == null)
{{
throw new ArgumentNullException(nameof(s));
}}
this.s = s;
//]
}}
}}
";
private static readonly string s_preferCoalesceExpression = $@"
using System;
class C
{{
private string s;
void M1(string s)
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = x ?? y;
//]
}}
void M2(string s)
{{
//[
// {ServicesVSResources.Over_colon}
var v = x != null ? x : y; // {ServicesVSResources.or}
var v = x == null ? y : x;
//]
}}
}}
";
private static readonly string s_preferConditionalDelegateCall = $@"
using System;
class C
{{
private string s;
void M1(string s)
{{
//[
// {ServicesVSResources.Prefer_colon}
func?.Invoke(args);
//]
}}
void M2(string s)
{{
//[
// {ServicesVSResources.Over_colon}
if (func != null)
{{
func(args);
}}
//]
}}
}}
";
private static readonly string s_preferNullPropagation = $@"
using System;
class C
{{
void M1(object o)
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = o?.ToString();
//]
}}
void M2(object o)
{{
//[
// {ServicesVSResources.Over_colon}
var v = o == null ? null : o.ToString(); // {ServicesVSResources.or}
var v = o != null ? o.ToString() : null;
//]
}}
}}
";
private static readonly string s_preferSwitchExpression = $@"
class C
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
return num switch
{{
1 => 1,
_ => 2,
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
switch (num)
{{
case 1:
return 1;
default:
return 2;
}}
//]
}}
}}
";
private static readonly string s_preferPatternMatching = $@"
class C
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
return num is 1 or 2;
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
return num == 1 || num == 2;
//]
}}
}}
";
private static readonly string s_preferPatternMatchingOverAsWithNullCheck = $@"
class C
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
if (o is string s)
{{
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
var s = o as string;
if (s != null)
{{
}}
//]
}}
}}
";
private static readonly string s_preferPatternMatchingOverMixedTypeCheck = $@"
class C
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
if (o is not string s)
{{
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
if (!(o is string s))
{{
}}
//]
}}
}}
";
private static readonly string s_preferConditionalExpressionOverIfWithAssignments = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
string s = expr ? ""hello"" : ""world"";
// {ServicesVSResources.Over_colon}
string s;
if (expr)
{{
s = ""hello"";
}}
else
{{
s = ""world"";
}}
//]
}}
}}
";
private static readonly string s_preferConditionalExpressionOverIfWithReturns = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
return expr ? ""hello"" : ""world"";
// {ServicesVSResources.Over_colon}
if (expr)
{{
return ""hello"";
}}
else
{{
return ""world"";
}}
//]
}}
}}
";
private static readonly string s_preferPatternMatchingOverIsWithCastCheck = $@"
class C
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
if (o is int i)
{{
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
if (o is int)
{{
var i = (int)o;
}}
//]
}}
}}
";
private static readonly string s_preferObjectInitializer = $@"
using System;
class Customer
{{
private int Age;
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
var c = new Customer()
{{
Age = 21
}};
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
var c = new Customer();
c.Age = 21;
//]
}}
}}
";
private static readonly string s_preferCollectionInitializer = $@"
using System.Collections.Generic;
class Customer
{{
private int Age;
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
var list = new List<int>
{{
1,
2,
3
}};
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
//]
}}
}}
";
private static readonly string s_preferExplicitTupleName = $@"
class Customer
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
(string name, int age) customer = GetCustomer();
var name = customer.name;
var age = customer.age;
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
(string name, int age) customer = GetCustomer();
var name = customer.Item1;
var age = customer.Item2;
//]
}}
}}
";
private static readonly string s_preferSimpleDefaultExpression = $@"
using System.Threading;
class Customer1
{{
//[
// {ServicesVSResources.Prefer_colon}
void DoWork(CancellationToken cancellationToken = default) {{ }}
//]
}}
class Customer2
{{
//[
// {ServicesVSResources.Over_colon}
void DoWork(CancellationToken cancellationToken = default(CancellationToken)) {{ }}
//]
}}
";
private static readonly string s_preferSimplifiedConditionalExpression = $@"
using System.Threading;
class Customer1
{{
bool A() => true;
bool B() => true;
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
var x = A() && B();
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
var x = A() && B() ? true : false
//]
}}
}}
";
private static readonly string s_preferInferredTupleName = $@"
using System.Threading;
class Customer
{{
void M1(int age, string name)
{{
//[
// {ServicesVSResources.Prefer_colon}
var tuple = (age, name);
//]
}}
void M2(int age, string name)
{{
//[
// {ServicesVSResources.Over_colon}
var tuple = (age: age, name: name);
//]
}}
}}
";
private static readonly string s_preferInferredAnonymousTypeMemberName = $@"
using System.Threading;
class Customer
{{
void M1(int age, string name)
{{
//[
// {ServicesVSResources.Prefer_colon}
var anon = new {{ age, name }};
//]
}}
void M2(int age, string name)
{{
//[
// {ServicesVSResources.Over_colon}
var anon = new {{ age = age, name = name }};
//]
}}
}}
";
private static readonly string s_preferInlinedVariableDeclaration = $@"
using System;
class Customer
{{
void M1(string value)
{{
//[
// {ServicesVSResources.Prefer_colon}
if (int.TryParse(value, out int i))
{{
}}
//]
}}
void M2(string value)
{{
//[
// {ServicesVSResources.Over_colon}
int i;
if (int.TryParse(value, out i))
{{
}}
//]
}}
}}
";
private static readonly string s_preferDeconstructedVariableDeclaration = $@"
using System;
class Customer
{{
void M1(string value)
{{
//[
// {ServicesVSResources.Prefer_colon}
var (name, age) = GetPersonTuple();
Console.WriteLine($""{{name}} {{age}}"");
(int x, int y) = GetPointTuple();
Console.WriteLine($""{{x}} {{y}}"");
//]
}}
void M2(string value)
{{
//[
// {ServicesVSResources.Over_colon}
var person = GetPersonTuple();
Console.WriteLine($""{{person.name}} {{person.age}}"");
(int x, int y) point = GetPointTuple();
Console.WriteLine($""{{point.x}} {{point.y}}"");
//]
}}
}}
";
private static readonly string s_doNotPreferBraces = $@"
using System;
class Customer
{{
private int Age;
void M1()
{{
//[
// {ServicesVSResources.Allow_colon}
if (test) Console.WriteLine(""Text"");
// {ServicesVSResources.Allow_colon}
if (test)
Console.WriteLine(""Text"");
// {ServicesVSResources.Allow_colon}
if (test)
Console.WriteLine(
""Text"");
// {ServicesVSResources.Allow_colon}
if (test)
{{
Console.WriteLine(
""Text"");
}}
//]
}}
}}
";
private static readonly string s_preferBracesWhenMultiline = $@"
using System;
class Customer
{{
private int Age;
void M1()
{{
//[
// {ServicesVSResources.Allow_colon}
if (test) Console.WriteLine(""Text"");
// {ServicesVSResources.Allow_colon}
if (test)
Console.WriteLine(""Text"");
// {ServicesVSResources.Prefer_colon}
if (test)
{{
Console.WriteLine(
""Text"");
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
if (test)
Console.WriteLine(
""Text"");
//]
}}
}}
";
private static readonly string s_preferBraces = $@"
using System;
class Customer
{{
private int Age;
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
if (test)
{{
Console.WriteLine(""Text"");
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
if (test)
Console.WriteLine(""Text"");
//]
}}
}}
";
private static readonly string s_preferAutoProperties = $@"
using System;
class Customer1
{{
//[
// {ServicesVSResources.Prefer_colon}
public int Age {{ get; }}
//]
}}
class Customer2
{{
//[
// {ServicesVSResources.Over_colon}
private int age;
public int Age
{{
get
{{
return age;
}}
}}
//]
}}
";
private static readonly string s_preferFileScopedNamespace = $@"
//[
// {ServicesVSResources.Prefer_colon}
namespace A.B.C;
public class Program
{{
}}
//]
//[
// {ServicesVSResources.Over_colon}
namespace A.B.C
{{
public class Program
{{
}}
}}
//]
";
private static readonly string s_preferBlockNamespace = $@"
//[
// {ServicesVSResources.Prefer_colon}
namespace A.B.C
{{
public class Program
{{
}}
}}
//]
//[
// {ServicesVSResources.Over_colon}
namespace A.B.C;
public class Program
{{
}}
//]
";
private static readonly string s_preferSimpleUsingStatement = $@"
using System;
class Customer1
{{
//[
// {ServicesVSResources.Prefer_colon}
void Method()
{{
using var resource = GetResource();
ProcessResource(resource);
}}
//]
}}
class Customer2
{{
//[
// {ServicesVSResources.Over_colon}
void Method()
{{
using (var resource = GetResource())
{{
ProcessResource(resource);
}}
}}
//]
}}
";
private static readonly string s_preferSystemHashCode = $@"
using System;
class Customer1
{{
int a, b, c;
//[
// {ServicesVSResources.Prefer_colon}
// {ServicesVSResources.Requires_System_HashCode_be_present_in_project}
public override int GetHashCode()
{{
return System.HashCode.Combine(a, b, c);
}}
//]
}}
class Customer2
{{
int a, b, c;
//[
// {ServicesVSResources.Over_colon}
public override int GetHashCode()
{{
var hashCode = 339610899;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
hashCode = hashCode * -1521134295 + c.GetHashCode();
return hashCode;
}}
//]
}}
";
private static readonly string s_preferLocalFunctionOverAnonymousFunction = $@"
using System;
class Customer
{{
void M1(string value)
{{
//[
// {ServicesVSResources.Prefer_colon}
int fibonacci(int n)
{{
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}}
//]
}}
void M2(string value)
{{
//[
// {ServicesVSResources.Over_colon}
Func<int, int> fibonacci = null;
fibonacci = (int n) =>
{{
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}};
//]
}}
}}
";
private static readonly string s_preferCompoundAssignments = $@"
using System;
class Customer
{{
void M1(int value)
{{
//[
// {ServicesVSResources.Prefer_colon}
value += 10;
//]
}}
void M2(int value)
{{
//[
// {ServicesVSResources.Over_colon}
value = value + 10
//]
}}
}}
";
private static readonly string s_preferImplicitObjectCreationWhenTypeIsApparent = $@"
using System.Collections.Generic;
class Order {{}}
//[
class Customer
{{
// {ServicesVSResources.Prefer_colon}
private readonly List<Order> orders = new();
// {ServicesVSResources.Over_colon}
private readonly List<Order> orders = new List<Order>();
}}
//]
";
private static readonly string s_preferIndexOperator = $@"
using System;
class Customer
{{
void M1(string value)
{{
//[
// {ServicesVSResources.Prefer_colon}
var ch = value[^1];
//]
}}
void M2(string value)
{{
//[
// {ServicesVSResources.Over_colon}
var ch = value[value.Length - 1];
//]
}}
}}
";
private static readonly string s_preferRangeOperator = $@"
using System;
class Customer
{{
void M1(string value)
{{
//[
// {ServicesVSResources.Prefer_colon}
var sub = value[1..^1];
//]
}}
void M2(string value)
{{
//[
// {ServicesVSResources.Over_colon}
var sub = value.Substring(1, value.Length - 2);
//]
}}
}}
";
private static readonly string s_preferIsNullOverReferenceEquals = $@"
using System;
class Customer
{{
void M1(string value1, string value2)
{{
//[
// {ServicesVSResources.Prefer_colon}
if (value1 is null)
return;
if (value2 is null)
return;
//]
}}
void M2(string value1, string value2)
{{
//[
// {ServicesVSResources.Over_colon}
if (object.ReferenceEquals(value1, null))
return;
if ((object)value2 == null)
return;
//]
}}
}}
";
private static readonly string s_preferNullcheckOverTypeCheck = $@"
using System;
class Customer
{{
void M1(string value1, string value2)
{{
//[
// {ServicesVSResources.Prefer_colon}
if (value1 is null)
return;
if (value2 is not null)
return;
//]
}}
void M2(string value1, string value2)
{{
//[
// {ServicesVSResources.Over_colon}
if (value1 is not object)
return;
if (value2 is object)
return;
//]
}}
}}
";
#region expression and block bodies
private const string s_preferExpressionBodyForMethods = @"
using System;
//[
class Customer
{
private int Age;
public int GetAge() => this.Age;
}
//]
";
private const string s_preferBlockBodyForMethods = @"
using System;
//[
class Customer
{
private int Age;
public int GetAge()
{
return this.Age;
}
}
//]
";
private const string s_preferExpressionBodyForConstructors = @"
using System;
//[
class Customer
{
private int Age;
public Customer(int age) => Age = age;
}
//]
";
private const string s_preferBlockBodyForConstructors = @"
using System;
//[
class Customer
{
private int Age;
public Customer(int age)
{
Age = age;
}
}
//]
";
private const string s_preferExpressionBodyForOperators = @"
using System;
struct ComplexNumber
{
//[
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
=> new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
//]
}
";
private const string s_preferBlockBodyForOperators = @"
using System;
struct ComplexNumber
{
//[
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
{
return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
//]
}
";
private const string s_preferExpressionBodyForProperties = @"
using System;
//[
class Customer
{
private int _age;
public int Age => _age;
}
//]
";
private const string s_preferBlockBodyForProperties = @"
using System;
//[
class Customer
{
private int _age;
public int Age { get { return _age; } }
}
//]
";
private const string s_preferExpressionBodyForAccessors = @"
using System;
//[
class Customer
{
private int _age;
public int Age
{
get => _age;
set => _age = value;
}
}
//]
";
private const string s_preferBlockBodyForAccessors = @"
using System;
//[
class Customer
{
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
}
//]
";
private const string s_preferExpressionBodyForIndexers = @"
using System;
//[
class List<T>
{
private T[] _values;
public T this[int i] => _values[i];
}
//]
";
private const string s_preferBlockBodyForIndexers = @"
using System;
//[
class List<T>
{
private T[] _values;
public T this[int i] { get { return _values[i]; } }
}
//]
";
private const string s_preferExpressionBodyForLambdas = @"
using System;
class Customer
{
void Method()
{
//[
Func<int, string> f = a => a.ToString();
//]
}
}
";
private const string s_preferBlockBodyForLambdas = @"
using System;
class Customer
{
void Method()
{
//[
Func<int, string> f = a =>
{
return a.ToString();
};
//]
}
}
";
private const string s_preferExpressionBodyForLocalFunctions = @"
using System;
//[
class Customer
{
private int Age;
public int GetAge()
{
return GetAgeLocal();
int GetAgeLocal() => this.Age;
}
}
//]
";
private const string s_preferBlockBodyForLocalFunctions = @"
using System;
//[
class Customer
{
private int Age;
public int GetAge()
{
return GetAgeLocal();
int GetAgeLocal()
{
return this.Age;
}
}
}
//]
";
private static readonly string s_preferReadonly = $@"
class Customer1
{{
//[
// {ServicesVSResources.Prefer_colon}
// '_value' can only be assigned in constructor
private readonly int _value = 0;
//]
}}
class Customer2
{{
//[
// {ServicesVSResources.Over_colon}
// '_value' can be assigned anywhere
private int _value = 0;
//]
}}
";
private static readonly string[] s_usingDirectivePlacement = new[] { $@"
//[
namespace Namespace
{{
// {CSharpVSResources.Inside_namespace}
using System;
using System.Linq;
class Customer
{{
}}
}}
//]", $@"
//[
// {CSharpVSResources.Outside_namespace}
using System;
using System.Linq;
namespace Namespace
{{
class Customer
{{
}}
}}
//]
" };
private static readonly string s_preferStaticLocalFunction = $@"
class Customer1
{{
//[
void Method()
{{
// {ServicesVSResources.Prefer_colon}
static int fibonacci(int n)
{{
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}}
}}
//]
}}
class Customer2
{{
//[
void Method()
{{
// {ServicesVSResources.Over_colon}
int fibonacci(int n)
{{
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}}
}}
//]
}}
";
private static readonly string s_allow_embedded_statements_on_same_line_true = $@"
class Class2
{{
void Method(int a, int b)
{{
//[
// {ServicesVSResources.Allow_colon}
if (a > b) return true;
//]
return false;
}}
}}
";
private static readonly string s_allow_embedded_statements_on_same_line_false = $@"
class Class1
{{
void Method(int a, int b)
{{
//[
// {ServicesVSResources.Require_colon}
if (a > b)
return true;
//]
return false;
}}
}}
class Class2
{{
void Method(int a, int b)
{{
//[
// {ServicesVSResources.Over_colon}
if (a > b) return true;
//]
return false;
}}
}}
";
private static readonly string s_allow_blank_line_between_consecutive_braces_true = $@"
class Class2
{{
//[
// {ServicesVSResources.Allow_colon}
void Method()
{{
if (true)
{{
DoWork();
}}
}}
//]
}}
";
private static readonly string s_allow_blank_line_between_consecutive_braces_false = $@"
class Class1
{{
//[
// {ServicesVSResources.Require_colon}
void Method()
{{
if (true)
{{
DoWork();
}}
}}
//]
}}
class Class2
{{
//[
// {ServicesVSResources.Over_colon}
void Method()
{{
if (true)
{{
DoWork();
}}
}}
//]
}}
";
private static readonly string s_allow_multiple_blank_lines_true = $@"
class Class2
{{
void Method()
{{
//[
// {ServicesVSResources.Allow_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
";
private static readonly string s_allow_multiple_blank_lines_false = $@"
class Class1
{{
void Method()
{{
//[
// {ServicesVSResources.Require_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
class Class2
{{
void Method()
{{
//[
// {ServicesVSResources.Over_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
";
private static readonly string s_allow_statement_immediately_after_block_true = $@"
class Class2
{{
void Method()
{{
//[
// {ServicesVSResources.Allow_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
";
private static readonly string s_allow_statement_immediately_after_block_false = $@"
class Class1
{{
void Method()
{{
//[
// {ServicesVSResources.Require_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
class Class2
{{
void Method()
{{
//[
// {ServicesVSResources.Over_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
";
private static readonly string s_allow_bank_line_after_colon_in_constructor_initializer_true = $@"
class Class
{{
//[
// {ServicesVSResources.Allow_colon}
public Class() :
base()
{{
}}
//]
}}
";
private static readonly string s_allow_bank_line_after_colon_in_constructor_initializer_false = $@"
namespace NS1
{{
class Class
{{
//[
// {ServicesVSResources.Require_colon}
public Class()
: base()
{{
}}
//]
}}
}}
namespace NS2
{{
class Class
{{
//[
// {ServicesVSResources.Over_colon}
public Class() :
base()
{{
}}
//]
}}
}}
";
#endregion
#region arithmetic binary parentheses
private readonly string s_arithmeticBinaryAlwaysForClarity = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a + (b * c);
// {ServicesVSResources.Over_colon}
var v = a + b * c;
//]
}}
}}
";
private readonly string s_arithmeticBinaryNeverIfUnnecessary = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a + b * c;
// {ServicesVSResources.Over_colon}
var v = a + (b * c);
//]
}}
}}
";
#endregion
#region relational binary parentheses
private readonly string s_relationalBinaryAlwaysForClarity = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = (a < b) == (c > d);
// {ServicesVSResources.Over_colon}
var v = a < b == c > d;
//]
}}
}}
";
private readonly string s_relationalBinaryNeverIfUnnecessary = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a < b == c > d;
// {ServicesVSResources.Over_colon}
var v = (a < b) == (c > d);
//]
}}
}}
";
#endregion
#region other binary parentheses
private readonly string s_otherBinaryAlwaysForClarity = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a || (b && c);
// {ServicesVSResources.Over_colon}
var v = a || b && c;
//]
}}
}}
";
private readonly string s_otherBinaryNeverIfUnnecessary = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a || b && c;
// {ServicesVSResources.Over_colon}
var v = a || (b && c);
//]
}}
}}
";
#endregion
#region other parentheses
private readonly string s_otherParenthesesAlwaysForClarity = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Keep_all_parentheses_in_colon}
var v = (a.b).Length;
//]
}}
}}
";
private readonly string s_otherParenthesesNeverIfUnnecessary = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a.b.Length;
// {ServicesVSResources.Over_colon}
var v = (a.b).Length;
//]
}}
}}
";
#endregion
#region unused parameters
private static readonly string s_avoidUnusedParametersNonPublicMethods = $@"
class C1
{{
//[
// {ServicesVSResources.Prefer_colon}
private void M()
{{
}}
//]
}}
class C2
{{
//[
// {ServicesVSResources.Over_colon}
private void M(int param)
{{
}}
//]
}}
";
private static readonly string s_avoidUnusedParametersAllMethods = $@"
class C1
{{
//[
// {ServicesVSResources.Prefer_colon}
public void M()
{{
}}
//]
}}
class C2
{{
//[
// {ServicesVSResources.Over_colon}
public void M(int param)
{{
}}
//]
}}
";
#endregion
#region unused values
private static readonly string s_avoidUnusedValueAssignmentUnusedLocal = $@"
class C
{{
int M()
{{
//[
// {ServicesVSResources.Prefer_colon}
int unused = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local}
int x = 1;
//]
return x;
}}
int Computation() => 0;
}}
class C2
{{
int M()
{{
//[
// {ServicesVSResources.Over_colon}
int x = Computation(); // {ServicesVSResources.Value_assigned_here_is_never_used}
x = 1;
//]
return x;
}}
int Computation() => 0;
}}
";
private static readonly string s_avoidUnusedValueAssignmentDiscard = $@"
class C
{{
int M()
{{
//[
// {ServicesVSResources.Prefer_colon}
_ = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_discard}
int x = 1;
//]
return x;
}}
int Computation() => 0;
}}
class C2
{{
int M()
{{
//[
// {ServicesVSResources.Over_colon}
int x = Computation(); // {ServicesVSResources.Value_assigned_here_is_never_used}
x = 1;
//]
return x;
}}
int Computation() => 0;
}}
";
private static readonly string s_avoidUnusedValueExpressionStatementUnusedLocal = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
int unused = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local}
//]
}}
int Computation() => 0;
}}
class C2
{{
void M()
{{
//[
// {ServicesVSResources.Over_colon}
Computation(); // {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored}
//]
}}
int Computation() => 0;
}}
";
private static readonly string s_avoidUnusedValueExpressionStatementDiscard = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
_ = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_discard}
//]
}}
int Computation() => 0;
}}
class C2
{{
void M()
{{
//[
// {ServicesVSResources.Over_colon}
Computation(); // {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored}
//]
}}
int Computation() => 0;
}}
";
#endregion
#endregion
internal StyleViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp)
{
var collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(CodeStyleItems);
collectionView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AbstractCodeStyleOptionViewModel.GroupName)));
var qualifyGroupTitle = CSharpVSResources.this_preferences_colon;
var predefinedTypesGroupTitle = CSharpVSResources.predefined_type_preferences_colon;
var varGroupTitle = CSharpVSResources.var_preferences_colon;
var nullCheckingGroupTitle = CSharpVSResources.null_checking_colon;
var usingsGroupTitle = CSharpVSResources.using_preferences_colon;
var modifierGroupTitle = ServicesVSResources.Modifier_preferences_colon;
var codeBlockPreferencesGroupTitle = ServicesVSResources.Code_block_preferences_colon;
var expressionPreferencesGroupTitle = ServicesVSResources.Expression_preferences_colon;
var patternMatchingPreferencesGroupTitle = CSharpVSResources.Pattern_matching_preferences_colon;
var variablePreferencesGroupTitle = ServicesVSResources.Variable_preferences_colon;
var parameterPreferencesGroupTitle = ServicesVSResources.Parameter_preferences_colon;
var newLinePreferencesGroupTitle = ServicesVSResources.New_line_preferences_experimental_colon;
var usingDirectivePlacementPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Inside_namespace, isChecked: false),
new CodeStylePreference(CSharpVSResources.Outside_namespace, isChecked: false),
};
var qualifyMemberAccessPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Prefer_this, isChecked: true),
new CodeStylePreference(CSharpVSResources.Do_not_prefer_this, isChecked: false),
};
var predefinedTypesPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(ServicesVSResources.Prefer_predefined_type, isChecked: true),
new CodeStylePreference(ServicesVSResources.Prefer_framework_type, isChecked: false),
};
var typeStylePreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Prefer_var, isChecked: true),
new CodeStylePreference(CSharpVSResources.Prefer_explicit_type, isChecked: false),
};
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyFieldAccess, CSharpVSResources.Qualify_field_access_with_this, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyPropertyAccess, CSharpVSResources.Qualify_property_access_with_this, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyMethodAccess, CSharpVSResources.Qualify_method_access_with_this, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyEventAccess, CSharpVSResources.Qualify_event_access_with_this, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, s_intrinsicPreviewDeclarationTrue, s_intrinsicPreviewDeclarationFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, s_intrinsicPreviewMemberAccessTrue, s_intrinsicPreviewMemberAccessFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences));
// Use var
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarForBuiltInTypes, CSharpVSResources.For_built_in_types, s_varForIntrinsicsPreviewTrue, s_varForIntrinsicsPreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CSharpVSResources.When_variable_type_is_apparent, s_varWhereApparentPreviewTrue, s_varWhereApparentPreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarElsewhere, CSharpVSResources.Elsewhere, s_varWherePossiblePreviewTrue, s_varWherePossiblePreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences));
// Code block
AddBracesOptions(optionStore, codeBlockPreferencesGroupTitle);
AddNamespaceDeclarationsOptions(optionStore, codeBlockPreferencesGroupTitle);
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, this, optionStore, codeBlockPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSimpleUsingStatement, ServicesVSResources.Prefer_simple_using_statement, s_preferSimpleUsingStatement, s_preferSimpleUsingStatement, this, optionStore, codeBlockPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, this, optionStore, codeBlockPreferencesGroupTitle));
AddParenthesesOptions(OptionStore);
// Expression preferences
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpression, s_preferSimplifiedConditionalExpression, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSwitchExpression, CSharpVSResources.Prefer_switch_expression, s_preferSwitchExpression, s_preferSwitchExpression, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, ServicesVSResources.Prefer_simple_default_expression, s_preferSimpleDefaultExpression, s_preferSimpleDefaultExpression, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferLocalOverAnonymousFunction, ServicesVSResources.Prefer_local_function_over_anonymous_function, s_preferLocalFunctionOverAnonymousFunction, s_preferLocalFunctionOverAnonymousFunction, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, CSharpVSResources.Prefer_implicit_object_creation_when_type_is_apparent, s_preferImplicitObjectCreationWhenTypeIsApparent, s_preferImplicitObjectCreationWhenTypeIsApparent, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferIndexOperator, ServicesVSResources.Prefer_index_operator, s_preferIndexOperator, s_preferIndexOperator, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferRangeOperator, ServicesVSResources.Prefer_range_operator, s_preferRangeOperator, s_preferRangeOperator, this, optionStore, expressionPreferencesGroupTitle));
// Pattern matching
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatching, CSharpVSResources.Prefer_pattern_matching, s_preferPatternMatching, s_preferPatternMatching, this, optionStore, patternMatchingPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck, CSharpVSResources.Prefer_pattern_matching_over_is_with_cast_check, s_preferPatternMatchingOverIsWithCastCheck, s_preferPatternMatchingOverIsWithCastCheck, this, optionStore, patternMatchingPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, CSharpVSResources.Prefer_pattern_matching_over_as_with_null_check, s_preferPatternMatchingOverAsWithNullCheck, s_preferPatternMatchingOverAsWithNullCheck, this, optionStore, patternMatchingPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferNotPattern, CSharpVSResources.Prefer_pattern_matching_over_mixed_type_check, s_preferPatternMatchingOverMixedTypeCheck, s_preferPatternMatchingOverMixedTypeCheck, this, optionStore, patternMatchingPreferencesGroupTitle));
AddExpressionBodyOptions(optionStore, expressionPreferencesGroupTitle);
AddUnusedValueOptions(optionStore, expressionPreferencesGroupTitle);
// Variable preferences
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferInlinedVariableDeclaration, ServicesVSResources.Prefer_inlined_variable_declaration, s_preferInlinedVariableDeclaration, s_preferInlinedVariableDeclaration, this, optionStore, variablePreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferDeconstructedVariableDeclaration, ServicesVSResources.Prefer_deconstructed_variable_declaration, s_preferDeconstructedVariableDeclaration, s_preferDeconstructedVariableDeclaration, this, optionStore, variablePreferencesGroupTitle));
// Null preferences.
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferThrowExpression, CSharpVSResources.Prefer_throw_expression, s_preferThrowExpression, s_preferThrowExpression, this, optionStore, nullCheckingGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferConditionalDelegateCall, CSharpVSResources.Prefer_conditional_delegate_call, s_preferConditionalDelegateCall, s_preferConditionalDelegateCall, this, optionStore, nullCheckingGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, this, optionStore, nullCheckingGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, this, optionStore, nullCheckingGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, CSharpVSResources.Prefer_is_null_for_reference_equality_checks, s_preferIsNullOverReferenceEquals, s_preferIsNullOverReferenceEquals, this, optionStore, nullCheckingGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, CSharpVSResources.Prefer_null_check_over_type_check, s_preferNullcheckOverTypeCheck, s_preferNullcheckOverTypeCheck, this, optionStore, nullCheckingGroupTitle));
// Using directive preferences.
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<AddImportPlacement>(
CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CSharpVSResources.Preferred_using_directive_placement,
new[] { AddImportPlacement.InsideNamespace, AddImportPlacement.OutsideNamespace },
s_usingDirectivePlacement, this, optionStore, usingsGroupTitle, usingDirectivePlacementPreferences));
// Modifier preferences.
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, this, optionStore, modifierGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferStaticLocalFunction, ServicesVSResources.Prefer_static_local_functions, s_preferStaticLocalFunction, s_preferStaticLocalFunction, this, optionStore, modifierGroupTitle));
// Parameter preferences
AddParameterOptions(optionStore, parameterPreferencesGroupTitle);
// New line preferences.
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowMultipleBlankLines, ServicesVSResources.Allow_multiple_blank_lines, s_allow_multiple_blank_lines_true, s_allow_multiple_blank_lines_false, this, optionStore, newLinePreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CSharpVSResources.Allow_embedded_statements_on_same_line, s_allow_embedded_statements_on_same_line_true, s_allow_embedded_statements_on_same_line_false, this, optionStore, newLinePreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CSharpVSResources.Allow_blank_lines_between_consecutive_braces, s_allow_blank_line_between_consecutive_braces_true, s_allow_blank_line_between_consecutive_braces_false, this, optionStore, newLinePreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, ServicesVSResources.Allow_statement_immediately_after_block, s_allow_statement_immediately_after_block_true, s_allow_statement_immediately_after_block_false, this, optionStore, newLinePreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CSharpVSResources.Allow_bank_line_after_colon_in_constructor_initializer, s_allow_bank_line_after_colon_in_constructor_initializer_true, s_allow_bank_line_after_colon_in_constructor_initializer_false, this, optionStore, newLinePreferencesGroupTitle));
}
private void AddParenthesesOptions(OptionStore optionStore)
{
AddParenthesesOption(
LanguageNames.CSharp, optionStore, CodeStyleOptions2.ArithmeticBinaryParentheses,
CSharpVSResources.In_arithmetic_binary_operators,
new[] { s_arithmeticBinaryAlwaysForClarity, s_arithmeticBinaryNeverIfUnnecessary },
defaultAddForClarity: true);
AddParenthesesOption(
LanguageNames.CSharp, optionStore, CodeStyleOptions2.OtherBinaryParentheses,
CSharpVSResources.In_other_binary_operators,
new[] { s_otherBinaryAlwaysForClarity, s_otherBinaryNeverIfUnnecessary },
defaultAddForClarity: true);
AddParenthesesOption(
LanguageNames.CSharp, optionStore, CodeStyleOptions2.RelationalBinaryParentheses,
CSharpVSResources.In_relational_binary_operators,
new[] { s_relationalBinaryAlwaysForClarity, s_relationalBinaryNeverIfUnnecessary },
defaultAddForClarity: true);
AddParenthesesOption(
LanguageNames.CSharp, optionStore, CodeStyleOptions2.OtherParentheses,
ServicesVSResources.In_other_operators,
new[] { s_otherParenthesesAlwaysForClarity, s_otherParenthesesNeverIfUnnecessary },
defaultAddForClarity: false);
}
private void AddBracesOptions(OptionStore optionStore, string bracesPreferenceGroupTitle)
{
var bracesPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(ServicesVSResources.Yes, isChecked: false),
new CodeStylePreference(ServicesVSResources.No, isChecked: false),
new CodeStylePreference(CSharpVSResources.When_on_multiple_lines, isChecked: false),
};
var enumValues = new[] { PreferBracesPreference.Always, PreferBracesPreference.None, PreferBracesPreference.WhenMultiline };
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<PreferBracesPreference>(
CSharpCodeStyleOptions.PreferBraces,
ServicesVSResources.Prefer_braces,
enumValues,
new[] { s_preferBraces, s_doNotPreferBraces, s_preferBracesWhenMultiline },
this, optionStore, bracesPreferenceGroupTitle, bracesPreferences));
}
private void AddNamespaceDeclarationsOptions(OptionStore optionStore, string group)
{
var preferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Block_scoped, isChecked: false),
new CodeStylePreference(CSharpVSResources.File_scoped, isChecked: false),
};
var enumValues = new[] { NamespaceDeclarationPreference.BlockScoped, NamespaceDeclarationPreference.FileScoped };
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<NamespaceDeclarationPreference>(
CSharpCodeStyleOptions.NamespaceDeclarations,
ServicesVSResources.Namespace_declarations,
enumValues,
new[] { s_preferBlockNamespace, s_preferFileScopedNamespace },
this, optionStore, group, preferences));
}
private void AddExpressionBodyOptions(OptionStore optionStore, string expressionPreferencesGroupTitle)
{
var expressionBodyPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Never, isChecked: false),
new CodeStylePreference(CSharpVSResources.When_possible, isChecked: false),
new CodeStylePreference(CSharpVSResources.When_on_single_line, isChecked: false),
};
var enumValues = new[] { ExpressionBodyPreference.Never, ExpressionBodyPreference.WhenPossible, ExpressionBodyPreference.WhenOnSingleLine };
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedMethods,
ServicesVSResources.Use_expression_body_for_methods,
enumValues,
new[] { s_preferBlockBodyForMethods, s_preferExpressionBodyForMethods, s_preferExpressionBodyForMethods },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedConstructors,
ServicesVSResources.Use_expression_body_for_constructors,
enumValues,
new[] { s_preferBlockBodyForConstructors, s_preferExpressionBodyForConstructors, s_preferExpressionBodyForConstructors },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedOperators,
ServicesVSResources.Use_expression_body_for_operators,
enumValues,
new[] { s_preferBlockBodyForOperators, s_preferExpressionBodyForOperators, s_preferExpressionBodyForOperators },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedProperties,
ServicesVSResources.Use_expression_body_for_properties,
enumValues,
new[] { s_preferBlockBodyForProperties, s_preferExpressionBodyForProperties, s_preferExpressionBodyForProperties },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedIndexers,
ServicesVSResources.Use_expression_body_for_indexers,
enumValues,
new[] { s_preferBlockBodyForIndexers, s_preferExpressionBodyForIndexers, s_preferExpressionBodyForIndexers },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedAccessors,
ServicesVSResources.Use_expression_body_for_accessors,
enumValues,
new[] { s_preferBlockBodyForAccessors, s_preferExpressionBodyForAccessors, s_preferExpressionBodyForAccessors },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedLambdas,
ServicesVSResources.Use_expression_body_for_lambdas,
enumValues,
new[] { s_preferBlockBodyForLambdas, s_preferExpressionBodyForLambdas, s_preferExpressionBodyForLambdas },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions,
ServicesVSResources.Use_expression_body_for_local_functions,
enumValues,
new[] { s_preferBlockBodyForLocalFunctions, s_preferExpressionBodyForLocalFunctions, s_preferExpressionBodyForLocalFunctions },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
}
private void AddUnusedValueOptions(OptionStore optionStore, string expressionPreferencesGroupTitle)
{
var unusedValuePreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Unused_local, isChecked: false),
new CodeStylePreference(CSharpVSResources.Discard, isChecked: true),
};
var enumValues = new[]
{
UnusedValuePreference.UnusedLocalVariable,
UnusedValuePreference.DiscardVariable
};
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<UnusedValuePreference>(
CSharpCodeStyleOptions.UnusedValueAssignment,
ServicesVSResources.Avoid_unused_value_assignments,
enumValues,
new[] { s_avoidUnusedValueAssignmentUnusedLocal, s_avoidUnusedValueAssignmentDiscard },
this,
optionStore,
expressionPreferencesGroupTitle,
unusedValuePreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<UnusedValuePreference>(
CSharpCodeStyleOptions.UnusedValueExpressionStatement,
ServicesVSResources.Avoid_expression_statements_that_implicitly_ignore_value,
enumValues,
new[] { s_avoidUnusedValueExpressionStatementUnusedLocal, s_avoidUnusedValueExpressionStatementDiscard },
this,
optionStore,
expressionPreferencesGroupTitle,
unusedValuePreferences));
}
private void AddParameterOptions(OptionStore optionStore, string parameterPreferencesGroupTitle)
{
var examples = new[]
{
s_avoidUnusedParametersNonPublicMethods,
s_avoidUnusedParametersAllMethods
};
AddUnusedParameterOption(LanguageNames.CSharp, optionStore, parameterPreferencesGroupTitle, examples);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Windows.Data;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting
{
/// <summary>
/// This is the view model for CodeStyle options page.
/// </summary>
/// <remarks>
/// The codestyle options page is defined in <see cref="CodeStylePage"/>
/// </remarks>
internal class StyleViewModel : AbstractOptionPreviewViewModel
{
#region "Preview Text"
private const string s_fieldDeclarationPreviewTrue = @"
class C{
int capacity;
void Method()
{
//[
this.capacity = 0;
//]
}
}";
private const string s_fieldDeclarationPreviewFalse = @"
class C{
int capacity;
void Method()
{
//[
capacity = 0;
//]
}
}";
private const string s_propertyDeclarationPreviewTrue = @"
class C{
public int Id { get; set; }
void Method()
{
//[
this.Id = 0;
//]
}
}";
private const string s_propertyDeclarationPreviewFalse = @"
class C{
public int Id { get; set; }
void Method()
{
//[
Id = 0;
//]
}
}";
private const string s_eventDeclarationPreviewTrue = @"
using System;
class C{
event EventHandler Elapsed;
void Handler(object sender, EventArgs args)
{
//[
this.Elapsed += Handler;
//]
}
}";
private const string s_eventDeclarationPreviewFalse = @"
using System;
class C{
event EventHandler Elapsed;
void Handler(object sender, EventArgs args)
{
//[
Elapsed += Handler;
//]
}
}";
private const string s_methodDeclarationPreviewTrue = @"
using System;
class C{
void Display()
{
//[
this.Display();
//]
}
}";
private const string s_methodDeclarationPreviewFalse = @"
using System;
class C{
void Display()
{
//[
Display();
//]
}
}";
private const string s_intrinsicPreviewDeclarationTrue = @"
class Program
{
//[
private int _member;
static void M(int argument)
{
int local;
}
//]
}";
private const string s_intrinsicPreviewDeclarationFalse = @"
using System;
class Program
{
//[
private Int32 _member;
static void M(Int32 argument)
{
Int32 local;
}
//]
}";
private const string s_intrinsicPreviewMemberAccessTrue = @"
class Program
{
//[
static void M()
{
var local = int.MaxValue;
}
//]
}";
private const string s_intrinsicPreviewMemberAccessFalse = @"
using System;
class Program
{
//[
static void M()
{
var local = Int32.MaxValue;
}
//]
}";
private static readonly string s_varForIntrinsicsPreviewFalse = $@"
using System;
class C{{
void Method()
{{
//[
int x = 5; // {ServicesVSResources.built_in_types}
//]
}}
}}";
private static readonly string s_varForIntrinsicsPreviewTrue = $@"
using System;
class C{{
void Method()
{{
//[
var x = 5; // {ServicesVSResources.built_in_types}
//]
}}
}}";
private static readonly string s_varWhereApparentPreviewFalse = $@"
using System;
class C{{
void Method()
{{
//[
C cobj = new C(); // {ServicesVSResources.type_is_apparent_from_assignment_expression}
//]
}}
}}";
private static readonly string s_varWhereApparentPreviewTrue = $@"
using System;
class C{{
void Method()
{{
//[
var cobj = new C(); // {ServicesVSResources.type_is_apparent_from_assignment_expression}
//]
}}
}}";
private static readonly string s_varWherePossiblePreviewFalse = $@"
using System;
class C{{
void Init()
{{
//[
Action f = this.Init(); // {ServicesVSResources.everywhere_else}
//]
}}
}}";
private static readonly string s_varWherePossiblePreviewTrue = $@"
using System;
class C{{
void Init()
{{
//[
var f = this.Init(); // {ServicesVSResources.everywhere_else}
//]
}}
}}";
private static readonly string s_preferThrowExpression = $@"
using System;
class C
{{
private string s;
void M1(string s)
{{
//[
// {ServicesVSResources.Prefer_colon}
this.s = s ?? throw new ArgumentNullException(nameof(s));
//]
}}
void M2(string s)
{{
//[
// {ServicesVSResources.Over_colon}
if (s == null)
{{
throw new ArgumentNullException(nameof(s));
}}
this.s = s;
//]
}}
}}
";
private static readonly string s_preferCoalesceExpression = $@"
using System;
class C
{{
private string s;
void M1(string s)
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = x ?? y;
//]
}}
void M2(string s)
{{
//[
// {ServicesVSResources.Over_colon}
var v = x != null ? x : y; // {ServicesVSResources.or}
var v = x == null ? y : x;
//]
}}
}}
";
private static readonly string s_preferConditionalDelegateCall = $@"
using System;
class C
{{
private string s;
void M1(string s)
{{
//[
// {ServicesVSResources.Prefer_colon}
func?.Invoke(args);
//]
}}
void M2(string s)
{{
//[
// {ServicesVSResources.Over_colon}
if (func != null)
{{
func(args);
}}
//]
}}
}}
";
private static readonly string s_preferNullPropagation = $@"
using System;
class C
{{
void M1(object o)
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = o?.ToString();
//]
}}
void M2(object o)
{{
//[
// {ServicesVSResources.Over_colon}
var v = o == null ? null : o.ToString(); // {ServicesVSResources.or}
var v = o != null ? o.ToString() : null;
//]
}}
}}
";
private static readonly string s_preferSwitchExpression = $@"
class C
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
return num switch
{{
1 => 1,
_ => 2,
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
switch (num)
{{
case 1:
return 1;
default:
return 2;
}}
//]
}}
}}
";
private static readonly string s_preferPatternMatching = $@"
class C
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
return num is 1 or 2;
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
return num == 1 || num == 2;
//]
}}
}}
";
private static readonly string s_preferPatternMatchingOverAsWithNullCheck = $@"
class C
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
if (o is string s)
{{
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
var s = o as string;
if (s != null)
{{
}}
//]
}}
}}
";
private static readonly string s_preferPatternMatchingOverMixedTypeCheck = $@"
class C
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
if (o is not string s)
{{
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
if (!(o is string s))
{{
}}
//]
}}
}}
";
private static readonly string s_preferConditionalExpressionOverIfWithAssignments = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
string s = expr ? ""hello"" : ""world"";
// {ServicesVSResources.Over_colon}
string s;
if (expr)
{{
s = ""hello"";
}}
else
{{
s = ""world"";
}}
//]
}}
}}
";
private static readonly string s_preferConditionalExpressionOverIfWithReturns = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
return expr ? ""hello"" : ""world"";
// {ServicesVSResources.Over_colon}
if (expr)
{{
return ""hello"";
}}
else
{{
return ""world"";
}}
//]
}}
}}
";
private static readonly string s_preferPatternMatchingOverIsWithCastCheck = $@"
class C
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
if (o is int i)
{{
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
if (o is int)
{{
var i = (int)o;
}}
//]
}}
}}
";
private static readonly string s_preferObjectInitializer = $@"
using System;
class Customer
{{
private int Age;
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
var c = new Customer()
{{
Age = 21
}};
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
var c = new Customer();
c.Age = 21;
//]
}}
}}
";
private static readonly string s_preferCollectionInitializer = $@"
using System.Collections.Generic;
class Customer
{{
private int Age;
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
var list = new List<int>
{{
1,
2,
3
}};
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
//]
}}
}}
";
private static readonly string s_preferExplicitTupleName = $@"
class Customer
{{
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
(string name, int age) customer = GetCustomer();
var name = customer.name;
var age = customer.age;
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
(string name, int age) customer = GetCustomer();
var name = customer.Item1;
var age = customer.Item2;
//]
}}
}}
";
private static readonly string s_preferSimpleDefaultExpression = $@"
using System.Threading;
class Customer1
{{
//[
// {ServicesVSResources.Prefer_colon}
void DoWork(CancellationToken cancellationToken = default) {{ }}
//]
}}
class Customer2
{{
//[
// {ServicesVSResources.Over_colon}
void DoWork(CancellationToken cancellationToken = default(CancellationToken)) {{ }}
//]
}}
";
private static readonly string s_preferSimplifiedConditionalExpression = $@"
using System.Threading;
class Customer1
{{
bool A() => true;
bool B() => true;
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
var x = A() && B();
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
var x = A() && B() ? true : false
//]
}}
}}
";
private static readonly string s_preferInferredTupleName = $@"
using System.Threading;
class Customer
{{
void M1(int age, string name)
{{
//[
// {ServicesVSResources.Prefer_colon}
var tuple = (age, name);
//]
}}
void M2(int age, string name)
{{
//[
// {ServicesVSResources.Over_colon}
var tuple = (age: age, name: name);
//]
}}
}}
";
private static readonly string s_preferInferredAnonymousTypeMemberName = $@"
using System.Threading;
class Customer
{{
void M1(int age, string name)
{{
//[
// {ServicesVSResources.Prefer_colon}
var anon = new {{ age, name }};
//]
}}
void M2(int age, string name)
{{
//[
// {ServicesVSResources.Over_colon}
var anon = new {{ age = age, name = name }};
//]
}}
}}
";
private static readonly string s_preferInlinedVariableDeclaration = $@"
using System;
class Customer
{{
void M1(string value)
{{
//[
// {ServicesVSResources.Prefer_colon}
if (int.TryParse(value, out int i))
{{
}}
//]
}}
void M2(string value)
{{
//[
// {ServicesVSResources.Over_colon}
int i;
if (int.TryParse(value, out i))
{{
}}
//]
}}
}}
";
private static readonly string s_preferDeconstructedVariableDeclaration = $@"
using System;
class Customer
{{
void M1(string value)
{{
//[
// {ServicesVSResources.Prefer_colon}
var (name, age) = GetPersonTuple();
Console.WriteLine($""{{name}} {{age}}"");
(int x, int y) = GetPointTuple();
Console.WriteLine($""{{x}} {{y}}"");
//]
}}
void M2(string value)
{{
//[
// {ServicesVSResources.Over_colon}
var person = GetPersonTuple();
Console.WriteLine($""{{person.name}} {{person.age}}"");
(int x, int y) point = GetPointTuple();
Console.WriteLine($""{{point.x}} {{point.y}}"");
//]
}}
}}
";
private static readonly string s_doNotPreferBraces = $@"
using System;
class Customer
{{
private int Age;
void M1()
{{
//[
// {ServicesVSResources.Allow_colon}
if (test) Console.WriteLine(""Text"");
// {ServicesVSResources.Allow_colon}
if (test)
Console.WriteLine(""Text"");
// {ServicesVSResources.Allow_colon}
if (test)
Console.WriteLine(
""Text"");
// {ServicesVSResources.Allow_colon}
if (test)
{{
Console.WriteLine(
""Text"");
}}
//]
}}
}}
";
private static readonly string s_preferBracesWhenMultiline = $@"
using System;
class Customer
{{
private int Age;
void M1()
{{
//[
// {ServicesVSResources.Allow_colon}
if (test) Console.WriteLine(""Text"");
// {ServicesVSResources.Allow_colon}
if (test)
Console.WriteLine(""Text"");
// {ServicesVSResources.Prefer_colon}
if (test)
{{
Console.WriteLine(
""Text"");
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
if (test)
Console.WriteLine(
""Text"");
//]
}}
}}
";
private static readonly string s_preferBraces = $@"
using System;
class Customer
{{
private int Age;
void M1()
{{
//[
// {ServicesVSResources.Prefer_colon}
if (test)
{{
Console.WriteLine(""Text"");
}}
//]
}}
void M2()
{{
//[
// {ServicesVSResources.Over_colon}
if (test)
Console.WriteLine(""Text"");
//]
}}
}}
";
private static readonly string s_preferAutoProperties = $@"
using System;
class Customer1
{{
//[
// {ServicesVSResources.Prefer_colon}
public int Age {{ get; }}
//]
}}
class Customer2
{{
//[
// {ServicesVSResources.Over_colon}
private int age;
public int Age
{{
get
{{
return age;
}}
}}
//]
}}
";
private static readonly string s_preferFileScopedNamespace = $@"
//[
// {ServicesVSResources.Prefer_colon}
namespace A.B.C;
public class Program
{{
}}
//]
//[
// {ServicesVSResources.Over_colon}
namespace A.B.C
{{
public class Program
{{
}}
}}
//]
";
private static readonly string s_preferBlockNamespace = $@"
//[
// {ServicesVSResources.Prefer_colon}
namespace A.B.C
{{
public class Program
{{
}}
}}
//]
//[
// {ServicesVSResources.Over_colon}
namespace A.B.C;
public class Program
{{
}}
//]
";
private static readonly string s_preferSimpleUsingStatement = $@"
using System;
class Customer1
{{
//[
// {ServicesVSResources.Prefer_colon}
void Method()
{{
using var resource = GetResource();
ProcessResource(resource);
}}
//]
}}
class Customer2
{{
//[
// {ServicesVSResources.Over_colon}
void Method()
{{
using (var resource = GetResource())
{{
ProcessResource(resource);
}}
}}
//]
}}
";
private static readonly string s_preferSystemHashCode = $@"
using System;
class Customer1
{{
int a, b, c;
//[
// {ServicesVSResources.Prefer_colon}
// {ServicesVSResources.Requires_System_HashCode_be_present_in_project}
public override int GetHashCode()
{{
return System.HashCode.Combine(a, b, c);
}}
//]
}}
class Customer2
{{
int a, b, c;
//[
// {ServicesVSResources.Over_colon}
public override int GetHashCode()
{{
var hashCode = 339610899;
hashCode = hashCode * -1521134295 + a.GetHashCode();
hashCode = hashCode * -1521134295 + b.GetHashCode();
hashCode = hashCode * -1521134295 + c.GetHashCode();
return hashCode;
}}
//]
}}
";
private static readonly string s_preferLocalFunctionOverAnonymousFunction = $@"
using System;
class Customer
{{
void M1(string value)
{{
//[
// {ServicesVSResources.Prefer_colon}
int fibonacci(int n)
{{
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}}
//]
}}
void M2(string value)
{{
//[
// {ServicesVSResources.Over_colon}
Func<int, int> fibonacci = null;
fibonacci = (int n) =>
{{
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}};
//]
}}
}}
";
private static readonly string s_preferCompoundAssignments = $@"
using System;
class Customer
{{
void M1(int value)
{{
//[
// {ServicesVSResources.Prefer_colon}
value += 10;
//]
}}
void M2(int value)
{{
//[
// {ServicesVSResources.Over_colon}
value = value + 10
//]
}}
}}
";
private static readonly string s_preferImplicitObjectCreationWhenTypeIsApparent = $@"
using System.Collections.Generic;
class Order {{}}
//[
class Customer
{{
// {ServicesVSResources.Prefer_colon}
private readonly List<Order> orders = new();
// {ServicesVSResources.Over_colon}
private readonly List<Order> orders = new List<Order>();
}}
//]
";
private static readonly string s_preferIndexOperator = $@"
using System;
class Customer
{{
void M1(string value)
{{
//[
// {ServicesVSResources.Prefer_colon}
var ch = value[^1];
//]
}}
void M2(string value)
{{
//[
// {ServicesVSResources.Over_colon}
var ch = value[value.Length - 1];
//]
}}
}}
";
private static readonly string s_preferRangeOperator = $@"
using System;
class Customer
{{
void M1(string value)
{{
//[
// {ServicesVSResources.Prefer_colon}
var sub = value[1..^1];
//]
}}
void M2(string value)
{{
//[
// {ServicesVSResources.Over_colon}
var sub = value.Substring(1, value.Length - 2);
//]
}}
}}
";
private static readonly string s_preferIsNullOverReferenceEquals = $@"
using System;
class Customer
{{
void M1(string value1, string value2)
{{
//[
// {ServicesVSResources.Prefer_colon}
if (value1 is null)
return;
if (value2 is null)
return;
//]
}}
void M2(string value1, string value2)
{{
//[
// {ServicesVSResources.Over_colon}
if (object.ReferenceEquals(value1, null))
return;
if ((object)value2 == null)
return;
//]
}}
}}
";
private static readonly string s_preferNullcheckOverTypeCheck = $@"
using System;
class Customer
{{
void M1(string value1, string value2)
{{
//[
// {ServicesVSResources.Prefer_colon}
if (value1 is null)
return;
if (value2 is not null)
return;
//]
}}
void M2(string value1, string value2)
{{
//[
// {ServicesVSResources.Over_colon}
if (value1 is not object)
return;
if (value2 is object)
return;
//]
}}
}}
";
#region expression and block bodies
private const string s_preferExpressionBodyForMethods = @"
using System;
//[
class Customer
{
private int Age;
public int GetAge() => this.Age;
}
//]
";
private const string s_preferBlockBodyForMethods = @"
using System;
//[
class Customer
{
private int Age;
public int GetAge()
{
return this.Age;
}
}
//]
";
private const string s_preferExpressionBodyForConstructors = @"
using System;
//[
class Customer
{
private int Age;
public Customer(int age) => Age = age;
}
//]
";
private const string s_preferBlockBodyForConstructors = @"
using System;
//[
class Customer
{
private int Age;
public Customer(int age)
{
Age = age;
}
}
//]
";
private const string s_preferExpressionBodyForOperators = @"
using System;
struct ComplexNumber
{
//[
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
=> new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
//]
}
";
private const string s_preferBlockBodyForOperators = @"
using System;
struct ComplexNumber
{
//[
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
{
return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
//]
}
";
private const string s_preferExpressionBodyForProperties = @"
using System;
//[
class Customer
{
private int _age;
public int Age => _age;
}
//]
";
private const string s_preferBlockBodyForProperties = @"
using System;
//[
class Customer
{
private int _age;
public int Age { get { return _age; } }
}
//]
";
private const string s_preferExpressionBodyForAccessors = @"
using System;
//[
class Customer
{
private int _age;
public int Age
{
get => _age;
set => _age = value;
}
}
//]
";
private const string s_preferBlockBodyForAccessors = @"
using System;
//[
class Customer
{
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
}
//]
";
private const string s_preferExpressionBodyForIndexers = @"
using System;
//[
class List<T>
{
private T[] _values;
public T this[int i] => _values[i];
}
//]
";
private const string s_preferBlockBodyForIndexers = @"
using System;
//[
class List<T>
{
private T[] _values;
public T this[int i] { get { return _values[i]; } }
}
//]
";
private const string s_preferExpressionBodyForLambdas = @"
using System;
class Customer
{
void Method()
{
//[
Func<int, string> f = a => a.ToString();
//]
}
}
";
private const string s_preferBlockBodyForLambdas = @"
using System;
class Customer
{
void Method()
{
//[
Func<int, string> f = a =>
{
return a.ToString();
};
//]
}
}
";
private const string s_preferExpressionBodyForLocalFunctions = @"
using System;
//[
class Customer
{
private int Age;
public int GetAge()
{
return GetAgeLocal();
int GetAgeLocal() => this.Age;
}
}
//]
";
private const string s_preferBlockBodyForLocalFunctions = @"
using System;
//[
class Customer
{
private int Age;
public int GetAge()
{
return GetAgeLocal();
int GetAgeLocal()
{
return this.Age;
}
}
}
//]
";
private static readonly string s_preferReadonly = $@"
class Customer1
{{
//[
// {ServicesVSResources.Prefer_colon}
// '_value' can only be assigned in constructor
private readonly int _value = 0;
//]
}}
class Customer2
{{
//[
// {ServicesVSResources.Over_colon}
// '_value' can be assigned anywhere
private int _value = 0;
//]
}}
";
private static readonly string[] s_usingDirectivePlacement = new[] { $@"
//[
namespace Namespace
{{
// {CSharpVSResources.Inside_namespace}
using System;
using System.Linq;
class Customer
{{
}}
}}
//]", $@"
//[
// {CSharpVSResources.Outside_namespace}
using System;
using System.Linq;
namespace Namespace
{{
class Customer
{{
}}
}}
//]
" };
private static readonly string s_preferStaticLocalFunction = $@"
class Customer1
{{
//[
void Method()
{{
// {ServicesVSResources.Prefer_colon}
static int fibonacci(int n)
{{
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}}
}}
//]
}}
class Customer2
{{
//[
void Method()
{{
// {ServicesVSResources.Over_colon}
int fibonacci(int n)
{{
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}}
}}
//]
}}
";
private static readonly string s_allow_embedded_statements_on_same_line_true = $@"
class Class2
{{
void Method(int a, int b)
{{
//[
// {ServicesVSResources.Allow_colon}
if (a > b) return true;
//]
return false;
}}
}}
";
private static readonly string s_allow_embedded_statements_on_same_line_false = $@"
class Class1
{{
void Method(int a, int b)
{{
//[
// {ServicesVSResources.Require_colon}
if (a > b)
return true;
//]
return false;
}}
}}
class Class2
{{
void Method(int a, int b)
{{
//[
// {ServicesVSResources.Over_colon}
if (a > b) return true;
//]
return false;
}}
}}
";
private static readonly string s_allow_blank_line_between_consecutive_braces_true = $@"
class Class2
{{
//[
// {ServicesVSResources.Allow_colon}
void Method()
{{
if (true)
{{
DoWork();
}}
}}
//]
}}
";
private static readonly string s_allow_blank_line_between_consecutive_braces_false = $@"
class Class1
{{
//[
// {ServicesVSResources.Require_colon}
void Method()
{{
if (true)
{{
DoWork();
}}
}}
//]
}}
class Class2
{{
//[
// {ServicesVSResources.Over_colon}
void Method()
{{
if (true)
{{
DoWork();
}}
}}
//]
}}
";
private static readonly string s_allow_multiple_blank_lines_true = $@"
class Class2
{{
void Method()
{{
//[
// {ServicesVSResources.Allow_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
";
private static readonly string s_allow_multiple_blank_lines_false = $@"
class Class1
{{
void Method()
{{
//[
// {ServicesVSResources.Require_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
class Class2
{{
void Method()
{{
//[
// {ServicesVSResources.Over_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
";
private static readonly string s_allow_statement_immediately_after_block_true = $@"
class Class2
{{
void Method()
{{
//[
// {ServicesVSResources.Allow_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
";
private static readonly string s_allow_statement_immediately_after_block_false = $@"
class Class1
{{
void Method()
{{
//[
// {ServicesVSResources.Require_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
class Class2
{{
void Method()
{{
//[
// {ServicesVSResources.Over_colon}
if (true)
{{
DoWork();
}}
return;
//]
}}
}}
";
private static readonly string s_allow_bank_line_after_colon_in_constructor_initializer_true = $@"
class Class
{{
//[
// {ServicesVSResources.Allow_colon}
public Class() :
base()
{{
}}
//]
}}
";
private static readonly string s_allow_bank_line_after_colon_in_constructor_initializer_false = $@"
namespace NS1
{{
class Class
{{
//[
// {ServicesVSResources.Require_colon}
public Class()
: base()
{{
}}
//]
}}
}}
namespace NS2
{{
class Class
{{
//[
// {ServicesVSResources.Over_colon}
public Class() :
base()
{{
}}
//]
}}
}}
";
#endregion
#region arithmetic binary parentheses
private readonly string s_arithmeticBinaryAlwaysForClarity = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a + (b * c);
// {ServicesVSResources.Over_colon}
var v = a + b * c;
//]
}}
}}
";
private readonly string s_arithmeticBinaryNeverIfUnnecessary = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a + b * c;
// {ServicesVSResources.Over_colon}
var v = a + (b * c);
//]
}}
}}
";
#endregion
#region relational binary parentheses
private readonly string s_relationalBinaryAlwaysForClarity = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = (a < b) == (c > d);
// {ServicesVSResources.Over_colon}
var v = a < b == c > d;
//]
}}
}}
";
private readonly string s_relationalBinaryNeverIfUnnecessary = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a < b == c > d;
// {ServicesVSResources.Over_colon}
var v = (a < b) == (c > d);
//]
}}
}}
";
#endregion
#region other binary parentheses
private readonly string s_otherBinaryAlwaysForClarity = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a || (b && c);
// {ServicesVSResources.Over_colon}
var v = a || b && c;
//]
}}
}}
";
private readonly string s_otherBinaryNeverIfUnnecessary = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a || b && c;
// {ServicesVSResources.Over_colon}
var v = a || (b && c);
//]
}}
}}
";
#endregion
#region other parentheses
private readonly string s_otherParenthesesAlwaysForClarity = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Keep_all_parentheses_in_colon}
var v = (a.b).Length;
//]
}}
}}
";
private readonly string s_otherParenthesesNeverIfUnnecessary = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
var v = a.b.Length;
// {ServicesVSResources.Over_colon}
var v = (a.b).Length;
//]
}}
}}
";
#endregion
#region unused parameters
private static readonly string s_avoidUnusedParametersNonPublicMethods = $@"
class C1
{{
//[
// {ServicesVSResources.Prefer_colon}
private void M()
{{
}}
//]
}}
class C2
{{
//[
// {ServicesVSResources.Over_colon}
private void M(int param)
{{
}}
//]
}}
";
private static readonly string s_avoidUnusedParametersAllMethods = $@"
class C1
{{
//[
// {ServicesVSResources.Prefer_colon}
public void M()
{{
}}
//]
}}
class C2
{{
//[
// {ServicesVSResources.Over_colon}
public void M(int param)
{{
}}
//]
}}
";
#endregion
#region unused values
private static readonly string s_avoidUnusedValueAssignmentUnusedLocal = $@"
class C
{{
int M()
{{
//[
// {ServicesVSResources.Prefer_colon}
int unused = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local}
int x = 1;
//]
return x;
}}
int Computation() => 0;
}}
class C2
{{
int M()
{{
//[
// {ServicesVSResources.Over_colon}
int x = Computation(); // {ServicesVSResources.Value_assigned_here_is_never_used}
x = 1;
//]
return x;
}}
int Computation() => 0;
}}
";
private static readonly string s_avoidUnusedValueAssignmentDiscard = $@"
class C
{{
int M()
{{
//[
// {ServicesVSResources.Prefer_colon}
_ = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_discard}
int x = 1;
//]
return x;
}}
int Computation() => 0;
}}
class C2
{{
int M()
{{
//[
// {ServicesVSResources.Over_colon}
int x = Computation(); // {ServicesVSResources.Value_assigned_here_is_never_used}
x = 1;
//]
return x;
}}
int Computation() => 0;
}}
";
private static readonly string s_avoidUnusedValueExpressionStatementUnusedLocal = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
int unused = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local}
//]
}}
int Computation() => 0;
}}
class C2
{{
void M()
{{
//[
// {ServicesVSResources.Over_colon}
Computation(); // {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored}
//]
}}
int Computation() => 0;
}}
";
private static readonly string s_avoidUnusedValueExpressionStatementDiscard = $@"
class C
{{
void M()
{{
//[
// {ServicesVSResources.Prefer_colon}
_ = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_discard}
//]
}}
int Computation() => 0;
}}
class C2
{{
void M()
{{
//[
// {ServicesVSResources.Over_colon}
Computation(); // {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored}
//]
}}
int Computation() => 0;
}}
";
#endregion
#endregion
internal StyleViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp)
{
var collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(CodeStyleItems);
collectionView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AbstractCodeStyleOptionViewModel.GroupName)));
var qualifyGroupTitle = CSharpVSResources.this_preferences_colon;
var predefinedTypesGroupTitle = CSharpVSResources.predefined_type_preferences_colon;
var varGroupTitle = CSharpVSResources.var_preferences_colon;
var nullCheckingGroupTitle = CSharpVSResources.null_checking_colon;
var usingsGroupTitle = CSharpVSResources.using_preferences_colon;
var modifierGroupTitle = ServicesVSResources.Modifier_preferences_colon;
var codeBlockPreferencesGroupTitle = ServicesVSResources.Code_block_preferences_colon;
var expressionPreferencesGroupTitle = ServicesVSResources.Expression_preferences_colon;
var patternMatchingPreferencesGroupTitle = CSharpVSResources.Pattern_matching_preferences_colon;
var variablePreferencesGroupTitle = ServicesVSResources.Variable_preferences_colon;
var parameterPreferencesGroupTitle = ServicesVSResources.Parameter_preferences_colon;
var newLinePreferencesGroupTitle = ServicesVSResources.New_line_preferences_experimental_colon;
var usingDirectivePlacementPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Inside_namespace, isChecked: false),
new CodeStylePreference(CSharpVSResources.Outside_namespace, isChecked: false),
};
var qualifyMemberAccessPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Prefer_this, isChecked: true),
new CodeStylePreference(CSharpVSResources.Do_not_prefer_this, isChecked: false),
};
var predefinedTypesPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(ServicesVSResources.Prefer_predefined_type, isChecked: true),
new CodeStylePreference(ServicesVSResources.Prefer_framework_type, isChecked: false),
};
var typeStylePreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Prefer_var, isChecked: true),
new CodeStylePreference(CSharpVSResources.Prefer_explicit_type, isChecked: false),
};
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyFieldAccess, CSharpVSResources.Qualify_field_access_with_this, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyPropertyAccess, CSharpVSResources.Qualify_property_access_with_this, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyMethodAccess, CSharpVSResources.Qualify_method_access_with_this, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyEventAccess, CSharpVSResources.Qualify_event_access_with_this, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, s_intrinsicPreviewDeclarationTrue, s_intrinsicPreviewDeclarationFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, s_intrinsicPreviewMemberAccessTrue, s_intrinsicPreviewMemberAccessFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences));
// Use var
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarForBuiltInTypes, CSharpVSResources.For_built_in_types, s_varForIntrinsicsPreviewTrue, s_varForIntrinsicsPreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CSharpVSResources.When_variable_type_is_apparent, s_varWhereApparentPreviewTrue, s_varWhereApparentPreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarElsewhere, CSharpVSResources.Elsewhere, s_varWherePossiblePreviewTrue, s_varWherePossiblePreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences));
// Code block
AddBracesOptions(optionStore, codeBlockPreferencesGroupTitle);
AddNamespaceDeclarationsOptions(optionStore, codeBlockPreferencesGroupTitle);
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, this, optionStore, codeBlockPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSimpleUsingStatement, ServicesVSResources.Prefer_simple_using_statement, s_preferSimpleUsingStatement, s_preferSimpleUsingStatement, this, optionStore, codeBlockPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, this, optionStore, codeBlockPreferencesGroupTitle));
AddParenthesesOptions(OptionStore);
// Expression preferences
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpression, s_preferSimplifiedConditionalExpression, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSwitchExpression, CSharpVSResources.Prefer_switch_expression, s_preferSwitchExpression, s_preferSwitchExpression, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, ServicesVSResources.Prefer_simple_default_expression, s_preferSimpleDefaultExpression, s_preferSimpleDefaultExpression, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferLocalOverAnonymousFunction, ServicesVSResources.Prefer_local_function_over_anonymous_function, s_preferLocalFunctionOverAnonymousFunction, s_preferLocalFunctionOverAnonymousFunction, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, CSharpVSResources.Prefer_implicit_object_creation_when_type_is_apparent, s_preferImplicitObjectCreationWhenTypeIsApparent, s_preferImplicitObjectCreationWhenTypeIsApparent, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferIndexOperator, ServicesVSResources.Prefer_index_operator, s_preferIndexOperator, s_preferIndexOperator, this, optionStore, expressionPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferRangeOperator, ServicesVSResources.Prefer_range_operator, s_preferRangeOperator, s_preferRangeOperator, this, optionStore, expressionPreferencesGroupTitle));
// Pattern matching
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatching, CSharpVSResources.Prefer_pattern_matching, s_preferPatternMatching, s_preferPatternMatching, this, optionStore, patternMatchingPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck, CSharpVSResources.Prefer_pattern_matching_over_is_with_cast_check, s_preferPatternMatchingOverIsWithCastCheck, s_preferPatternMatchingOverIsWithCastCheck, this, optionStore, patternMatchingPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, CSharpVSResources.Prefer_pattern_matching_over_as_with_null_check, s_preferPatternMatchingOverAsWithNullCheck, s_preferPatternMatchingOverAsWithNullCheck, this, optionStore, patternMatchingPreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferNotPattern, CSharpVSResources.Prefer_pattern_matching_over_mixed_type_check, s_preferPatternMatchingOverMixedTypeCheck, s_preferPatternMatchingOverMixedTypeCheck, this, optionStore, patternMatchingPreferencesGroupTitle));
AddExpressionBodyOptions(optionStore, expressionPreferencesGroupTitle);
AddUnusedValueOptions(optionStore, expressionPreferencesGroupTitle);
// Variable preferences
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferInlinedVariableDeclaration, ServicesVSResources.Prefer_inlined_variable_declaration, s_preferInlinedVariableDeclaration, s_preferInlinedVariableDeclaration, this, optionStore, variablePreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferDeconstructedVariableDeclaration, ServicesVSResources.Prefer_deconstructed_variable_declaration, s_preferDeconstructedVariableDeclaration, s_preferDeconstructedVariableDeclaration, this, optionStore, variablePreferencesGroupTitle));
// Null preferences.
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferThrowExpression, CSharpVSResources.Prefer_throw_expression, s_preferThrowExpression, s_preferThrowExpression, this, optionStore, nullCheckingGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferConditionalDelegateCall, CSharpVSResources.Prefer_conditional_delegate_call, s_preferConditionalDelegateCall, s_preferConditionalDelegateCall, this, optionStore, nullCheckingGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, this, optionStore, nullCheckingGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, this, optionStore, nullCheckingGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, CSharpVSResources.Prefer_is_null_for_reference_equality_checks, s_preferIsNullOverReferenceEquals, s_preferIsNullOverReferenceEquals, this, optionStore, nullCheckingGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, CSharpVSResources.Prefer_null_check_over_type_check, s_preferNullcheckOverTypeCheck, s_preferNullcheckOverTypeCheck, this, optionStore, nullCheckingGroupTitle));
// Using directive preferences.
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<AddImportPlacement>(
CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CSharpVSResources.Preferred_using_directive_placement,
new[] { AddImportPlacement.InsideNamespace, AddImportPlacement.OutsideNamespace },
s_usingDirectivePlacement, this, optionStore, usingsGroupTitle, usingDirectivePlacementPreferences));
// Modifier preferences.
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, this, optionStore, modifierGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferStaticLocalFunction, ServicesVSResources.Prefer_static_local_functions, s_preferStaticLocalFunction, s_preferStaticLocalFunction, this, optionStore, modifierGroupTitle));
// Parameter preferences
AddParameterOptions(optionStore, parameterPreferencesGroupTitle);
// New line preferences.
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowMultipleBlankLines, ServicesVSResources.Allow_multiple_blank_lines, s_allow_multiple_blank_lines_true, s_allow_multiple_blank_lines_false, this, optionStore, newLinePreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CSharpVSResources.Allow_embedded_statements_on_same_line, s_allow_embedded_statements_on_same_line_true, s_allow_embedded_statements_on_same_line_false, this, optionStore, newLinePreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CSharpVSResources.Allow_blank_lines_between_consecutive_braces, s_allow_blank_line_between_consecutive_braces_true, s_allow_blank_line_between_consecutive_braces_false, this, optionStore, newLinePreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, ServicesVSResources.Allow_statement_immediately_after_block, s_allow_statement_immediately_after_block_true, s_allow_statement_immediately_after_block_false, this, optionStore, newLinePreferencesGroupTitle));
CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CSharpVSResources.Allow_bank_line_after_colon_in_constructor_initializer, s_allow_bank_line_after_colon_in_constructor_initializer_true, s_allow_bank_line_after_colon_in_constructor_initializer_false, this, optionStore, newLinePreferencesGroupTitle));
}
private void AddParenthesesOptions(OptionStore optionStore)
{
AddParenthesesOption(
LanguageNames.CSharp, optionStore, CodeStyleOptions2.ArithmeticBinaryParentheses,
CSharpVSResources.In_arithmetic_binary_operators,
new[] { s_arithmeticBinaryAlwaysForClarity, s_arithmeticBinaryNeverIfUnnecessary },
defaultAddForClarity: true);
AddParenthesesOption(
LanguageNames.CSharp, optionStore, CodeStyleOptions2.OtherBinaryParentheses,
CSharpVSResources.In_other_binary_operators,
new[] { s_otherBinaryAlwaysForClarity, s_otherBinaryNeverIfUnnecessary },
defaultAddForClarity: true);
AddParenthesesOption(
LanguageNames.CSharp, optionStore, CodeStyleOptions2.RelationalBinaryParentheses,
CSharpVSResources.In_relational_binary_operators,
new[] { s_relationalBinaryAlwaysForClarity, s_relationalBinaryNeverIfUnnecessary },
defaultAddForClarity: true);
AddParenthesesOption(
LanguageNames.CSharp, optionStore, CodeStyleOptions2.OtherParentheses,
ServicesVSResources.In_other_operators,
new[] { s_otherParenthesesAlwaysForClarity, s_otherParenthesesNeverIfUnnecessary },
defaultAddForClarity: false);
}
private void AddBracesOptions(OptionStore optionStore, string bracesPreferenceGroupTitle)
{
var bracesPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(ServicesVSResources.Yes, isChecked: false),
new CodeStylePreference(ServicesVSResources.No, isChecked: false),
new CodeStylePreference(CSharpVSResources.When_on_multiple_lines, isChecked: false),
};
var enumValues = new[] { PreferBracesPreference.Always, PreferBracesPreference.None, PreferBracesPreference.WhenMultiline };
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<PreferBracesPreference>(
CSharpCodeStyleOptions.PreferBraces,
ServicesVSResources.Prefer_braces,
enumValues,
new[] { s_preferBraces, s_doNotPreferBraces, s_preferBracesWhenMultiline },
this, optionStore, bracesPreferenceGroupTitle, bracesPreferences));
}
private void AddNamespaceDeclarationsOptions(OptionStore optionStore, string group)
{
var preferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Block_scoped, isChecked: false),
new CodeStylePreference(CSharpVSResources.File_scoped, isChecked: false),
};
var enumValues = new[] { NamespaceDeclarationPreference.BlockScoped, NamespaceDeclarationPreference.FileScoped };
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<NamespaceDeclarationPreference>(
CSharpCodeStyleOptions.NamespaceDeclarations,
ServicesVSResources.Namespace_declarations,
enumValues,
new[] { s_preferBlockNamespace, s_preferFileScopedNamespace },
this, optionStore, group, preferences));
}
private void AddExpressionBodyOptions(OptionStore optionStore, string expressionPreferencesGroupTitle)
{
var expressionBodyPreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Never, isChecked: false),
new CodeStylePreference(CSharpVSResources.When_possible, isChecked: false),
new CodeStylePreference(CSharpVSResources.When_on_single_line, isChecked: false),
};
var enumValues = new[] { ExpressionBodyPreference.Never, ExpressionBodyPreference.WhenPossible, ExpressionBodyPreference.WhenOnSingleLine };
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedMethods,
ServicesVSResources.Use_expression_body_for_methods,
enumValues,
new[] { s_preferBlockBodyForMethods, s_preferExpressionBodyForMethods, s_preferExpressionBodyForMethods },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedConstructors,
ServicesVSResources.Use_expression_body_for_constructors,
enumValues,
new[] { s_preferBlockBodyForConstructors, s_preferExpressionBodyForConstructors, s_preferExpressionBodyForConstructors },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedOperators,
ServicesVSResources.Use_expression_body_for_operators,
enumValues,
new[] { s_preferBlockBodyForOperators, s_preferExpressionBodyForOperators, s_preferExpressionBodyForOperators },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedProperties,
ServicesVSResources.Use_expression_body_for_properties,
enumValues,
new[] { s_preferBlockBodyForProperties, s_preferExpressionBodyForProperties, s_preferExpressionBodyForProperties },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedIndexers,
ServicesVSResources.Use_expression_body_for_indexers,
enumValues,
new[] { s_preferBlockBodyForIndexers, s_preferExpressionBodyForIndexers, s_preferExpressionBodyForIndexers },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedAccessors,
ServicesVSResources.Use_expression_body_for_accessors,
enumValues,
new[] { s_preferBlockBodyForAccessors, s_preferExpressionBodyForAccessors, s_preferExpressionBodyForAccessors },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedLambdas,
ServicesVSResources.Use_expression_body_for_lambdas,
enumValues,
new[] { s_preferBlockBodyForLambdas, s_preferExpressionBodyForLambdas, s_preferExpressionBodyForLambdas },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>(
CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions,
ServicesVSResources.Use_expression_body_for_local_functions,
enumValues,
new[] { s_preferBlockBodyForLocalFunctions, s_preferExpressionBodyForLocalFunctions, s_preferExpressionBodyForLocalFunctions },
this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences));
}
private void AddUnusedValueOptions(OptionStore optionStore, string expressionPreferencesGroupTitle)
{
var unusedValuePreferences = new List<CodeStylePreference>
{
new CodeStylePreference(CSharpVSResources.Unused_local, isChecked: false),
new CodeStylePreference(CSharpVSResources.Discard, isChecked: true),
};
var enumValues = new[]
{
UnusedValuePreference.UnusedLocalVariable,
UnusedValuePreference.DiscardVariable
};
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<UnusedValuePreference>(
CSharpCodeStyleOptions.UnusedValueAssignment,
ServicesVSResources.Avoid_unused_value_assignments,
enumValues,
new[] { s_avoidUnusedValueAssignmentUnusedLocal, s_avoidUnusedValueAssignmentDiscard },
this,
optionStore,
expressionPreferencesGroupTitle,
unusedValuePreferences));
CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<UnusedValuePreference>(
CSharpCodeStyleOptions.UnusedValueExpressionStatement,
ServicesVSResources.Avoid_expression_statements_that_implicitly_ignore_value,
enumValues,
new[] { s_avoidUnusedValueExpressionStatementUnusedLocal, s_avoidUnusedValueExpressionStatementDiscard },
this,
optionStore,
expressionPreferencesGroupTitle,
unusedValuePreferences));
}
private void AddParameterOptions(OptionStore optionStore, string parameterPreferencesGroupTitle)
{
var examples = new[]
{
s_avoidUnusedParametersNonPublicMethods,
s_avoidUnusedParametersAllMethods
};
AddUnusedParameterOption(LanguageNames.CSharp, optionStore, parameterPreferencesGroupTitle, examples);
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpUpdateProjectToAllowUnsafe.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpUpdateProjectToAllowUnsafe : AbstractUpdateProjectTest
{
public CSharpUpdateProjectToAllowUnsafe(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
private void InvokeFix()
{
VisualStudio.Editor.SetText(@"
unsafe class C
{
}");
VisualStudio.Editor.Activate();
VisualStudio.Editor.PlaceCaret("C");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Allow unsafe code in this project", applyFix: true);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/44301"), Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void CPSProject_GeneralPropertyGroupUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.CSharpNetStandardClassLibrary, LanguageNames.CSharp);
VisualStudio.SolutionExplorer.RestoreNuGetPackages(project);
InvokeFix();
VerifyPropertyOutsideConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void LegacyProject_AllConfigurationsUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.ClassLibrary, LanguageNames.CSharp);
InvokeFix();
VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
[WorkItem(23342, "https://github.com/dotnet/roslyn/issues/23342")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void LegacyProject_MultiplePlatforms_AllConfigurationsUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddCustomProject(project, ".csproj", $@"<?xml version=""1.0"" encoding=""utf-8""?>
<Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" />
<PropertyGroup>
<Configuration Condition=""'$(Configuration)' == ''"">Debug</Configuration>
<Platform Condition=""'$(Platform)' == ''"">x64</Platform>
<ProjectGuid>{{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>{ProjectName}</RootNamespace>
<AssemblyName>{ProjectName}</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x86'"">
<OutputPath>bin\x86\Debug\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x86'"">
<OutputPath>bin\x86\Release\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x64'"">
<OutputPath>bin\x64\Debug\</OutputPath>
<PlatformTarget>x64</PlatformTarget>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x64'"">
<OutputPath>bin\x64\Release\</OutputPath>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
</ItemGroup>
<Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
</Project>");
VisualStudio.SolutionExplorer.AddFile(project, "C.cs", open: true);
InvokeFix();
VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpUpdateProjectToAllowUnsafe : AbstractUpdateProjectTest
{
public CSharpUpdateProjectToAllowUnsafe(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
private void InvokeFix()
{
VisualStudio.Editor.SetText(@"
unsafe class C
{
}");
VisualStudio.Editor.Activate();
VisualStudio.Editor.PlaceCaret("C");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Allow unsafe code in this project", applyFix: true);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/44301"), Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void CPSProject_GeneralPropertyGroupUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.CSharpNetStandardClassLibrary, LanguageNames.CSharp);
VisualStudio.SolutionExplorer.RestoreNuGetPackages(project);
InvokeFix();
VerifyPropertyOutsideConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void LegacyProject_AllConfigurationsUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.ClassLibrary, LanguageNames.CSharp);
InvokeFix();
VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
[WorkItem(23342, "https://github.com/dotnet/roslyn/issues/23342")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpdateProjectToAllowUnsafe)]
public void LegacyProject_MultiplePlatforms_AllConfigurationsUpdated()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.CreateSolution(SolutionName);
VisualStudio.SolutionExplorer.AddCustomProject(project, ".csproj", $@"<?xml version=""1.0"" encoding=""utf-8""?>
<Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" />
<PropertyGroup>
<Configuration Condition=""'$(Configuration)' == ''"">Debug</Configuration>
<Platform Condition=""'$(Platform)' == ''"">x64</Platform>
<ProjectGuid>{{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>{ProjectName}</RootNamespace>
<AssemblyName>{ProjectName}</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x86'"">
<OutputPath>bin\x86\Debug\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x86'"">
<OutputPath>bin\x86\Release\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x64'"">
<OutputPath>bin\x64\Debug\</OutputPath>
<PlatformTarget>x64</PlatformTarget>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x64'"">
<OutputPath>bin\x64\Release\</OutputPath>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
</ItemGroup>
<Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
</Project>");
VisualStudio.SolutionExplorer.AddFile(project, "C.cs", open: true);
InvokeFix();
VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "AllowUnsafeBlocks", "true");
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Scripting/CSharp/PublicAPI.Unshipped.txt | -1 |
||
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Analyzers/VisualBasic/Analyzers/UseObjectInitializer/VisualBasicUseObjectInitializerDiagnosticAnalyzer.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.Diagnostics
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.UseObjectInitializer
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend Class VisualBasicUseObjectInitializerDiagnosticAnalyzer
Inherits AbstractUseObjectInitializerDiagnosticAnalyzer(Of
SyntaxKind,
ExpressionSyntax,
StatementSyntax,
ObjectCreationExpressionSyntax,
MemberAccessExpressionSyntax,
AssignmentStatementSyntax,
VariableDeclaratorSyntax)
Protected Overrides ReadOnly Property FadeOutOperatorToken As Boolean
Get
Return False
End Get
End Property
Protected Overrides Function AreObjectInitializersSupported(compilation As Compilation) As Boolean
'Object Initializers are supported in all the versions of Visual Basic we support
Return True
End Function
Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts
Return VisualBasicSyntaxFacts.Instance
End Function
Protected Overrides Function IsValidContainingStatement(node As StatementSyntax) As Boolean
Return True
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.UseObjectInitializer
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend Class VisualBasicUseObjectInitializerDiagnosticAnalyzer
Inherits AbstractUseObjectInitializerDiagnosticAnalyzer(Of
SyntaxKind,
ExpressionSyntax,
StatementSyntax,
ObjectCreationExpressionSyntax,
MemberAccessExpressionSyntax,
AssignmentStatementSyntax,
VariableDeclaratorSyntax)
Protected Overrides ReadOnly Property FadeOutOperatorToken As Boolean
Get
Return False
End Get
End Property
Protected Overrides Function AreObjectInitializersSupported(compilation As Compilation) As Boolean
'Object Initializers are supported in all the versions of Visual Basic we support
Return True
End Function
Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts
Return VisualBasicSyntaxFacts.Instance
End Function
Protected Overrides Function IsValidContainingStatement(node As StatementSyntax) As Boolean
Return True
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/IsExternalInit.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Reserved to be used by the compiler for tracking metadata.
/// This class should not be used by developers in source code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit
{
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
namespace System.Runtime.CompilerServices
{
/// <summary>
/// Reserved to be used by the compiler for tracking metadata.
/// This class should not be used by developers in source code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit
{
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal abstract class SourceConstructorSymbolBase : SourceMemberMethodSymbol
{
protected ImmutableArray<ParameterSymbol> _lazyParameters;
private TypeWithAnnotations _lazyReturnType;
private bool _lazyIsVararg;
protected SourceConstructorSymbolBase(
SourceMemberContainerTypeSymbol containingType,
Location location,
CSharpSyntaxNode syntax,
bool isIterator)
: base(containingType, syntax.GetReference(), ImmutableArray.Create(location), isIterator)
{
Debug.Assert(
syntax.IsKind(SyntaxKind.ConstructorDeclaration) ||
syntax.IsKind(SyntaxKind.RecordDeclaration) ||
syntax.IsKind(SyntaxKind.RecordStructDeclaration));
}
protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics)
{
var syntax = (CSharpSyntaxNode)syntaxReferenceOpt.GetSyntax();
var binderFactory = this.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree);
ParameterListSyntax parameterList = GetParameterList();
// NOTE: if we asked for the binder for the body of the constructor, we'd risk a stack overflow because
// we might still be constructing the member list of the containing type. However, getting the binder
// for the parameters should be safe.
var bodyBinder = binderFactory.GetBinder(parameterList, syntax, this).WithContainingMemberOrLambda(this);
// Constraint checking for parameter and return types must be delayed until
// the method has been added to the containing type member list since
// evaluating the constraints may depend on accessing this method from
// the container (comparing this method to others to find overrides for
// instance). Constraints are checked in AfterAddingTypeMembersChecks.
var signatureBinder = bodyBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);
SyntaxToken arglistToken;
_lazyParameters = ParameterHelpers.MakeParameters(
signatureBinder, this, parameterList, out arglistToken,
allowRefOrOut: AllowRefOrOut,
allowThis: false,
addRefReadOnlyModifier: false,
diagnostics: diagnostics);
_lazyIsVararg = (arglistToken.Kind() == SyntaxKind.ArgListKeyword);
_lazyReturnType = TypeWithAnnotations.Create(bodyBinder.GetSpecialType(SpecialType.System_Void, diagnostics, syntax));
var location = this.Locations[0];
// Don't report ERR_StaticConstParam if the ctor symbol name doesn't match the containing type name.
// This avoids extra unnecessary errors.
// There will already be a diagnostic saying Method must have a return type.
if (MethodKind == MethodKind.StaticConstructor && (_lazyParameters.Length != 0) &&
ContainingType.Name == ((ConstructorDeclarationSyntax)this.SyntaxNode).Identifier.ValueText)
{
diagnostics.Add(ErrorCode.ERR_StaticConstParam, location, this);
}
this.CheckEffectiveAccessibility(_lazyReturnType, _lazyParameters, diagnostics);
if (_lazyIsVararg && (IsGenericMethod || ContainingType.IsGenericType || _lazyParameters.Length > 0 && _lazyParameters[_lazyParameters.Length - 1].IsParams))
{
diagnostics.Add(ErrorCode.ERR_BadVarargs, location);
}
}
#nullable enable
protected abstract ParameterListSyntax GetParameterList();
protected abstract bool AllowRefOrOut { get; }
#nullable disable
internal sealed override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics)
{
base.AfterAddingTypeMembersChecks(conversions, diagnostics);
var compilation = DeclaringCompilation;
ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true);
ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true);
ParameterHelpers.EnsureNullableAttributeExists(compilation, this, Parameters, diagnostics, modifyCompilation: true);
foreach (var parameter in this.Parameters)
{
parameter.Type.CheckAllConstraints(compilation, conversions, parameter.Locations[0], diagnostics);
}
}
public sealed override bool IsVararg
{
get
{
LazyMethodChecks();
return _lazyIsVararg;
}
}
public sealed override bool IsImplicitlyDeclared
{
get
{
return base.IsImplicitlyDeclared;
}
}
internal sealed override int ParameterCount
{
get
{
if (!_lazyParameters.IsDefault)
{
return _lazyParameters.Length;
}
return GetParameterList().ParameterCount;
}
}
public sealed override ImmutableArray<ParameterSymbol> Parameters
{
get
{
LazyMethodChecks();
return _lazyParameters;
}
}
public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return ImmutableArray<TypeParameterSymbol>.Empty; }
}
public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes()
=> ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty;
public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds()
=> ImmutableArray<TypeParameterConstraintKind>.Empty;
public override RefKind RefKind
{
get { return RefKind.None; }
}
public sealed override TypeWithAnnotations ReturnTypeWithAnnotations
{
get
{
LazyMethodChecks();
return _lazyReturnType;
}
}
public sealed override string Name
{
get { return this.IsStatic ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName; }
}
internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations()
{
// constructors can't have return type attributes
return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>));
}
protected sealed override IAttributeTargetSymbol AttributeOwner
{
get
{
return base.AttributeOwner;
}
}
internal sealed override bool GenerateDebugInfo
{
get { return true; }
}
internal sealed override int CalculateLocalSyntaxOffset(int position, SyntaxTree tree)
{
Debug.Assert(position >= 0 && tree != null);
TextSpan span;
// local/lambda/closure defined within the body of the constructor:
var ctorSyntax = (CSharpSyntaxNode)syntaxReferenceOpt.GetSyntax();
if (tree == ctorSyntax.SyntaxTree)
{
if (IsWithinExpressionOrBlockBody(position, out int offset))
{
return offset;
}
// closure in ctor initializer lifting its parameter(s) spans the constructor declaration:
if (position == ctorSyntax.SpanStart)
{
// Use a constant that is distinct from any other syntax offset.
// -1 works since a field initializer and a constructor declaration header can't squeeze into a single character.
return -1;
}
}
// lambdas in ctor initializer:
int ctorInitializerLength;
var ctorInitializer = GetInitializer();
if (tree == ctorInitializer?.SyntaxTree)
{
span = ctorInitializer.Span;
ctorInitializerLength = span.Length;
if (span.Contains(position))
{
return -ctorInitializerLength + (position - span.Start);
}
}
else
{
ctorInitializerLength = 0;
}
// lambdas in field/property initializers:
int syntaxOffset;
var containingType = (SourceNamedTypeSymbol)this.ContainingType;
if (containingType.TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, this.IsStatic, ctorInitializerLength, out syntaxOffset))
{
return syntaxOffset;
}
// we haven't found the constructor part that declares the variable:
throw ExceptionUtilities.Unreachable;
}
internal abstract override bool IsNullableAnalysisEnabled();
protected abstract CSharpSyntaxNode GetInitializer();
protected abstract bool IsWithinExpressionOrBlockBody(int position, out int offset);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal abstract class SourceConstructorSymbolBase : SourceMemberMethodSymbol
{
protected ImmutableArray<ParameterSymbol> _lazyParameters;
private TypeWithAnnotations _lazyReturnType;
private bool _lazyIsVararg;
protected SourceConstructorSymbolBase(
SourceMemberContainerTypeSymbol containingType,
Location location,
CSharpSyntaxNode syntax,
bool isIterator)
: base(containingType, syntax.GetReference(), ImmutableArray.Create(location), isIterator)
{
Debug.Assert(
syntax.IsKind(SyntaxKind.ConstructorDeclaration) ||
syntax.IsKind(SyntaxKind.RecordDeclaration) ||
syntax.IsKind(SyntaxKind.RecordStructDeclaration));
}
protected sealed override void MethodChecks(BindingDiagnosticBag diagnostics)
{
var syntax = (CSharpSyntaxNode)syntaxReferenceOpt.GetSyntax();
var binderFactory = this.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree);
ParameterListSyntax parameterList = GetParameterList();
// NOTE: if we asked for the binder for the body of the constructor, we'd risk a stack overflow because
// we might still be constructing the member list of the containing type. However, getting the binder
// for the parameters should be safe.
var bodyBinder = binderFactory.GetBinder(parameterList, syntax, this).WithContainingMemberOrLambda(this);
// Constraint checking for parameter and return types must be delayed until
// the method has been added to the containing type member list since
// evaluating the constraints may depend on accessing this method from
// the container (comparing this method to others to find overrides for
// instance). Constraints are checked in AfterAddingTypeMembersChecks.
var signatureBinder = bodyBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);
SyntaxToken arglistToken;
_lazyParameters = ParameterHelpers.MakeParameters(
signatureBinder, this, parameterList, out arglistToken,
allowRefOrOut: AllowRefOrOut,
allowThis: false,
addRefReadOnlyModifier: false,
diagnostics: diagnostics);
_lazyIsVararg = (arglistToken.Kind() == SyntaxKind.ArgListKeyword);
_lazyReturnType = TypeWithAnnotations.Create(bodyBinder.GetSpecialType(SpecialType.System_Void, diagnostics, syntax));
var location = this.Locations[0];
// Don't report ERR_StaticConstParam if the ctor symbol name doesn't match the containing type name.
// This avoids extra unnecessary errors.
// There will already be a diagnostic saying Method must have a return type.
if (MethodKind == MethodKind.StaticConstructor && (_lazyParameters.Length != 0) &&
ContainingType.Name == ((ConstructorDeclarationSyntax)this.SyntaxNode).Identifier.ValueText)
{
diagnostics.Add(ErrorCode.ERR_StaticConstParam, location, this);
}
this.CheckEffectiveAccessibility(_lazyReturnType, _lazyParameters, diagnostics);
if (_lazyIsVararg && (IsGenericMethod || ContainingType.IsGenericType || _lazyParameters.Length > 0 && _lazyParameters[_lazyParameters.Length - 1].IsParams))
{
diagnostics.Add(ErrorCode.ERR_BadVarargs, location);
}
}
#nullable enable
protected abstract ParameterListSyntax GetParameterList();
protected abstract bool AllowRefOrOut { get; }
#nullable disable
internal sealed override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics)
{
base.AfterAddingTypeMembersChecks(conversions, diagnostics);
var compilation = DeclaringCompilation;
ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true);
ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true);
ParameterHelpers.EnsureNullableAttributeExists(compilation, this, Parameters, diagnostics, modifyCompilation: true);
foreach (var parameter in this.Parameters)
{
parameter.Type.CheckAllConstraints(compilation, conversions, parameter.Locations[0], diagnostics);
}
}
public sealed override bool IsVararg
{
get
{
LazyMethodChecks();
return _lazyIsVararg;
}
}
public sealed override bool IsImplicitlyDeclared
{
get
{
return base.IsImplicitlyDeclared;
}
}
internal sealed override int ParameterCount
{
get
{
if (!_lazyParameters.IsDefault)
{
return _lazyParameters.Length;
}
return GetParameterList().ParameterCount;
}
}
public sealed override ImmutableArray<ParameterSymbol> Parameters
{
get
{
LazyMethodChecks();
return _lazyParameters;
}
}
public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return ImmutableArray<TypeParameterSymbol>.Empty; }
}
public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes()
=> ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty;
public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds()
=> ImmutableArray<TypeParameterConstraintKind>.Empty;
public override RefKind RefKind
{
get { return RefKind.None; }
}
public sealed override TypeWithAnnotations ReturnTypeWithAnnotations
{
get
{
LazyMethodChecks();
return _lazyReturnType;
}
}
public sealed override string Name
{
get { return this.IsStatic ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName; }
}
internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations()
{
// constructors can't have return type attributes
return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>));
}
protected sealed override IAttributeTargetSymbol AttributeOwner
{
get
{
return base.AttributeOwner;
}
}
internal sealed override bool GenerateDebugInfo
{
get { return true; }
}
internal sealed override int CalculateLocalSyntaxOffset(int position, SyntaxTree tree)
{
Debug.Assert(position >= 0 && tree != null);
TextSpan span;
// local/lambda/closure defined within the body of the constructor:
var ctorSyntax = (CSharpSyntaxNode)syntaxReferenceOpt.GetSyntax();
if (tree == ctorSyntax.SyntaxTree)
{
if (IsWithinExpressionOrBlockBody(position, out int offset))
{
return offset;
}
// closure in ctor initializer lifting its parameter(s) spans the constructor declaration:
if (position == ctorSyntax.SpanStart)
{
// Use a constant that is distinct from any other syntax offset.
// -1 works since a field initializer and a constructor declaration header can't squeeze into a single character.
return -1;
}
}
// lambdas in ctor initializer:
int ctorInitializerLength;
var ctorInitializer = GetInitializer();
if (tree == ctorInitializer?.SyntaxTree)
{
span = ctorInitializer.Span;
ctorInitializerLength = span.Length;
if (span.Contains(position))
{
return -ctorInitializerLength + (position - span.Start);
}
}
else
{
ctorInitializerLength = 0;
}
// lambdas in field/property initializers:
int syntaxOffset;
var containingType = (SourceNamedTypeSymbol)this.ContainingType;
if (containingType.TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, this.IsStatic, ctorInitializerLength, out syntaxOffset))
{
return syntaxOffset;
}
// we haven't found the constructor part that declares the variable:
throw ExceptionUtilities.Unreachable;
}
internal abstract override bool IsNullableAnalysisEnabled();
protected abstract CSharpSyntaxNode GetInitializer();
protected abstract bool IsWithinExpressionOrBlockBody(int position, out int offset);
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Analyzers/Core/Analyzers/QualifyMemberAccess/AbstractQualifyMemberAccessDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
#if CODE_STYLE
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#endif
namespace Microsoft.CodeAnalysis.QualifyMemberAccess
{
internal abstract class AbstractQualifyMemberAccessDiagnosticAnalyzer<
TLanguageKindEnum,
TExpressionSyntax,
TSimpleNameSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TLanguageKindEnum : struct
where TExpressionSyntax : SyntaxNode
where TSimpleNameSyntax : TExpressionSyntax
{
protected AbstractQualifyMemberAccessDiagnosticAnalyzer()
: base(IDEDiagnosticIds.AddQualificationDiagnosticId,
EnforceOnBuildValues.AddQualification,
options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOptions2.QualifyPropertyAccess, CodeStyleOptions2.QualifyMethodAccess, CodeStyleOptions2.QualifyEventAccess),
new LocalizableResourceString(nameof(AnalyzersResources.Member_access_should_be_qualified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Add_this_or_Me_qualification), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
public override bool OpenFileOnly(OptionSet options)
{
var qualifyFieldAccessOption = options.GetOption(CodeStyleOptions2.QualifyFieldAccess, GetLanguageName()).Notification;
var qualifyPropertyAccessOption = options.GetOption(CodeStyleOptions2.QualifyPropertyAccess, GetLanguageName()).Notification;
var qualifyMethodAccessOption = options.GetOption(CodeStyleOptions2.QualifyMethodAccess, GetLanguageName()).Notification;
var qualifyEventAccessOption = options.GetOption(CodeStyleOptions2.QualifyEventAccess, GetLanguageName()).Notification;
return !(qualifyFieldAccessOption == NotificationOption2.Warning || qualifyFieldAccessOption == NotificationOption2.Error ||
qualifyPropertyAccessOption == NotificationOption2.Warning || qualifyPropertyAccessOption == NotificationOption2.Error ||
qualifyMethodAccessOption == NotificationOption2.Warning || qualifyMethodAccessOption == NotificationOption2.Error ||
qualifyEventAccessOption == NotificationOption2.Warning || qualifyEventAccessOption == NotificationOption2.Error);
}
protected abstract string GetLanguageName();
/// <summary>
/// Reports on whether the specified member is suitable for qualification. Some member
/// access expressions cannot be qualified; for instance if they begin with <c>base.</c>,
/// <c>MyBase.</c>, or <c>MyClass.</c>.
/// </summary>
/// <returns>True if the member access can be qualified; otherwise, False.</returns>
protected abstract bool CanMemberAccessBeQualified(ISymbol containingSymbol, SyntaxNode node);
protected abstract bool IsAlreadyQualifiedMemberAccess(TExpressionSyntax node);
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference, OperationKind.PropertyReference, OperationKind.MethodReference, OperationKind.Invocation);
protected abstract Location GetLocation(IOperation operation);
public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
private void AnalyzeOperation(OperationAnalysisContext context)
{
if (context.ContainingSymbol.IsStatic)
{
return;
}
switch (context.Operation)
{
case IMemberReferenceOperation memberReferenceOperation:
AnalyzeOperation(context, memberReferenceOperation, memberReferenceOperation.Instance);
break;
case IInvocationOperation invocationOperation:
AnalyzeOperation(context, invocationOperation, invocationOperation.Instance);
break;
default:
throw ExceptionUtilities.UnexpectedValue(context.Operation);
}
}
private void AnalyzeOperation(OperationAnalysisContext context, IOperation operation, IOperation? instanceOperation)
{
// this is a static reference so we don't care if it's qualified
if (instanceOperation == null)
return;
// if we're not referencing `this.` or `Me.` (e.g., a parameter, local, etc.)
if (instanceOperation.Kind != OperationKind.InstanceReference)
return;
// We shouldn't qualify if it is inside a property pattern
if (context.Operation.Parent?.Kind == OperationKind.PropertySubpattern)
return;
// Initializer lists are IInvocationOperation which if passed to GetApplicableOptionFromSymbolKind
// will incorrectly fetch the options for method call.
// We still want to handle InstanceReferenceKind.ContainingTypeInstance
if ((instanceOperation as IInstanceReferenceOperation)?.ReferenceKind == InstanceReferenceKind.ImplicitReceiver)
return;
// If we can't be qualified (e.g., because we're already qualified with `base.`), we're done.
if (!CanMemberAccessBeQualified(context.ContainingSymbol, instanceOperation.Syntax))
return;
// if we can't find a member then we can't do anything. Also, we shouldn't qualify
// accesses to static members.
if (IsStaticMemberOrIsLocalFunction(operation))
return;
if (instanceOperation.Syntax is not TSimpleNameSyntax simpleName)
return;
var applicableOption = QualifyMembersHelpers.GetApplicableOptionFromSymbolKind(operation);
var optionValue = context.GetOption(applicableOption, context.Operation.Syntax.Language);
var shouldOptionBePresent = optionValue.Value;
var severity = optionValue.Notification.Severity;
if (!shouldOptionBePresent || severity == ReportDiagnostic.Suppress)
{
return;
}
if (!IsAlreadyQualifiedMemberAccess(simpleName))
{
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
GetLocation(operation),
severity,
additionalLocations: null,
properties: null));
}
}
private static bool IsStaticMemberOrIsLocalFunction(IOperation operation)
{
return operation switch
{
IMemberReferenceOperation memberReferenceOperation => IsStaticMemberOrIsLocalFunctionHelper(memberReferenceOperation.Member),
IInvocationOperation invocationOperation => IsStaticMemberOrIsLocalFunctionHelper(invocationOperation.TargetMethod),
_ => throw ExceptionUtilities.UnexpectedValue(operation),
};
static bool IsStaticMemberOrIsLocalFunctionHelper(ISymbol symbol)
{
return symbol == null || symbol.IsStatic || symbol is IMethodSymbol { MethodKind: MethodKind.LocalFunction };
}
}
}
internal static class QualifyMembersHelpers
{
public static PerLanguageOption2<CodeStyleOption2<bool>> GetApplicableOptionFromSymbolKind(SymbolKind symbolKind)
=> symbolKind switch
{
SymbolKind.Field => CodeStyleOptions2.QualifyFieldAccess,
SymbolKind.Property => CodeStyleOptions2.QualifyPropertyAccess,
SymbolKind.Method => CodeStyleOptions2.QualifyMethodAccess,
SymbolKind.Event => CodeStyleOptions2.QualifyEventAccess,
_ => throw ExceptionUtilities.UnexpectedValue(symbolKind),
};
internal static PerLanguageOption2<CodeStyleOption2<bool>> GetApplicableOptionFromSymbolKind(IOperation operation)
=> operation switch
{
IMemberReferenceOperation memberReferenceOperation => GetApplicableOptionFromSymbolKind(memberReferenceOperation.Member.Kind),
IInvocationOperation invocationOperation => GetApplicableOptionFromSymbolKind(invocationOperation.TargetMethod.Kind),
_ => throw ExceptionUtilities.UnexpectedValue(operation),
};
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
#if CODE_STYLE
using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions;
#endif
namespace Microsoft.CodeAnalysis.QualifyMemberAccess
{
internal abstract class AbstractQualifyMemberAccessDiagnosticAnalyzer<
TLanguageKindEnum,
TExpressionSyntax,
TSimpleNameSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TLanguageKindEnum : struct
where TExpressionSyntax : SyntaxNode
where TSimpleNameSyntax : TExpressionSyntax
{
protected AbstractQualifyMemberAccessDiagnosticAnalyzer()
: base(IDEDiagnosticIds.AddQualificationDiagnosticId,
EnforceOnBuildValues.AddQualification,
options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOptions2.QualifyPropertyAccess, CodeStyleOptions2.QualifyMethodAccess, CodeStyleOptions2.QualifyEventAccess),
new LocalizableResourceString(nameof(AnalyzersResources.Member_access_should_be_qualified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Add_this_or_Me_qualification), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
public override bool OpenFileOnly(OptionSet options)
{
var qualifyFieldAccessOption = options.GetOption(CodeStyleOptions2.QualifyFieldAccess, GetLanguageName()).Notification;
var qualifyPropertyAccessOption = options.GetOption(CodeStyleOptions2.QualifyPropertyAccess, GetLanguageName()).Notification;
var qualifyMethodAccessOption = options.GetOption(CodeStyleOptions2.QualifyMethodAccess, GetLanguageName()).Notification;
var qualifyEventAccessOption = options.GetOption(CodeStyleOptions2.QualifyEventAccess, GetLanguageName()).Notification;
return !(qualifyFieldAccessOption == NotificationOption2.Warning || qualifyFieldAccessOption == NotificationOption2.Error ||
qualifyPropertyAccessOption == NotificationOption2.Warning || qualifyPropertyAccessOption == NotificationOption2.Error ||
qualifyMethodAccessOption == NotificationOption2.Warning || qualifyMethodAccessOption == NotificationOption2.Error ||
qualifyEventAccessOption == NotificationOption2.Warning || qualifyEventAccessOption == NotificationOption2.Error);
}
protected abstract string GetLanguageName();
/// <summary>
/// Reports on whether the specified member is suitable for qualification. Some member
/// access expressions cannot be qualified; for instance if they begin with <c>base.</c>,
/// <c>MyBase.</c>, or <c>MyClass.</c>.
/// </summary>
/// <returns>True if the member access can be qualified; otherwise, False.</returns>
protected abstract bool CanMemberAccessBeQualified(ISymbol containingSymbol, SyntaxNode node);
protected abstract bool IsAlreadyQualifiedMemberAccess(TExpressionSyntax node);
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference, OperationKind.PropertyReference, OperationKind.MethodReference, OperationKind.Invocation);
protected abstract Location GetLocation(IOperation operation);
public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
private void AnalyzeOperation(OperationAnalysisContext context)
{
if (context.ContainingSymbol.IsStatic)
{
return;
}
switch (context.Operation)
{
case IMemberReferenceOperation memberReferenceOperation:
AnalyzeOperation(context, memberReferenceOperation, memberReferenceOperation.Instance);
break;
case IInvocationOperation invocationOperation:
AnalyzeOperation(context, invocationOperation, invocationOperation.Instance);
break;
default:
throw ExceptionUtilities.UnexpectedValue(context.Operation);
}
}
private void AnalyzeOperation(OperationAnalysisContext context, IOperation operation, IOperation? instanceOperation)
{
// this is a static reference so we don't care if it's qualified
if (instanceOperation == null)
return;
// if we're not referencing `this.` or `Me.` (e.g., a parameter, local, etc.)
if (instanceOperation.Kind != OperationKind.InstanceReference)
return;
// We shouldn't qualify if it is inside a property pattern
if (context.Operation.Parent?.Kind == OperationKind.PropertySubpattern)
return;
// Initializer lists are IInvocationOperation which if passed to GetApplicableOptionFromSymbolKind
// will incorrectly fetch the options for method call.
// We still want to handle InstanceReferenceKind.ContainingTypeInstance
if ((instanceOperation as IInstanceReferenceOperation)?.ReferenceKind == InstanceReferenceKind.ImplicitReceiver)
return;
// If we can't be qualified (e.g., because we're already qualified with `base.`), we're done.
if (!CanMemberAccessBeQualified(context.ContainingSymbol, instanceOperation.Syntax))
return;
// if we can't find a member then we can't do anything. Also, we shouldn't qualify
// accesses to static members.
if (IsStaticMemberOrIsLocalFunction(operation))
return;
if (instanceOperation.Syntax is not TSimpleNameSyntax simpleName)
return;
var applicableOption = QualifyMembersHelpers.GetApplicableOptionFromSymbolKind(operation);
var optionValue = context.GetOption(applicableOption, context.Operation.Syntax.Language);
var shouldOptionBePresent = optionValue.Value;
var severity = optionValue.Notification.Severity;
if (!shouldOptionBePresent || severity == ReportDiagnostic.Suppress)
{
return;
}
if (!IsAlreadyQualifiedMemberAccess(simpleName))
{
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
GetLocation(operation),
severity,
additionalLocations: null,
properties: null));
}
}
private static bool IsStaticMemberOrIsLocalFunction(IOperation operation)
{
return operation switch
{
IMemberReferenceOperation memberReferenceOperation => IsStaticMemberOrIsLocalFunctionHelper(memberReferenceOperation.Member),
IInvocationOperation invocationOperation => IsStaticMemberOrIsLocalFunctionHelper(invocationOperation.TargetMethod),
_ => throw ExceptionUtilities.UnexpectedValue(operation),
};
static bool IsStaticMemberOrIsLocalFunctionHelper(ISymbol symbol)
{
return symbol == null || symbol.IsStatic || symbol is IMethodSymbol { MethodKind: MethodKind.LocalFunction };
}
}
}
internal static class QualifyMembersHelpers
{
public static PerLanguageOption2<CodeStyleOption2<bool>> GetApplicableOptionFromSymbolKind(SymbolKind symbolKind)
=> symbolKind switch
{
SymbolKind.Field => CodeStyleOptions2.QualifyFieldAccess,
SymbolKind.Property => CodeStyleOptions2.QualifyPropertyAccess,
SymbolKind.Method => CodeStyleOptions2.QualifyMethodAccess,
SymbolKind.Event => CodeStyleOptions2.QualifyEventAccess,
_ => throw ExceptionUtilities.UnexpectedValue(symbolKind),
};
internal static PerLanguageOption2<CodeStyleOption2<bool>> GetApplicableOptionFromSymbolKind(IOperation operation)
=> operation switch
{
IMemberReferenceOperation memberReferenceOperation => GetApplicableOptionFromSymbolKind(memberReferenceOperation.Member.Kind),
IInvocationOperation invocationOperation => GetApplicableOptionFromSymbolKind(invocationOperation.TargetMethod.Kind),
_ => throw ExceptionUtilities.UnexpectedValue(operation),
};
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/VisualStudio/Core/Def/EditorConfigSettings/Analyzers/View/ColumnDefinitions/AnalyzerLocationColumnDefinition.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Host.Mef;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Utilities;
using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Analyzer;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.View.ColumnDefinitions
{
[Export(typeof(ITableColumnDefinition))]
[Name(Location)]
internal class AnalyzerLocationColumnDefinition : TableColumnDefinitionBase
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerLocationColumnDefinition()
{
}
public override string Name => Location;
public override string DisplayName => ServicesVSResources.Location;
public override bool IsFilterable => true;
public override bool IsSortable => true;
public override double MinWidth => 250;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Host.Mef;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Utilities;
using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Analyzer;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.View.ColumnDefinitions
{
[Export(typeof(ITableColumnDefinition))]
[Name(Location)]
internal class AnalyzerLocationColumnDefinition : TableColumnDefinitionBase
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public AnalyzerLocationColumnDefinition()
{
}
public override string Name => Location;
public override string DisplayName => ServicesVSResources.Location;
public override bool IsFilterable => true;
public override bool IsSortable => true;
public override double MinWidth => 250;
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.UShortTC.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp
{
using static BinaryOperatorKind;
internal static partial class ValueSetFactory
{
private struct UShortTC : INumericTC<ushort>
{
ushort INumericTC<ushort>.MinValue => ushort.MinValue;
ushort INumericTC<ushort>.MaxValue => ushort.MaxValue;
ushort INumericTC<ushort>.Zero => 0;
bool INumericTC<ushort>.Related(BinaryOperatorKind relation, ushort left, ushort right)
{
switch (relation)
{
case Equal:
return left == right;
case GreaterThanOrEqual:
return left >= right;
case GreaterThan:
return left > right;
case LessThanOrEqual:
return left <= right;
case LessThan:
return left < right;
default:
throw new ArgumentException("relation");
}
}
ushort INumericTC<ushort>.Next(ushort value)
{
Debug.Assert(value != ushort.MaxValue);
return (ushort)(value + 1);
}
ushort INumericTC<ushort>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (ushort)0 : constantValue.UInt16Value;
ConstantValue INumericTC<ushort>.ToConstantValue(ushort value) => ConstantValue.Create(value);
string INumericTC<ushort>.ToString(ushort value) => value.ToString();
ushort INumericTC<ushort>.Prev(ushort value)
{
Debug.Assert(value != ushort.MinValue);
return (ushort)(value - 1);
}
ushort INumericTC<ushort>.Random(Random random)
{
return (ushort)random.Next();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp
{
using static BinaryOperatorKind;
internal static partial class ValueSetFactory
{
private struct UShortTC : INumericTC<ushort>
{
ushort INumericTC<ushort>.MinValue => ushort.MinValue;
ushort INumericTC<ushort>.MaxValue => ushort.MaxValue;
ushort INumericTC<ushort>.Zero => 0;
bool INumericTC<ushort>.Related(BinaryOperatorKind relation, ushort left, ushort right)
{
switch (relation)
{
case Equal:
return left == right;
case GreaterThanOrEqual:
return left >= right;
case GreaterThan:
return left > right;
case LessThanOrEqual:
return left <= right;
case LessThan:
return left < right;
default:
throw new ArgumentException("relation");
}
}
ushort INumericTC<ushort>.Next(ushort value)
{
Debug.Assert(value != ushort.MaxValue);
return (ushort)(value + 1);
}
ushort INumericTC<ushort>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (ushort)0 : constantValue.UInt16Value;
ConstantValue INumericTC<ushort>.ToConstantValue(ushort value) => ConstantValue.Create(value);
string INumericTC<ushort>.ToString(ushort value) => value.ToString();
ushort INumericTC<ushort>.Prev(ushort value)
{
Debug.Assert(value != ushort.MinValue);
return (ushort)(value - 1);
}
ushort INumericTC<ushort>.Random(Random random)
{
return (ushort)random.Next();
}
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/EditorFeatures/Core/Implementation/EditAndContinue/IActiveStatementTrackingService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Host;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue
{
internal interface IActiveStatementTrackingService : IWorkspaceService
{
ValueTask StartTrackingAsync(Solution solution, IActiveStatementSpanProvider spanProvider, CancellationToken cancellationToken);
void EndTracking();
/// <summary>
/// Triggered when tracking spans have changed.
/// </summary>
event Action TrackingChanged;
/// <summary>
/// Returns location of the tracking spans in the specified document snapshot (#line target document).
/// </summary>
/// <returns>Empty array if tracking spans are not available for the document.</returns>
ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(Solution solution, DocumentId? documentId, string filePath, CancellationToken cancellationToken);
/// <summary>
/// Updates tracking spans with the latest positions of all active statements in the specified document snapshot (#line target document) and returns them.
/// </summary>
ValueTask<ImmutableArray<ActiveStatementTrackingSpan>> GetAdjustedTrackingSpansAsync(TextDocument document, ITextSnapshot snapshot, 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;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Host;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue
{
internal interface IActiveStatementTrackingService : IWorkspaceService
{
ValueTask StartTrackingAsync(Solution solution, IActiveStatementSpanProvider spanProvider, CancellationToken cancellationToken);
void EndTracking();
/// <summary>
/// Triggered when tracking spans have changed.
/// </summary>
event Action TrackingChanged;
/// <summary>
/// Returns location of the tracking spans in the specified document snapshot (#line target document).
/// </summary>
/// <returns>Empty array if tracking spans are not available for the document.</returns>
ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(Solution solution, DocumentId? documentId, string filePath, CancellationToken cancellationToken);
/// <summary>
/// Updates tracking spans with the latest positions of all active statements in the specified document snapshot (#line target document) and returns them.
/// </summary>
ValueTask<ImmutableArray<ActiveStatementTrackingSpan>> GetAdjustedTrackingSpansAsync(TextDocument document, ITextSnapshot snapshot, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/EditorFeatures/CSharpTest/EditAndContinue/TopLevelEditingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
[UseExportProvider]
public class TopLevelEditingTests : EditingTestBase
{
#region Usings
[Fact]
public void Using_Global_Insert()
{
var src1 = @"
using System.Collections.Generic;
";
var src2 = @"
global using D = System.Diagnostics;
global using System.Collections;
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [global using D = System.Diagnostics;]@2",
"Insert [global using System.Collections;]@40");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Delete1()
{
var src1 = @"
using System.Diagnostics;
";
var src2 = @"";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [using System.Diagnostics;]@2");
Assert.IsType<UsingDirectiveSyntax>(edits.Edits.First().OldNode);
Assert.Null(edits.Edits.First().NewNode);
}
[Fact]
public void Using_Delete2()
{
var src1 = @"
using D = System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
";
var src2 = @"
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [using D = System.Diagnostics;]@2",
"Delete [using System.Collections;]@33");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Insert()
{
var src1 = @"
using System.Collections.Generic;
";
var src2 = @"
using D = System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [using D = System.Diagnostics;]@2",
"Insert [using System.Collections;]@33");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Update1()
{
var src1 = @"
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
";
var src2 = @"
using System.Diagnostics;
using X = System.Collections;
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [using System.Collections;]@29 -> [using X = System.Collections;]@29");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Update2()
{
var src1 = @"
using System.Diagnostics;
using X1 = System.Collections;
using System.Collections.Generic;
";
var src2 = @"
using System.Diagnostics;
using X2 = System.Collections;
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [using X1 = System.Collections;]@29 -> [using X2 = System.Collections;]@29");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Update3()
{
var src1 = @"
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
";
var src2 = @"
using System;
using System.Collections;
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [using System.Diagnostics;]@2 -> [using System;]@2");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Reorder1()
{
var src1 = @"
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
";
var src2 = @"
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [using System.Diagnostics;]@2 -> @64");
}
[Fact]
public void Using_InsertDelete1()
{
var src1 = @"
namespace N
{
using System.Collections;
}
namespace M
{
}
";
var src2 = @"
namespace N
{
}
namespace M
{
using System.Collections;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [using System.Collections;]@43",
"Delete [using System.Collections;]@22");
}
[Fact]
public void Using_InsertDelete2()
{
var src1 = @"
namespace N
{
using System.Collections;
}
";
var src2 = @"
using System.Collections;
namespace N
{
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [using System.Collections;]@2",
"Delete [using System.Collections;]@22");
}
[Fact]
public void Using_Delete_ChangesCodeMeaning()
{
// This test specifically validates the scenario we _don't_ support, namely when inserting or deleting
// a using directive, if existing code changes in meaning as a result, we don't issue edits for that code.
// If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself.
var src1 = @"
using System.IO;
using DirectoryInfo = N.C;
namespace N
{
public class C
{
public C(string a) { }
public FileAttributes Attributes { get; set; }
}
public class D
{
public void M()
{
var d = new DirectoryInfo(""aa"");
var x = directoryInfo.Attributes;
}
}
}";
var src2 = @"
using System.IO;
namespace N
{
public class C
{
public C(string a) { }
public FileAttributes Attributes { get; set; }
}
public class D
{
public void M()
{
var d = new DirectoryInfo(""aa"");
var x = directoryInfo.Attributes;
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [using DirectoryInfo = N.C;]@20");
edits.VerifySemantics();
}
[Fact]
public void Using_Insert_ForNewCode()
{
// As distinct from the above, this test validates a real world scenario of inserting a using directive
// and changing code that utilizes the new directive to some effect.
var src1 = @"
namespace N
{
class Program
{
static void Main(string[] args)
{
}
}
}";
var src2 = @"
using System;
namespace N
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main")));
}
[Fact]
public void Using_Delete_ForOldCode()
{
var src1 = @"
using System;
namespace N
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
}
}
}";
var src2 = @"
namespace N
{
class Program
{
static void Main(string[] args)
{
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main")));
}
[Fact]
public void Using_Insert_CreatesAmbiguousCode()
{
// This test validates that we still issue edits for changed valid code, even when unchanged
// code has ambiguities after adding a using.
var src1 = @"
using System.Threading;
namespace N
{
class C
{
void M()
{
// Timer exists in System.Threading and System.Timers
var t = new Timer(s => System.Console.WriteLine(s));
}
}
}";
var src2 = @"
using System.Threading;
using System.Timers;
namespace N
{
class C
{
void M()
{
// Timer exists in System.Threading and System.Timers
var t = new Timer(s => System.Console.WriteLine(s));
}
void M2()
{
// TimersDescriptionAttribute only exists in System.Timers
System.Console.WriteLine(new TimersDescriptionAttribute(""""));
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("N.C.M2")));
}
#endregion
#region Extern Alias
[Fact]
public void ExternAliasUpdate()
{
var src1 = "extern alias X;";
var src2 = "extern alias Y;";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [extern alias X;]@0 -> [extern alias Y;]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Update, "extern alias Y;", CSharpFeaturesResources.extern_alias));
}
[Fact]
public void ExternAliasInsert()
{
var src1 = "";
var src2 = "extern alias Y;";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [extern alias Y;]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "extern alias Y;", CSharpFeaturesResources.extern_alias));
}
[Fact]
public void ExternAliasDelete()
{
var src1 = "extern alias Y;";
var src2 = "";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [extern alias Y;]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.extern_alias));
}
#endregion
#region Assembly/Module Attributes
[Fact]
public void Insert_TopLevelAttribute()
{
var src1 = "";
var src2 = "[assembly: System.Obsolete(\"2\")]";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [[assembly: System.Obsolete(\"2\")]]@0",
"Insert [System.Obsolete(\"2\")]@11");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "[assembly: System.Obsolete(\"2\")]", FeaturesResources.attribute));
}
[Fact]
public void Delete_TopLevelAttribute()
{
var src1 = "[assembly: System.Obsolete(\"2\")]";
var src2 = "";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [[assembly: System.Obsolete(\"2\")]]@0",
"Delete [System.Obsolete(\"2\")]@11");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, null, FeaturesResources.attribute));
}
[Fact]
public void Update_TopLevelAttribute()
{
var src1 = "[assembly: System.Obsolete(\"1\")]";
var src2 = "[assembly: System.Obsolete(\"2\")]";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[assembly: System.Obsolete(\"1\")]]@0 -> [[assembly: System.Obsolete(\"2\")]]@0",
"Update [System.Obsolete(\"1\")]@11 -> [System.Obsolete(\"2\")]@11");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Update, "System.Obsolete(\"2\")", FeaturesResources.attribute));
}
[Fact]
public void Reorder_TopLevelAttribute()
{
var src1 = "[assembly: System.Obsolete(\"1\")][assembly: System.Obsolete(\"2\")]";
var src2 = "[assembly: System.Obsolete(\"2\")][assembly: System.Obsolete(\"1\")]";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [[assembly: System.Obsolete(\"2\")]]@32 -> @0");
edits.VerifyRudeDiagnostics();
}
#endregion
#region Types
[Theory]
[InlineData("class", "struct")]
[InlineData("class", "record")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874
[InlineData("class", "record struct")]
[InlineData("class", "interface")]
[InlineData("struct", "record struct")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874
public void Type_Kind_Update(string oldKeyword, string newKeyword)
{
var src1 = oldKeyword + " C { }";
var src2 = newKeyword + " C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [" + oldKeyword + " C { }]@0 -> [" + newKeyword + " C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeKindUpdate, newKeyword + " C"));
}
[Theory]
[InlineData("class", "struct")]
[InlineData("class", "record")]
[InlineData("class", "record struct")]
[InlineData("class", "interface")]
[InlineData("struct", "record struct")]
public void Type_Kind_Update_Reloadable(string oldKeyword, string newKeyword)
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + newKeyword + " C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }]@145 -> [[CreateNewOnMetadataUpdate]" + newKeyword + " C { }]@145");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Modifiers_Static_Remove()
{
var src1 = "public static class C { }";
var src2 = "public class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public static class C { }]@0 -> [public class C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public class C", FeaturesResources.class_));
}
[Theory]
[InlineData("public")]
[InlineData("protected")]
[InlineData("private")]
[InlineData("private protected")]
[InlineData("internal protected")]
public void Type_Modifiers_Accessibility_Change(string accessibility)
{
var src1 = accessibility + " class C { }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [" + accessibility + " class C { }]@0 -> [class C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "class C", FeaturesResources.class_));
}
[Theory]
[InlineData("public", "public")]
[InlineData("internal", "internal")]
[InlineData("", "internal")]
[InlineData("internal", "")]
[InlineData("protected", "protected")]
[InlineData("private", "private")]
[InlineData("private protected", "private protected")]
[InlineData("internal protected", "internal protected")]
public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB)
{
var srcA1 = accessibilityA + " partial class C { }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = accessibilityB + " partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(),
});
}
[Fact]
public void Type_Modifiers_Internal_Remove()
{
var src1 = "internal interface C { }";
var src2 = "interface C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact]
public void Type_Modifiers_Internal_Add()
{
var src1 = "struct C { }";
var src2 = "internal struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact]
public void Type_Modifiers_Accessibility_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[CreateNewOnMetadataUpdate]public class C { }]@145 -> [[CreateNewOnMetadataUpdate]internal class C { }]@145");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Theory]
[InlineData("class")]
[InlineData("struct")]
[InlineData("interface")]
[InlineData("record")]
[InlineData("record struct")]
public void Type_Modifiers_NestedPrivateInInterface_Remove(string keyword)
{
var src1 = "interface C { private " + keyword + " S { } }";
var src2 = "interface C { " + keyword + " S { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, keyword + " S", GetResource(keyword)));
}
[Theory]
[InlineData("class")]
[InlineData("struct")]
[InlineData("interface")]
[InlineData("record")]
[InlineData("record struct")]
public void Type_Modifiers_NestedPrivateInClass_Add(string keyword)
{
var src1 = "class C { " + keyword + " S { } }";
var src2 = "class C { private " + keyword + " S { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Theory]
[InlineData("class")]
[InlineData("struct")]
[InlineData("interface")]
[InlineData("record")]
[InlineData("record struct")]
public void Type_Modifiers_NestedPublicInInterface_Add(string keyword)
{
var src1 = "interface C { " + keyword + " S { } }";
var src2 = "interface C { public " + keyword + " S { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")]
public void Type_Modifiers_Unsafe_Add()
{
var src1 = "public class C { }";
var src2 = "public unsafe class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public class C { }]@0 -> [public unsafe class C { }]@0");
edits.VerifyRudeDiagnostics();
}
[Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")]
public void Type_Modifiers_Unsafe_Remove()
{
var src1 = @"
using System;
unsafe delegate void D();
class C
{
unsafe class N { }
public unsafe event Action<int> A { add { } remove { } }
unsafe int F() => 0;
unsafe int X;
unsafe int Y { get; }
unsafe C() {}
unsafe ~C() {}
}
";
var src2 = @"
using System;
delegate void D();
class C
{
class N { }
public event Action<int> A { add { } remove { } }
int F() => 0;
int X;
int Y { get; }
C() {}
~C() {}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [unsafe delegate void D();]@17 -> [delegate void D();]@17",
"Update [unsafe class N { }]@60 -> [class N { }]@53",
"Update [public unsafe event Action<int> A { add { } remove { } }]@84 -> [public event Action<int> A { add { } remove { } }]@70",
"Update [unsafe int F() => 0;]@146 -> [int F() => 0;]@125",
"Update [unsafe int X;]@172 -> [int X;]@144",
"Update [unsafe int Y { get; }]@191 -> [int Y { get; }]@156",
"Update [unsafe C() {}]@218 -> [C() {}]@176",
"Update [unsafe ~C() {}]@237 -> [~C() {}]@188");
edits.VerifyRudeDiagnostics();
}
[Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")]
public void Type_Modifiers_Unsafe_DeleteInsert()
{
var srcA1 = "partial class C { unsafe void F() { } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"))
}),
});
}
[Fact]
public void Type_Modifiers_Ref_Add()
{
var src1 = "public struct C { }";
var src2 = "public ref struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public struct C { }]@0 -> [public ref struct C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public ref struct C", CSharpFeaturesResources.struct_));
}
[Fact]
public void Type_Modifiers_Ref_Remove()
{
var src1 = "public ref struct C { }";
var src2 = "public struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public ref struct C { }]@0 -> [public struct C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_));
}
[Fact]
public void Type_Modifiers_ReadOnly_Add()
{
var src1 = "public struct C { }";
var src2 = "public readonly struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public struct C { }]@0 -> [public readonly struct C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly struct C", CSharpFeaturesResources.struct_));
}
[Fact]
public void Type_Modifiers_ReadOnly_Remove()
{
var src1 = "public readonly struct C { }";
var src2 = "public struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public readonly struct C { }]@0 -> [public struct C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_));
}
[Theory]
[InlineData("[System.CLSCompliantAttribute]", "CLSCompliantAttribute")]
[InlineData("[System.Diagnostics.CodeAnalysis.AllowNullAttribute]", "AllowNullAttribute")]
[InlineData("[System.Diagnostics.CodeAnalysis.DisallowNullAttribute]", "DisallowNullAttribute")]
[InlineData("[System.Diagnostics.CodeAnalysis.MaybeNullAttribute]", "MaybeNullAttribute")]
[InlineData("[System.Diagnostics.CodeAnalysis.NotNullAttribute]", "NotNullAttribute")]
[InlineData("[System.NonSerializedAttribute]", "NonSerializedAttribute")]
[InlineData("[System.Reflection.AssemblyAlgorithmIdAttribute]", "AssemblyAlgorithmIdAttribute")]
[InlineData("[System.Reflection.AssemblyCultureAttribute]", "AssemblyCultureAttribute")]
[InlineData("[System.Reflection.AssemblyFlagsAttribute]", "AssemblyFlagsAttribute")]
[InlineData("[System.Reflection.AssemblyVersionAttribute]", "AssemblyVersionAttribute")]
[InlineData("[System.Runtime.CompilerServices.DllImportAttribute]", "DllImportAttribute")]
[InlineData("[System.Runtime.CompilerServices.IndexerNameAttribute]", "IndexerNameAttribute")]
[InlineData("[System.Runtime.CompilerServices.MethodImplAttribute]", "MethodImplAttribute")]
[InlineData("[System.Runtime.CompilerServices.SpecialNameAttribute]", "SpecialNameAttribute")]
[InlineData("[System.Runtime.CompilerServices.TypeForwardedToAttribute]", "TypeForwardedToAttribute")]
[InlineData("[System.Runtime.InteropServices.ComImportAttribute]", "ComImportAttribute")]
[InlineData("[System.Runtime.InteropServices.DefaultParameterValueAttribute]", "DefaultParameterValueAttribute")]
[InlineData("[System.Runtime.InteropServices.FieldOffsetAttribute]", "FieldOffsetAttribute")]
[InlineData("[System.Runtime.InteropServices.InAttribute]", "InAttribute")]
[InlineData("[System.Runtime.InteropServices.MarshalAsAttribute]", "MarshalAsAttribute")]
[InlineData("[System.Runtime.InteropServices.OptionalAttribute]", "OptionalAttribute")]
[InlineData("[System.Runtime.InteropServices.OutAttribute]", "OutAttribute")]
[InlineData("[System.Runtime.InteropServices.PreserveSigAttribute]", "PreserveSigAttribute")]
[InlineData("[System.Runtime.InteropServices.StructLayoutAttribute]", "StructLayoutAttribute")]
[InlineData("[System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute]", "WindowsRuntimeImportAttribute")]
[InlineData("[System.Security.DynamicSecurityMethodAttribute]", "DynamicSecurityMethodAttribute")]
[InlineData("[System.SerializableAttribute]", "SerializableAttribute")]
[InlineData("[System.Runtime.CompilerServices.AsyncMethodBuilderAttribute]", "AsyncMethodBuilderAttribute")]
public void Type_Attribute_Insert_SupportedByRuntime_NonCustomAttribute(string attributeType, string attributeName)
{
var src1 = @"class C { public void M(int a) {} }";
var src2 = attributeType + @"class C { public void M(int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { public void M(int a) {} }]@0 -> [" + attributeType + "class C { public void M(int a) {} }]@0");
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.ChangingNonCustomAttribute, "class C", attributeName, FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Update_NotSupportedByRuntime1()
{
var attribute = "public class A1Attribute : System.Attribute { }\n\n" +
"public class A2Attribute : System.Attribute { }\n\n";
var src1 = attribute + "[A1]class C { }";
var src2 = attribute + "[A2]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A1]class C { }]@98 -> [[A2]class C { }]@98");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Update_NotSupportedByRuntime2()
{
var src1 = "[System.Obsolete(\"1\")]class C { }";
var src2 = "[System.Obsolete(\"2\")]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete(\"1\")]class C { }]@0 -> [[System.Obsolete(\"2\")]class C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Delete_NotSupportedByRuntime1()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + "[A, B]class C { }";
var src2 = attribute + "[A]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A, B]class C { }]@96 -> [[A]class C { }]@96");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Delete_NotSupportedByRuntime2()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + "[B, A]class C { }";
var src2 = attribute + "[A]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[B, A]class C { }]@96 -> [[A]class C { }]@96");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Change_Reloadable()
{
var attributeSrc = @"
public class A1 : System.Attribute { }
public class A2 : System.Attribute { }
public class A3 : System.Attribute { }
";
var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }";
var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[CreateNewOnMetadataUpdate, A1, A2]class C { }]@267 -> [[CreateNewOnMetadataUpdate, A2, A3]class C { }]@267");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Attribute_ReloadableRemove()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var src2 = ReloadableAttributeSrc + "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Attribute_ReloadableAdd()
{
var src1 = ReloadableAttributeSrc + "class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_Attribute_ReloadableBase()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { void F() {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Attribute_Add()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + "[A]class C { }";
var src2 = attribute + "[A, B]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]class C { }]@96 -> [[A, B]class C { }]@96");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_Attribute_Add_NotSupportedByRuntime1()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + "[A]class C { }";
var src2 = attribute + "[A, B]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]class C { }]@96 -> [[A, B]class C { }]@96");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Add_NotSupportedByRuntime2()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "class C { }";
var src2 = attribute + "[A]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { }]@48 -> [[A]class C { }]@48");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Reorder1()
{
var src1 = "[A(1), B(2), C(3)]class C { }";
var src2 = "[C(3), A(1), B(2)]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A(1), B(2), C(3)]class C { }]@0 -> [[C(3), A(1), B(2)]class C { }]@0");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Type_Attribute_Reorder2()
{
var src1 = "[A, B, C]class C { }";
var src2 = "[B, C, A]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A, B, C]class C { }]@0 -> [[B, C, A]class C { }]@0");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Type_Attribute_ReorderAndUpdate_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + "[System.Obsolete(\"1\"), A, B]class C { }";
var src2 = attribute + "[A, B, System.Obsolete(\"2\")]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete(\"1\"), A, B]class C { }]@96 -> [[A, B, System.Obsolete(\"2\")]class C { }]@96");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Theory]
[InlineData("class")]
[InlineData("struct")]
[InlineData("interface")]
[InlineData("record")]
[InlineData("record struct")]
public void Type_Rename(string keyword)
{
var src1 = keyword + " C { }";
var src2 = keyword + " D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [" + keyword + " C { }]@0 -> [" + keyword + " D { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, keyword + " D", GetResource(keyword)));
}
[Fact]
public void Type_Rename_AddAndDeleteMember()
{
var src1 = "class C { int x = 1; }";
var src2 = "class D { void F() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { int x = 1; }]@0 -> [class D { void F() { } }]@0",
"Insert [void F() { }]@10",
"Insert [()]@16",
"Delete [int x = 1;]@10",
"Delete [int x = 1]@10",
"Delete [x = 1]@14");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_));
}
[Fact]
[WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")]
public void Type_Rename_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[CreateNewOnMetadataUpdate]class C { }]@145 -> [[CreateNewOnMetadataUpdate]class D { }]@145");
// TODO: expected: Replace edit of D
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_));
}
[Fact]
[WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")]
public void Type_Rename_Reloadable_AddAndDeleteMember()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { int x = 1; }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { void F() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[CreateNewOnMetadataUpdate]class C { int x = 1; }]@145 -> [[CreateNewOnMetadataUpdate]class D { void F() { } }]@145",
"Insert [void F() { }]@182",
"Insert [()]@188",
"Delete [int x = 1;]@182",
"Delete [int x = 1]@182",
"Delete [x = 1]@186");
// TODO: expected: Replace edit of D
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_));
}
[Fact]
public void Interface_NoModifiers_Insert()
{
var src1 = "";
var src2 = "interface C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Interface_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { } ";
var src2 = "namespace N { interface C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Interface_NoModifiers_IntoType_Insert()
{
var src1 = "interface N { }";
var src2 = "interface N { interface C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Class_NoModifiers_Insert()
{
var src1 = "";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Class_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { }";
var src2 = "namespace N { class C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Class_NoModifiers_IntoType_Insert()
{
var src1 = "struct N { }";
var src2 = "struct N { class C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Struct_NoModifiers_Insert()
{
var src1 = "";
var src2 = "struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Struct_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { }";
var src2 = "namespace N { struct C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Struct_NoModifiers_IntoType_Insert()
{
var src1 = "struct N { }";
var src2 = "struct N { struct C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Type_BaseType_Add_Unchanged()
{
var src1 = "class C { }";
var src2 = "class C : object { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { }]@0 -> [class C : object { }]@0");
edits.VerifySemantics();
}
[Fact]
public void Type_BaseType_Add_Changed()
{
var src1 = "class C { }";
var src2 = "class C : D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { }]@0 -> [class C : D { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("string[]", "string[]?")]
[InlineData("object", "dynamic")]
[InlineData("dynamic?", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Type_BaseType_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}";
var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Type_BaseType_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}";
var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_BaseType_Update_CompileTimeTypeUnchanged()
{
var src1 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<A> {}";
var src2 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<B> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact]
public void Type_BaseInterface_Add()
{
var src1 = "class C { }";
var src2 = "class C : IDisposable { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { }]@0 -> [class C : IDisposable { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_BaseInterface_Delete_Inherited()
{
var src1 = @"
interface B {}
interface A : B {}
class C : A, B {}
";
var src2 = @"
interface B {}
interface A : B {}
class C : A {}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact]
public void Type_BaseInterface_Reorder()
{
var src1 = "class C : IGoo, IBar { }";
var src2 = "class C : IBar, IGoo { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C : IGoo, IBar { }]@0 -> [class C : IBar, IGoo { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("object", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Type_BaseInterface_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}";
var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}";
var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Base_Partial()
{
var srcA1 = "partial class C : B, I { }";
var srcB1 = "partial class C : J { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C : B, I, J { }";
var srcC = @"
class B {}
interface I {}
interface J {}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults()
});
}
[Fact]
public void Type_Base_Partial_InsertDeleteAndUpdate()
{
var srcA1 = "partial class C { }";
var srcB1 = "";
var srcC1 = "partial class C { }";
var srcA2 = "";
var srcB2 = "partial class C : D { }";
var srcC2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "partial class C", FeaturesResources.class_) }),
DocumentResults(),
});
}
[Fact]
public void Type_Base_InsertDelete()
{
var srcA1 = "";
var srcB1 = "class C : B, I { }";
var srcA2 = "class C : B, I { }";
var srcB2 = "";
var srcC = @"
class B {}
interface I {}
interface J {}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults()
});
}
[Fact]
public void Type_Reloadable_NotSupportedByRuntime()
{
var src1 = ReloadableAttributeSrc + @"
[CreateNewOnMetadataUpdate]
public class C
{
void F() { System.Console.WriteLine(1); }
}";
var src2 = ReloadableAttributeSrc + @"
[CreateNewOnMetadataUpdate]
public class C
{
void F() { System.Console.WriteLine(2); }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void F()", "CreateNewOnMetadataUpdateAttribute"));
}
[Fact]
public void Type_Insert_AbstractVirtualOverride()
{
var src1 = "";
var src2 = @"
public abstract class C<T>
{
public abstract void F();
public virtual void G() {}
public override string ToString() => null;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Type_Insert_NotSupportedByRuntime()
{
var src1 = @"
public class C
{
void F()
{
}
}";
var src2 = @"
public class C
{
void F()
{
}
}
public class D
{
void M()
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "public class D", FeaturesResources.class_));
}
[Fact]
public void Type_Insert_Reloadable()
{
var src1 = ReloadableAttributeSrc + "";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C")));
}
[Fact]
public void InterfaceInsert()
{
var src1 = "";
var src2 = @"
public interface I
{
void F();
static void G() {}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void RefStructInsert()
{
var src1 = "";
var src2 = "ref struct X { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [ref struct X { }]@0");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Struct_ReadOnly_Insert()
{
var src1 = "";
var src2 = "readonly struct X { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [readonly struct X { }]@0");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Struct_RefModifier_Add()
{
var src1 = "struct X { }";
var src2 = "ref struct X { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [struct X { }]@0 -> [ref struct X { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "ref struct X", CSharpFeaturesResources.struct_));
}
[Fact]
public void Struct_ReadonlyModifier_Add()
{
var src1 = "struct X { }";
var src2 = "readonly struct X { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [struct X { }]@0 -> [readonly struct X { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly struct X", SyntaxFacts.GetText(SyntaxKind.StructKeyword)));
}
[Theory]
[InlineData("ref")]
[InlineData("readonly")]
public void Struct_Modifiers_Partial_InsertDelete(string modifier)
{
var srcA1 = modifier + " partial struct S { }";
var srcB1 = "partial struct S { }";
var srcA2 = "partial struct S { }";
var srcB2 = modifier + " partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults()
});
}
[Fact]
public void Class_ImplementingInterface_Add()
{
var src1 = @"
using System;
public interface ISample
{
string Get();
}
public interface IConflict
{
string Get();
}
public class BaseClass : ISample
{
public virtual string Get() => string.Empty;
}
";
var src2 = @"
using System;
public interface ISample
{
string Get();
}
public interface IConflict
{
string Get();
}
public class BaseClass : ISample
{
public virtual string Get() => string.Empty;
}
public class SubClass : BaseClass, IConflict
{
public override string Get() => string.Empty;
string IConflict.Get() => String.Empty;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Insert [public class SubClass : BaseClass, IConflict
{
public override string Get() => string.Empty;
string IConflict.Get() => String.Empty;
}]@219",
"Insert [public override string Get() => string.Empty;]@272",
"Insert [string IConflict.Get() => String.Empty;]@325",
"Insert [()]@298",
"Insert [()]@345");
// Here we add a class implementing an interface and a method inside it with explicit interface specifier.
// We want to be sure that adding the method will not tirgger a rude edit as it happens if adding a single method with explicit interface specifier.
edits.VerifyRudeDiagnostics();
}
[WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")]
[Fact]
public void Interface_InsertMembers()
{
var src1 = @"
using System;
interface I
{
}
";
var src2 = @"
using System;
interface I
{
static int StaticField = 10;
static void StaticMethod() { }
void VirtualMethod1() { }
virtual void VirtualMethod2() { }
abstract void AbstractMethod();
sealed void NonVirtualMethod() { }
public static int operator +(I a, I b) => 1;
static int StaticProperty1 { get => 1; set { } }
static int StaticProperty2 => 1;
virtual int VirtualProperty1 { get => 1; set { } }
virtual int VirtualProperty2 { get => 1; }
int VirtualProperty3 { get => 1; set { } }
int VirtualProperty4 { get => 1; }
abstract int AbstractProperty1 { get; set; }
abstract int AbstractProperty2 { get; }
sealed int NonVirtualProperty => 1;
int this[byte virtualIndexer] => 1;
int this[sbyte virtualIndexer] { get => 1; }
virtual int this[ushort virtualIndexer] { get => 1; set {} }
virtual int this[short virtualIndexer] { get => 1; set {} }
abstract int this[uint abstractIndexer] { get; set; }
abstract int this[int abstractIndexer] { get; }
sealed int this[ulong nonVirtualIndexer] { get => 1; set {} }
sealed int this[long nonVirtualIndexer] { get => 1; set {} }
static event Action StaticEvent;
static event Action StaticEvent2 { add { } remove { } }
event Action VirtualEvent { add { } remove { } }
abstract event Action AbstractEvent;
sealed event Action NonVirtualEvent { add { } remove { } }
abstract class C { }
interface J { }
enum E { }
delegate void D();
}
";
var edits = GetTopEdits(src1, src2);
// TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128.
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoInterface, "static void StaticMethod()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertVirtual, "void VirtualMethod1()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertVirtual, "virtual void VirtualMethod2()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertVirtual, "abstract void AbstractMethod()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed void NonVirtualMethod()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertOperator, "public static int operator +(I a, I b)", FeaturesResources.operator_),
Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty1", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", CSharpFeaturesResources.property_getter),
Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty1", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty2", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty3", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty4", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty1", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty2", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", CSharpFeaturesResources.property_getter),
Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", CSharpFeaturesResources.indexer_getter),
Diagnostic(RudeEditKind.InsertVirtual, "int this[sbyte virtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[ushort virtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[short virtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[uint abstractIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[int abstractIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[ulong nonVirtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[long nonVirtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertIntoInterface, "static event Action StaticEvent2", FeaturesResources.event_),
Diagnostic(RudeEditKind.InsertVirtual, "event Action VirtualEvent", FeaturesResources.event_),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed event Action NonVirtualEvent", FeaturesResources.event_),
Diagnostic(RudeEditKind.InsertIntoInterface, "StaticField = 10", FeaturesResources.field),
Diagnostic(RudeEditKind.InsertIntoInterface, "StaticEvent", CSharpFeaturesResources.event_field),
Diagnostic(RudeEditKind.InsertVirtual, "AbstractEvent", CSharpFeaturesResources.event_field));
}
[Fact]
public void Interface_InsertDelete()
{
var srcA1 = @"
interface I
{
static void M() { }
}
";
var srcB1 = @"
";
var srcA2 = @"
";
var srcB2 = @"
interface I
{
static void M() { }
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("M"))
}),
});
}
[Fact]
public void Type_Generic_InsertMembers()
{
var src1 = @"
using System;
class C<T>
{
}
";
var src2 = @"
using System;
class C<T>
{
void M() {}
int P1 { get; set; }
int P2 { get => 1; set {} }
int this[int i] { get => 1; set {} }
event Action E { add {} remove {} }
event Action EF;
int F1, F2;
enum E {}
interface I {}
class D {}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoGenericType, "void M()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertIntoGenericType, "int P1", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertIntoGenericType, "int P2", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertIntoGenericType, "int this[int i]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertIntoGenericType, "event Action E", FeaturesResources.event_),
Diagnostic(RudeEditKind.InsertIntoGenericType, "EF", CSharpFeaturesResources.event_field),
Diagnostic(RudeEditKind.InsertIntoGenericType, "F1", FeaturesResources.field),
Diagnostic(RudeEditKind.InsertIntoGenericType, "F2", FeaturesResources.field));
}
[Fact]
public void Type_Generic_InsertMembers_Reloadable()
{
var src1 = ReloadableAttributeSrc + @"
[CreateNewOnMetadataUpdate]
class C<T>
{
}
";
var src2 = ReloadableAttributeSrc + @"
[CreateNewOnMetadataUpdate]
class C<T>
{
void M() {}
int P1 { get; set; }
int P2 { get => 1; set {} }
int this[int i] { get => 1; set {} }
event System.Action E { add {} remove {} }
event System.Action EF;
int F1, F2;
enum E {}
interface I {}
class D {}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Generic_DeleteInsert()
{
var srcA1 = @"
class C<T> { void F() {} }
struct S<T> { void F() {} }
interface I<T> { void F() {} }
";
var srcB1 = "";
var srcA2 = srcB1;
var srcB2 = srcA1;
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "struct S<T>"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "interface I<T>"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"),
})
});
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")]
[WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")]
public void Type_TypeParameter_Insert_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C<T> { void F() { } }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C<T, S> { int x = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Delete()
{
var src1 = @"
class C { void F() {} }
struct S { void F() {} }
interface I { void F() {} }
";
var src2 = "";
GetTopEdits(src1, src2).VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")),
Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(CSharpFeaturesResources.struct_, "S")),
Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I")));
}
[Fact]
public void Type_Delete_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }";
var src2 = ReloadableAttributeSrc;
GetTopEdits(src1, src2).VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")));
}
[Fact]
public void Type_Partial_DeleteDeclaration()
{
var srcA1 = "partial class C { void F() {} void M() { } }";
var srcB1 = "partial class C { void G() {} }";
var srcA2 = "";
var srcB2 = "partial class C { void G() {} void M() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.method, "C.F()")) }),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("M")),
})
});
}
[Fact]
public void Type_Partial_InsertFirstDeclaration()
{
var src1 = "";
var src2 = "partial class C { void F() {} }";
GetTopEdits(src1, src2).VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C"), preserveLocalVariables: false) });
}
[Fact]
public void Type_Partial_InsertSecondDeclaration()
{
var srcA1 = "partial class C { void F() {} }";
var srcB1 = "";
var srcA2 = "partial class C { void F() {} }";
var srcB2 = "partial class C { void G() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G"), preserveLocalVariables: false)
}),
});
}
[Fact]
public void Type_Partial_Reloadable()
{
var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }";
var srcB1 = "";
var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }";
var srcB2 = "partial class C { void G() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")
}),
});
}
[Fact]
public void Type_DeleteInsert()
{
var srcA1 = @"
class C { void F() {} }
struct S { void F() {} }
interface I { void F() {} }
";
var srcB1 = "";
var srcA2 = srcB1;
var srcB2 = srcA1;
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember("F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")),
})
});
}
[Fact]
public void Type_DeleteInsert_Reloadable()
{
var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }";
var srcB1 = "";
var srcA2 = ReloadableAttributeSrc;
var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")),
})
});
}
[Fact]
public void Type_NonInsertableMembers_DeleteInsert()
{
var srcA1 = @"
abstract class C
{
public abstract void AbstractMethod();
public virtual void VirtualMethod() {}
public override string ToString() => null;
public void I.G() {}
}
interface I
{
void G();
void F() {}
}
";
var srcB1 = "";
var srcA2 = srcB1;
var srcB2 = srcA1;
// TODO: The methods without bodies do not need to be updated.
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")),
})
});
}
[Fact]
public void Type_Attribute_NonInsertableMembers_DeleteInsert()
{
var srcA1 = @"
abstract class C
{
public abstract void AbstractMethod();
public virtual void VirtualMethod() {}
public override string ToString() => null;
public void I.G() {}
}
interface I
{
void G();
void F() {}
}
";
var srcB1 = "";
var srcA2 = "";
var srcB2 = @"
abstract class C
{
[System.Obsolete]public abstract void AbstractMethod();
public virtual void VirtualMethod() {}
public override string ToString() => null;
public void I.G() {}
}
interface I
{
[System.Obsolete]void G();
void F() {}
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")),
})
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_DeleteInsert_DataMembers()
{
var srcA1 = @"
class C
{
public int x = 1;
public int y = 2;
public int P { get; set; } = 3;
public event System.Action E = new System.Action(null);
}
";
var srcB1 = "";
var srcA2 = "";
var srcB2 = @"
class C
{
public int x = 1;
public int y = 2;
public int P { get; set; } = 3;
public event System.Action E = new System.Action(null);
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true),
})
});
}
[Fact]
public void Type_DeleteInsert_DataMembers_PartialSplit()
{
var srcA1 = @"
class C
{
public int x = 1;
public int y = 2;
public int P { get; set; } = 3;
}
";
var srcB1 = "";
var srcA2 = @"
partial class C
{
public int x = 1;
public int y = 2;
}
";
var srcB2 = @"
partial class C
{
public int P { get; set; } = 3;
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true),
})
});
}
[Fact]
public void Type_DeleteInsert_DataMembers_PartialMerge()
{
var srcA1 = @"
partial class C
{
public int x = 1;
public int y = 2;
}
";
var srcB1 = @"
partial class C
{
public int P { get; set; } = 3;
}";
var srcA2 = @"
class C
{
public int x = 1;
public int y = 2;
public int P { get; set; } = 3;
}
";
var srcB2 = @"
";
// note that accessors are not updated since they do not have bodies
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true),
}),
DocumentResults()
});
}
#endregion
#region Records
[Fact]
public void Record_Partial_MovePrimaryConstructor()
{
var src1 = @"
partial record C { }
partial record C(int X);";
var src2 = @"
partial record C(int X);
partial record C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_Name_Update()
{
var src1 = "record C { }";
var src2 = "record D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C { }]@0 -> [record D { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "record D", CSharpFeaturesResources.record_));
}
[Fact]
public void RecordStruct_NoModifiers_Insert()
{
var src1 = "";
var src2 = "record struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void RecordStruct_AddField()
{
var src1 = @"
record struct C(int X)
{
}";
var src2 = @"
record struct C(int X)
{
private int _y = 0;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoStruct, "_y = 0", FeaturesResources.field, CSharpFeaturesResources.record_struct));
}
[Fact]
public void RecordStruct_AddProperty()
{
var src1 = @"
record struct C(int X)
{
}";
var src2 = @"
record struct C(int X)
{
public int Y { get; set; } = 0;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoStruct, "public int Y { get; set; } = 0;", FeaturesResources.auto_property, CSharpFeaturesResources.record_struct));
}
[Fact]
public void Record_NoModifiers_Insert()
{
var src1 = "";
var src2 = "record C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { }";
var src2 = "namespace N { record C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_NoModifiers_IntoType_Insert()
{
var src1 = "struct N { }";
var src2 = "struct N { record C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_BaseTypeUpdate1()
{
var src1 = "record C { }";
var src2 = "record C : D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C { }]@0 -> [record C : D { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_));
}
[Fact]
public void Record_BaseTypeUpdate2()
{
var src1 = "record C : D1 { }";
var src2 = "record C : D2 { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C : D1 { }]@0 -> [record C : D2 { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_));
}
[Fact]
public void Record_BaseInterfaceUpdate1()
{
var src1 = "record C { }";
var src2 = "record C : IDisposable { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C { }]@0 -> [record C : IDisposable { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_));
}
[Fact]
public void Record_BaseInterfaceUpdate2()
{
var src1 = "record C : IGoo, IBar { }";
var src2 = "record C : IGoo { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C : IGoo, IBar { }]@0 -> [record C : IGoo { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_));
}
[Fact]
public void Record_BaseInterfaceUpdate3()
{
var src1 = "record C : IGoo, IBar { }";
var src2 = "record C : IBar, IGoo { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C : IGoo, IBar { }]@0 -> [record C : IBar, IGoo { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_));
}
[Fact]
public void RecordInsert_AbstractVirtualOverride()
{
var src1 = "";
var src2 = @"
public abstract record C<T>
{
public abstract void F();
public virtual void G() {}
public override void H() {}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_ParameterlessConstructor()
{
var src1 = "record C { }";
var src2 = @"
record C
{
public C()
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void RecordStruct_ImplementSynthesized_ParameterlessConstructor()
{
var src1 = "record struct C { }";
var src2 = @"
record struct C
{
public C()
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_PrintMembers()
{
var src1 = "record C { }";
var src2 = @"
record C
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void RecordStruct_ImplementSynthesized_PrintMembers()
{
var src1 = "record struct C { }";
var src2 = @"
record struct C
{
private readonly bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_WrongParameterName()
{
var src1 = "record C { }";
var src2 = @"
record C
{
protected virtual bool PrintMembers(System.Text.StringBuilder sb)
{
return false;
}
public virtual bool Equals(C rhs)
{
return false;
}
protected C(C other)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected virtual bool PrintMembers(System.Text.StringBuilder sb)", "PrintMembers(System.Text.StringBuilder builder)"),
Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "public virtual bool Equals(C rhs)", "Equals(C other)"),
Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected C(C other)", "C(C original)"));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.FirstOrDefault()?.Type.ToDisplayString() == "C"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true),
},
EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Record_ImplementSynthesized_ToString()
{
var src1 = "record C { }";
var src2 = @"
record C
{
public override string ToString()
{
return ""R"";
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_UnImplementSynthesized_ToString()
{
var src1 = @"
record C
{
public override string ToString()
{
return ""R"";
}
}";
var src2 = "record C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddProperty_Primary()
{
var src1 = "record C(int X);";
var src2 = "record C(int X, int Y);";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "int Y", FeaturesResources.parameter));
}
[Fact]
public void Record_UnimplementSynthesized_ParameterlessConstructor()
{
var src1 = @"
record C
{
public C()
{
}
}";
var src2 = "record C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void RecordStruct_UnimplementSynthesized_ParameterlessConstructor()
{
var src1 = @"
record struct C
{
public C()
{
}
}";
var src2 = "record struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddProperty_NotPrimary()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int Y { get; set; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddProperty_NotPrimary_WithConstructor()
{
var src1 = @"
record C(int X)
{
public C(string fromAString)
{
}
}";
var src2 = @"
record C(int X)
{
public int Y { get; set; }
public C(string fromAString)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddProperty_NotPrimary_WithExplicitMembers()
{
var src1 = @"
record C(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return false;
}
public override int GetHashCode()
{
return 0;
}
public virtual bool Equals(C other)
{
return false;
}
public C(C original)
{
}
}";
var src2 = @"
record C(int X)
{
public int Y { get; set; }
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return false;
}
public override int GetHashCode()
{
return 0;
}
public virtual bool Equals(C other)
{
return false;
}
public C(C original)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddProperty_NotPrimary_WithInitializer()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int Y { get; set; } = 1;
}";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddField()
{
var src1 = "record C(int X) { }";
var src2 = "record C(int X) { private int _y; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddField_WithExplicitMembers()
{
var src1 = @"
record C(int X)
{
public C(C other)
{
}
}";
var src2 = @"
record C(int X)
{
private int _y;
public C(C other)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddField_WithInitializer()
{
var src1 = "record C(int X) { }";
var src2 = "record C(int X) { private int _y = 1; }";
var syntaxMap = GetSyntaxMap(src1, src2);
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddField_WithExistingInitializer()
{
var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }";
var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z; }";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddField_WithInitializerAndExistingInitializer()
{
var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }";
var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z = 1; }";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_DeleteField()
{
var src1 = "record C(int X) { private int _y; }";
var src2 = "record C(int X) { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.field, "_y")));
}
[Fact]
public void Record_DeleteProperty_Primary()
{
var src1 = "record C(int X, int Y) { }";
var src2 = "record C(int X) { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.parameter, "int Y")));
}
[Fact]
public void Record_DeleteProperty_NotPrimary()
{
var src1 = "record C(int X) { public int P { get; set; } }";
var src2 = "record C(int X) { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "P")));
}
[Fact]
public void Record_ImplementSynthesized_Property()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int X { get; init; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_Property_WithBody()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int X
{
get
{
return 4;
}
init
{
throw null;
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_Property_WithExpressionBody()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int X { get => 4; init => throw null; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_Property_InitToSet()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int X { get; set; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ImplementRecordParameterWithSet, "public int X", "X"));
}
[Fact]
public void Record_ImplementSynthesized_Property_MakeReadOnly()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int X { get; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ImplementRecordParameterAsReadOnly, "public int X", "X"));
}
[Fact]
public void Record_UnImplementSynthesized_Property()
{
var src1 = @"
record C(int X)
{
public int X { get; init; }
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_UnImplementSynthesized_Property_WithExpressionBody()
{
var src1 = @"
record C(int X)
{
public int X { get => 4; init => throw null; }
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_UnImplementSynthesized_Property_WithBody()
{
var src1 = @"
record C(int X)
{
public int X { get { return 4; } init { } }
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_Property_Partial()
{
var srcA1 = @"partial record C(int X);";
var srcB1 = @"partial record C;";
var srcA2 = @"partial record C(int X);";
var srcB2 = @"
partial record C
{
public int X { get; init; }
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true)
})
});
}
[Fact]
public void Record_UnImplementSynthesized_Property_Partial()
{
var srcA1 = @"partial record C(int X);";
var srcB1 = @"
partial record C
{
public int X { get; init; }
}";
var srcA2 = @"partial record C(int X);";
var srcB2 = @"partial record C;";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true)
})
});
}
[Fact]
public void Record_ImplementSynthesized_Property_Partial_WithBody()
{
var srcA1 = @"partial record C(int X);";
var srcB1 = @"partial record C;";
var srcA2 = @"partial record C(int X);";
var srcB2 = @"
partial record C
{
public int X
{
get
{
return 4;
}
init
{
throw null;
}
}
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))
})
});
}
[Fact]
public void Record_UnImplementSynthesized_Property_Partial_WithBody()
{
var srcA1 = @"partial record C(int X);";
var srcB1 = @"
partial record C
{
public int X
{
get
{
return 4;
}
init
{
throw null;
}
}
}";
var srcA2 = @"partial record C(int X);";
var srcB2 = @"partial record C;";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))
})
});
}
[Fact]
public void Record_MoveProperty_Partial()
{
var srcA1 = @"
partial record C(int X)
{
public int Y { get; init; }
}";
var srcB1 = @"
partial record C;
";
var srcA2 = @"
partial record C(int X);
";
var srcB2 = @"
partial record C
{
public int Y { get; init; }
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").SetMethod)
}),
});
}
[Fact]
public void Record_UnImplementSynthesized_Property_WithInitializer()
{
var src1 = @"
record C(int X)
{
public int X { get; init; } = 1;
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_UnImplementSynthesized_Property_WithInitializerMatchingCompilerGenerated()
{
var src1 = @"
record C(int X)
{
public int X { get; init; } = X;
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_Property_Delete_NotPrimary()
{
var src1 = @"
record C(int X)
{
public int Y { get; init; }
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "Y")));
}
[Fact]
public void Record_PropertyInitializer_Update_NotPrimary()
{
var src1 = "record C { int X { get; } = 0; }";
var src2 = "record C { int X { get; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true));
}
[Fact]
public void Record_PropertyInitializer_Update_Primary()
{
var src1 = "record C(int X) { int X { get; } = 0; }";
var src2 = "record C(int X) { int X { get; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
}
#endregion
#region Enums
[Fact]
public void Enum_NoModifiers_Insert()
{
var src1 = "";
var src2 = "enum C { A }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Enum_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { }";
var src2 = "namespace N { enum C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Enum_NoModifiers_IntoType_Insert()
{
var src1 = "struct N { }";
var src2 = "struct N { enum C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Enum_Attribute_Insert()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "enum E { }";
var src2 = attribute + "[A]enum E { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum E { }]@48 -> [[A]enum E { }]@48");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "enum E", FeaturesResources.enum_));
}
[Fact]
public void Enum_Member_Attribute_Delete()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "enum E { [A]X }";
var src2 = attribute + "enum E { X }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]X]@57 -> [X]@57");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "X", FeaturesResources.enum_value));
}
[Fact]
public void Enum_Member_Attribute_Insert()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "enum E { X }";
var src2 = attribute + "enum E { [A]X }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [X]@57 -> [[A]X]@57");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A]X", FeaturesResources.enum_value));
}
[Fact]
public void Enum_Member_Attribute_Update()
{
var attribute = "public class A1Attribute : System.Attribute { }\n\n" +
"public class A2Attribute : System.Attribute { }\n\n";
var src1 = attribute + "enum E { [A1]X }";
var src2 = attribute + "enum E { [A2]X }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A1]X]@107 -> [[A2]X]@107");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A2]X", FeaturesResources.enum_value));
}
[Fact]
public void Enum_Member_Attribute_InsertDeleteAndUpdate()
{
var srcA1 = "";
var srcB1 = "enum N { A = 1 }";
var srcA2 = "enum N { [System.Obsolete]A = 1 }";
var srcB2 = "";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.A"))
}),
DocumentResults()
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Enum_Rename()
{
var src1 = "enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Colors { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Colors { Red = 1, Blue = 2, }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "enum Colors", FeaturesResources.enum_));
}
[Fact]
public void Enum_BaseType_Add()
{
var src1 = "enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color : ushort { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : ushort { Red = 1, Blue = 2, }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_));
}
[Fact]
public void Enum_BaseType_Add_Unchanged()
{
var src1 = "enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color : int { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : int { Red = 1, Blue = 2, }]@0");
edits.VerifySemantics();
}
[Fact]
public void Enum_BaseType_Update()
{
var src1 = "enum Color : ushort { Red = 1, Blue = 2, }";
var src2 = "enum Color : long { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color : long { Red = 1, Blue = 2, }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_));
}
[Fact]
public void Enum_BaseType_Delete_Unchanged()
{
var src1 = "enum Color : int { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color : int { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0");
edits.VerifySemantics();
}
[Fact]
public void Enum_BaseType_Delete_Changed()
{
var src1 = "enum Color : ushort { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_));
}
[Fact]
public void EnumAccessibilityChange()
{
var src1 = "public enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "enum Color", FeaturesResources.enum_));
}
[Fact]
public void EnumAccessibilityNoChange()
{
var src1 = "internal enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact]
public void EnumInitializerUpdate()
{
var src1 = "enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1, Blue = 3, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Blue = 2]@22 -> [Blue = 3]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 3", FeaturesResources.enum_value));
}
[Fact]
public void EnumInitializerUpdate2()
{
var src1 = "enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1 << 0, Blue = 2 << 1, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [Red = 1]@13 -> [Red = 1 << 0]@13",
"Update [Blue = 2]@22 -> [Blue = 2 << 1]@27");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 2 << 1", FeaturesResources.enum_value));
}
[Fact]
public void EnumInitializerUpdate3()
{
var src1 = "enum Color { Red = int.MinValue }";
var src2 = "enum Color { Red = int.MaxValue }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [Red = int.MinValue]@13 -> [Red = int.MaxValue]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "Red = int.MaxValue", FeaturesResources.enum_value));
}
[Fact]
public void EnumInitializerUpdate_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 1 }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 2 }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [Red = 1]@185 -> [Red = 2]@185");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("Color")));
}
[Fact]
public void EnumInitializerAdd()
{
var src1 = "enum Color { Red, }";
var src2 = "enum Color { Red = 1, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Red]@13 -> [Red = 1]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "Red = 1", FeaturesResources.enum_value));
}
[Fact]
public void EnumInitializerDelete()
{
var src1 = "enum Color { Red = 1, }";
var src2 = "enum Color { Red, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Red = 1]@13 -> [Red]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "Red", FeaturesResources.enum_value));
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")]
[Fact]
public void EnumMemberAdd()
{
var src1 = "enum Color { Red }";
var src2 = "enum Color { Red, Blue}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum Color { Red }]@0 -> [enum Color { Red, Blue}]@0",
"Insert [Blue]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value));
}
[Fact]
public void EnumMemberAdd2()
{
var src1 = "enum Color { Red, }";
var src2 = "enum Color { Red, Blue}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [Blue]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value));
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")]
[Fact]
public void EnumMemberAdd3()
{
var src1 = "enum Color { Red, }";
var src2 = "enum Color { Red, Blue,}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red, Blue,}]@0",
"Insert [Blue]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value));
}
[Fact]
public void EnumMemberUpdate()
{
var src1 = "enum Color { Red }";
var src2 = "enum Color { Orange }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Red]@13 -> [Orange]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "Orange", FeaturesResources.enum_value));
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")]
[Fact]
public void EnumMemberDelete()
{
var src1 = "enum Color { Red, Blue}";
var src2 = "enum Color { Red }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum Color { Red, Blue}]@0 -> [enum Color { Red }]@0",
"Delete [Blue]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue")));
}
[Fact]
public void EnumMemberDelete2()
{
var src1 = "enum Color { Red, Blue}";
var src2 = "enum Color { Red, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [Blue]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue")));
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")]
[Fact]
public void EnumTrailingCommaAdd()
{
var src1 = "enum Color { Red }";
var src2 = "enum Color { Red, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum Color { Red }]@0 -> [enum Color { Red, }]@0");
edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits);
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")]
[Fact]
public void EnumTrailingCommaAdd_WithInitializer()
{
var src1 = "enum Color { Red = 1 }";
var src2 = "enum Color { Red = 1, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum Color { Red = 1 }]@0 -> [enum Color { Red = 1, }]@0");
edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits);
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")]
[Fact]
public void EnumTrailingCommaDelete()
{
var src1 = "enum Color { Red, }";
var src2 = "enum Color { Red }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red }]@0");
edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits);
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")]
[Fact]
public void EnumTrailingCommaDelete_WithInitializer()
{
var src1 = "enum Color { Red = 1, }";
var src2 = "enum Color { Red = 1 }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color { Red = 1, }]@0 -> [enum Color { Red = 1 }]@0");
edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits);
}
#endregion
#region Delegates
[Fact]
public void Delegates_NoModifiers_Insert()
{
var src1 = "";
var src2 = "delegate void D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { }";
var src2 = "namespace N { delegate void D(); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_NoModifiers_IntoType_Insert()
{
var src1 = "class C { }";
var src2 = "class C { delegate void D(); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_Public_IntoType_Insert()
{
var src1 = "class C { }";
var src2 = "class C { public delegate void D(); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public delegate void D();]@10",
"Insert [()]@32");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_Generic_Insert()
{
var src1 = "class C { }";
var src2 = "class C { private delegate void D<T>(T a); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [private delegate void D<T>(T a);]@10",
"Insert [<T>]@33",
"Insert [(T a)]@36",
"Insert [T]@34",
"Insert [T a]@37");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_Delete()
{
var src1 = "class C { private delegate void D(); }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [private delegate void D();]@10",
"Delete [()]@33");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.delegate_, "D")));
}
[Fact]
public void Delegates_Rename()
{
var src1 = "public delegate void D();";
var src2 = "public delegate void Z();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate void D();]@0 -> [public delegate void Z();]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "public delegate void Z()", FeaturesResources.delegate_));
}
[Fact]
public void Delegates_Accessibility_Update()
{
var src1 = "public delegate void D();";
var src2 = "private delegate void D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate void D();]@0 -> [private delegate void D();]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "private delegate void D()", FeaturesResources.delegate_));
}
[Fact]
public void Delegates_ReturnType_Update()
{
var src1 = "public delegate int D();";
var src2 = "public delegate void D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D();]@0 -> [public delegate void D();]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "public delegate void D()", FeaturesResources.delegate_));
}
[Fact]
public void Delegates_ReturnType_AddAttribute()
{
var attribute = "public class A : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "[return: A]public delegate int D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D(int a);]@39 -> [[return: A]public delegate int D(int a);]@39");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Delegates_Parameter_Insert()
{
var src1 = "public delegate int D();";
var src2 = "public delegate int D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [int a]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "int a", FeaturesResources.parameter));
}
[Fact]
public void Delegates_Parameter_Insert_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D();";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D")));
}
[Fact]
public void Delegates_Parameter_Delete()
{
var src1 = "public delegate int D(int a);";
var src2 = "public delegate int D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [int a]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.parameter, "int a")));
}
[Fact]
public void Delegates_Parameter_Rename()
{
var src1 = "public delegate int D(int a);";
var src2 = "public delegate int D(int b);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@22 -> [int b]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "int b", FeaturesResources.parameter));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Delegates_Parameter_Update()
{
var src1 = "public delegate int D(int a);";
var src2 = "public delegate int D(byte a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@22 -> [byte a]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "byte a", FeaturesResources.parameter));
}
[Fact]
public void Delegates_Parameter_AddAttribute_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "public delegate int D([A]int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@70 -> [[A]int a]@70");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter));
}
[Fact]
public void Delegates_Parameter_AddAttribute()
{
var attribute = "public class A : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "public delegate int D([A]int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@61 -> [[A]int a]@61");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Delegates_TypeParameter_Insert()
{
var src1 = "public delegate int D();";
var src2 = "public delegate int D<T>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [<T>]@21",
"Insert [T]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "T", FeaturesResources.type_parameter));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")]
[WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")]
public void Delegates_TypeParameter_Insert_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D<out T>();";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D<in T, out S>(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D")));
}
[Fact]
public void Delegates_TypeParameter_Delete()
{
var src1 = "public delegate int D<T>();";
var src2 = "public delegate int D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [<T>]@21",
"Delete [T]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T")));
}
[Fact]
public void Delegates_TypeParameter_Rename()
{
var src1 = "public delegate int D<T>();";
var src2 = "public delegate int D<S>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@22 -> [S]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "S", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "S"));
}
[Fact]
public void Delegates_TypeParameter_Variance1()
{
var src1 = "public delegate int D<T>();";
var src2 = "public delegate int D<in T>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@22 -> [in T]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void Delegates_TypeParameter_Variance2()
{
var src1 = "public delegate int D<out T>();";
var src2 = "public delegate int D<T>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [out T]@22 -> [T]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void Delegates_TypeParameter_Variance3()
{
var src1 = "public delegate int D<out T>();";
var src2 = "public delegate int D<in T>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [out T]@22 -> [in T]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void Delegates_TypeParameter_AddAttribute()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D<T>();";
var src2 = attribute + "public delegate int D<[A]T>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@70 -> [[A]T]@70");
edits.VerifyRudeDiagnostics(
EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void Delegates_Attribute_Add_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "[A]public delegate int D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public delegate int D(int a)", FeaturesResources.delegate_));
}
[Fact]
public void Delegates_Attribute_Add()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "[A]public delegate int D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Delegates_Attribute_Add_WithReturnTypeAttribute()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "[return: A][A]public delegate int D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D(int a);]@48 -> [[return: A][A]public delegate int D(int a);]@48");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Delegates_ReadOnlyRef_Parameter_InsertWhole()
{
var src1 = "";
var src2 = "public delegate int D(in int b);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public delegate int D(in int b);]@0",
"Insert [(in int b)]@21",
"Insert [in int b]@22");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_ReadOnlyRef_Parameter_InsertParameter()
{
var src1 = "public delegate int D();";
var src2 = "public delegate int D(in int b);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [in int b]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter));
}
[Fact]
public void Delegates_ReadOnlyRef_Parameter_Update()
{
var src1 = "public delegate int D(int b);";
var src2 = "public delegate int D(in int b);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int b]@22 -> [in int b]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter));
}
[Fact]
public void Delegates_ReadOnlyRef_ReturnType_Insert()
{
var src1 = "";
var src2 = "public delegate ref readonly int D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public delegate ref readonly int D();]@0",
"Insert [()]@34");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_ReadOnlyRef_ReturnType_Update()
{
var src1 = "public delegate int D();";
var src2 = "public delegate ref readonly int D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D();]@0 -> [public delegate ref readonly int D();]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "public delegate ref readonly int D()", FeaturesResources.delegate_));
}
#endregion
#region Nested Types
[Fact]
public void NestedClass_ClassMove1()
{
var src1 = @"class C { class D { } }";
var src2 = @"class C { } class D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Move [class D { }]@10 -> @12");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_));
}
[Fact]
public void NestedClass_ClassMove2()
{
var src1 = @"class C { class D { } class E { } class F { } }";
var src2 = @"class C { class D { } class F { } } class E { } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Move [class E { }]@23 -> @37");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "class E", FeaturesResources.class_));
}
[Fact]
public void NestedClass_ClassInsertMove1()
{
var src1 = @"class C { class D { } }";
var src2 = @"class C { class E { class D { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [class E { class D { } }]@10",
"Move [class D { }]@10 -> @20");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_));
}
[Fact]
public void NestedClass_Insert1()
{
var src1 = @"class C { }";
var src2 = @"class C { class D { class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [class D { class E { } }]@10",
"Insert [class E { }]@20");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_Insert2()
{
var src1 = @"class C { }";
var src2 = @"class C { protected class D { public class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [protected class D { public class E { } }]@10",
"Insert [public class E { }]@30");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_Insert3()
{
var src1 = @"class C { }";
var src2 = @"class C { private class D { public class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [private class D { public class E { } }]@10",
"Insert [public class E { }]@28");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_Insert4()
{
var src1 = @"class C { }";
var src2 = @"class C { private class D { public D(int a, int b) { } public int P { get; set; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [private class D { public D(int a, int b) { } public int P { get; set; } }]@10",
"Insert [public D(int a, int b) { }]@28",
"Insert [public int P { get; set; }]@55",
"Insert [(int a, int b)]@36",
"Insert [{ get; set; }]@68",
"Insert [int a]@37",
"Insert [int b]@44",
"Insert [get;]@70",
"Insert [set;]@75");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_Insert_ReloadableIntoReloadable1()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void NestedClass_Insert_ReloadableIntoReloadable2()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void NestedClass_Insert_ReloadableIntoReloadable3()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { class D { [CreateNewOnMetadataUpdate]class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void NestedClass_Insert_ReloadableIntoReloadable4()
{
var src1 = ReloadableAttributeSrc + "class C { }";
var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D")));
}
[Fact]
public void NestedClass_Insert_Member_Reloadable()
{
var src1 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { } }";
var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { int x; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C.D")));
}
[Fact]
public void NestedClass_InsertMemberWithInitializer1()
{
var src1 = @"
class C
{
}";
var src2 = @"
class C
{
private class D
{
public int P = 1;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"), preserveLocalVariables: false)
});
}
[WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
[Fact]
public void NestedClass_Insert_PInvoke()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
}";
var src2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
abstract class D
{
public extern D();
public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; }
[DllImport(""msvcrt.dll"")]
public static extern int puts(string c);
[DllImport(""msvcrt.dll"")]
public static extern int operator +(D d, D g);
[DllImport(""msvcrt.dll"")]
public static extern explicit operator int (D d);
}
}
";
var edits = GetTopEdits(src1, src2);
// Adding P/Invoke is not supported by the CLR.
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertExtern, "public extern D()", FeaturesResources.constructor),
Diagnostic(RudeEditKind.InsertExtern, "public static extern int P", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertExtern, "public static extern int puts(string c)", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertExtern, "public static extern int operator +(D d, D g)", FeaturesResources.operator_),
Diagnostic(RudeEditKind.InsertExtern, "public static extern explicit operator int (D d)", CSharpFeaturesResources.conversion_operator));
}
[WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
[Fact]
public void NestedClass_Insert_VirtualAbstract()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
}";
var src2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
abstract class D
{
public abstract int P { get; }
public abstract int this[int i] { get; }
public abstract int puts(string c);
public virtual event Action E { add { } remove { } }
public virtual int Q { get { return 1; } }
public virtual int this[string i] { get { return 1; } }
public virtual int M(string c) { return 1; }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_TypeReorder1()
{
var src1 = @"class C { struct E { } class F { } delegate void D(); interface I {} }";
var src2 = @"class C { class F { } interface I {} delegate void D(); struct E { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [struct E { }]@10 -> @56",
"Reorder [interface I {}]@54 -> @22");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_MethodDeleteInsert()
{
var src1 = @"public class C { public void goo() {} }";
var src2 = @"public class C { private class D { public void goo() {} } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [private class D { public void goo() {} }]@17",
"Insert [public void goo() {}]@35",
"Insert [()]@50",
"Delete [public void goo() {}]@17",
"Delete [()]@32");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "public class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()")));
}
[Fact]
public void NestedClass_ClassDeleteInsert()
{
var src1 = @"public class C { public class X {} }";
var src2 = @"public class C { public class D { public class X {} } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public class D { public class X {} }]@17",
"Move [public class X {}]@17 -> @34");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "public class X", FeaturesResources.class_));
}
/// <summary>
/// A new generic type can be added whether it's nested and inherits generic parameters from the containing type, or top-level.
/// </summary>
[Fact]
public void NestedClassGeneric_Insert()
{
var src1 = @"
using System;
class C<T>
{
}
";
var src2 = @"
using System;
class C<T>
{
class D {}
struct S {}
enum N {}
interface I {}
delegate void D();
}
class D<T>
{
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedEnum_InsertMember()
{
var src1 = "struct S { enum N { A = 1 } }";
var src2 = "struct S { enum N { A = 1, B = 2 } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum N { A = 1 }]@11 -> [enum N { A = 1, B = 2 }]@11",
"Insert [B = 2]@27");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value));
}
[Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")]
public void NestedEnumInPartialType_InsertDelete()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { enum N { A = 1 } }";
var srcA2 = "partial struct S { enum N { A = 1 } }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults()
});
}
[Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")]
public void NestedEnumInPartialType_InsertDeleteAndUpdateMember()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { enum N { A = 1 } }";
var srcA2 = "partial struct S { enum N { A = 2 } }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.InitializerUpdate, "A = 2", FeaturesResources.enum_value),
}),
DocumentResults()
});
}
[Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")]
public void NestedEnumInPartialType_InsertDeleteAndUpdateBase()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { enum N : uint { A = 1 } }";
var srcA2 = "partial struct S { enum N : int { A = 1 } }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum N", FeaturesResources.enum_),
}),
DocumentResults()
});
}
[Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")]
public void NestedEnumInPartialType_InsertDeleteAndInsertMember()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { enum N { A = 1 } }";
var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value) }),
DocumentResults()
});
}
[Fact]
public void NestedDelegateInPartialType_InsertDelete()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { delegate void D(); }";
var srcA2 = "partial struct S { delegate void D(); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
// delegate does not have any user-defined method body and this does not need a PDB update
semanticEdits: NoSemanticEdits),
DocumentResults()
});
}
[Fact]
public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { delegate void D(); }";
var srcA2 = "partial struct S { delegate void D(int x); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.ChangingParameterTypes, "delegate void D(int x)", FeaturesResources.delegate_)
}),
DocumentResults()
});
}
[Fact]
public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { delegate ref int D(); }";
var srcA2 = "partial struct S { delegate ref readonly int D(); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.TypeUpdate, "delegate ref readonly int D()", FeaturesResources.delegate_)
}),
DocumentResults()
});
}
[Fact]
public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { delegate void D(int x = 1); }";
var srcA2 = "partial struct S { delegate void D(int x = 2); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter)
}),
DocumentResults()
});
}
[Fact]
public void NestedPartialTypeInPartialType_InsertDeleteAndChange()
{
var srcA1 = "partial struct S { partial class C { void F1() {} } }";
var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }";
var srcC1 = "partial struct S { }";
var srcA2 = "partial struct S { partial class C { void F1() {} } }";
var srcB2 = "partial struct S { }";
var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F2(byte x)")) }),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("S").GetMember<INamedTypeSymbol>("C").GetMember("F2")) })
});
}
[Fact]
public void Type_Partial_AddMultiple()
{
var srcA1 = "";
var srcB1 = "";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C")
}),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C")
}),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_Partial_InsertDeleteAndChange_Attribute()
{
var srcA1 = "partial class C { }";
var srcB1 = "";
var srcC1 = "partial class C { }";
var srcA2 = "";
var srcB2 = "[A]partial class C { }";
var srcC2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C")
}),
DocumentResults(),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute_NotSupportedByRuntime()
{
var srcA1 = "partial class C<T> { }";
var srcB1 = "";
var srcC1 = "partial class C<T> { }";
var srcA2 = "";
var srcB2 = "partial class C<[A]T> { }";
var srcC2 = "partial class C<T> { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<[A]T>"),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T")
}),
DocumentResults(),
});
}
[Fact]
public void Type_Partial_InsertDeleteAndChange_Constraint()
{
var srcA1 = "partial class C<T> { }";
var srcB1 = "";
var srcC1 = "partial class C<T> { }";
var srcA2 = "";
var srcB2 = "partial class C<T> where T : new() { }";
var srcC2 = "partial class C<T> { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<T>"),
Diagnostic(RudeEditKind.ChangingConstraints, "where T : new()", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : new()")
}),
DocumentResults(),
});
}
[Fact]
public void Type_Partial_InsertDeleteRefactor()
{
var srcA1 = "partial class C : I { void F() { } }";
var srcB1 = "[A][B]partial class C : J { void G() { } }";
var srcC1 = "";
var srcD1 = "";
var srcA2 = "";
var srcB2 = "";
var srcC2 = "[A]partial class C : I, J { void F() { } }";
var srcD2 = "[B]partial class C { void G() { } }";
var srcE = "interface I {} interface J {}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G")) }),
DocumentResults(),
});
}
[Fact]
public void Type_Partial_Attribute_AddMultiple()
{
var attributes = @"
class A : System.Attribute {}
class B : System.Attribute {}
";
var srcA1 = "partial class C { }" + attributes;
var srcB1 = "partial class C { }";
var srcA2 = "[A]partial class C { }" + attributes;
var srcB2 = "[B]partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C")
}),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C")
}),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting()
{
var srcA1 = "partial class C { void F() { } }";
var srcB1 = "[A,B]partial class C { void G() { } }";
var srcC1 = "";
var srcD1 = "";
var srcA2 = "";
var srcB2 = "";
var srcC2 = "[A]partial class C { void F() { } }";
var srcD2 = "[B]partial class C { void G() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"))
}),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))
}),
});
}
[Fact]
public void Type_Partial_InsertDeleteChangeMember()
{
var srcA1 = "partial class C { void F(int y = 1) { } }";
var srcB1 = "partial class C { void G(int x = 1) { } }";
var srcC1 = "";
var srcA2 = "";
var srcB2 = "partial class C { void G(int x = 2) { } }";
var srcC2 = "partial class C { void F(int y = 2) { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }),
DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int y = 2", FeaturesResources.parameter) }),
});
}
[Fact]
public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual()
{
var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }";
var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }";
var srcC1 = "partial interface I { partial class C { } }";
var srcD1 = "partial interface I { partial class C { } }";
var srcE1 = "partial interface I { }";
var srcF1 = "partial interface I { }";
var srcA2 = "partial interface I { partial class C { } }";
var srcB2 = "";
var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl
var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl
var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl
var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2) },
new[]
{
// A
DocumentResults(),
// B
DocumentResults(),
// C
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F1")) }),
// D
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N1()", FeaturesResources.method) }),
// E
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }),
// F
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N2()", FeaturesResources.method) }),
});
}
#endregion
#region Namespaces
[Fact]
public void Namespace_Insert()
{
var src1 = @"";
var src2 = @"namespace C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [namespace C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_));
}
[Fact]
public void Namespace_InsertNested()
{
var src1 = @"namespace C { }";
var src2 = @"namespace C { namespace D { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [namespace D { }]@14");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "namespace D", FeaturesResources.namespace_));
}
[Fact]
public void Namespace_DeleteNested()
{
var src1 = @"namespace C { namespace D { } }";
var src2 = @"namespace C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [namespace D { }]@14");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "namespace C", FeaturesResources.namespace_));
}
[Fact]
public void Namespace_Move()
{
var src1 = @"namespace C { namespace D { } }";
var src2 = @"namespace C { } namespace D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Move [namespace D { }]@14 -> @16");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "namespace D", FeaturesResources.namespace_));
}
[Fact]
public void Namespace_Reorder1()
{
var src1 = @"namespace C { namespace D { } class T { } namespace E { } }";
var src2 = @"namespace C { namespace E { } class T { } namespace D { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [class T { }]@30 -> @30",
"Reorder [namespace E { }]@42 -> @14");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Namespace_Reorder2()
{
var src1 = @"namespace C { namespace D1 { } namespace D2 { } namespace D3 { } class T { } namespace E { } }";
var src2 = @"namespace C { namespace E { } class T { } namespace D1 { } namespace D2 { } namespace D3 { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [class T { }]@65 -> @65",
"Reorder [namespace E { }]@77 -> @14");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Namespace_FileScoped_Insert()
{
var src1 = @"";
var src2 = @"namespace C;";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [namespace C;]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_));
}
[Fact]
public void Namespace_FileScoped_Delete()
{
var src1 = @"namespace C;";
var src2 = @"";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [namespace C;]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_));
}
#endregion
#region Members
[Fact]
public void PartialMember_DeleteInsert_SingleDocument()
{
var src1 = @"
using System;
partial class C
{
void M() {}
int P1 { get; set; }
int P2 { get => 1; set {} }
int this[int i] { get => 1; set {} }
int this[byte i] { get => 1; set {} }
event Action E { add {} remove {} }
event Action EF;
int F1;
int F2;
}
partial class C
{
}
";
var src2 = @"
using System;
partial class C
{
}
partial class C
{
void M() {}
int P1 { get; set; }
int P2 { get => 1; set {} }
int this[int i] { get => 1; set {} }
int this[byte i] { get => 1; set {} }
event Action E { add {} remove {} }
event Action EF;
int F1, F2;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [void M() {}]@68",
"Insert [int P1 { get; set; }]@85",
"Insert [int P2 { get => 1; set {} }]@111",
"Insert [int this[int i] { get => 1; set {} }]@144",
"Insert [int this[byte i] { get => 1; set {} }]@186",
"Insert [event Action E { add {} remove {} }]@229",
"Insert [event Action EF;]@270",
"Insert [int F1, F2;]@292",
"Insert [()]@74",
"Insert [{ get; set; }]@92",
"Insert [{ get => 1; set {} }]@118",
"Insert [[int i]]@152",
"Insert [{ get => 1; set {} }]@160",
"Insert [[byte i]]@194",
"Insert [{ get => 1; set {} }]@203",
"Insert [{ add {} remove {} }]@244",
"Insert [Action EF]@276",
"Insert [int F1, F2]@292",
"Insert [get;]@94",
"Insert [set;]@99",
"Insert [get => 1;]@120",
"Insert [set {}]@130",
"Insert [int i]@153",
"Insert [get => 1;]@162",
"Insert [set {}]@172",
"Insert [byte i]@195",
"Insert [get => 1;]@205",
"Insert [set {}]@215",
"Insert [add {}]@246",
"Insert [remove {}]@253",
"Insert [EF]@283",
"Insert [F1]@296",
"Insert [F2]@300",
"Delete [void M() {}]@43",
"Delete [()]@49",
"Delete [int P1 { get; set; }]@60",
"Delete [{ get; set; }]@67",
"Delete [get;]@69",
"Delete [set;]@74",
"Delete [int P2 { get => 1; set {} }]@86",
"Delete [{ get => 1; set {} }]@93",
"Delete [get => 1;]@95",
"Delete [set {}]@105",
"Delete [int this[int i] { get => 1; set {} }]@119",
"Delete [[int i]]@127",
"Delete [int i]@128",
"Delete [{ get => 1; set {} }]@135",
"Delete [get => 1;]@137",
"Delete [set {}]@147",
"Delete [int this[byte i] { get => 1; set {} }]@161",
"Delete [[byte i]]@169",
"Delete [byte i]@170",
"Delete [{ get => 1; set {} }]@178",
"Delete [get => 1;]@180",
"Delete [set {}]@190",
"Delete [event Action E { add {} remove {} }]@204",
"Delete [{ add {} remove {} }]@219",
"Delete [add {}]@221",
"Delete [remove {}]@228",
"Delete [event Action EF;]@245",
"Delete [Action EF]@251",
"Delete [EF]@258",
"Delete [int F1;]@267",
"Delete [int F1]@267",
"Delete [F1]@271",
"Delete [int F2;]@280",
"Delete [int F2]@280",
"Delete [F2]@284");
EditAndContinueValidation.VerifySemantics(
new[] { edits },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").SetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").SetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").SetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod, preserveLocalVariables: false),
})
});
}
[Fact]
public void PartialMember_InsertDelete_MultipleDocuments()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { void F() {} }";
var srcA2 = "partial class C { void F() {} }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"), preserveLocalVariables: false)
}),
DocumentResults()
});
}
[Fact]
public void PartialMember_DeleteInsert_MultipleDocuments()
{
var srcA1 = "partial class C { void F() {} }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { void F() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"), preserveLocalVariables: false)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_GenericMethod()
{
var srcA1 = "partial class C { void F<T>() {} }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { void F<T>() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<T>()"),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T")
})
});
}
[Fact]
public void PartialMember_DeleteInsert_GenericType()
{
var srcA1 = "partial class C<T> { void F() {} }";
var srcB1 = "partial class C<T> { }";
var srcA2 = "partial class C<T> { }";
var srcB2 = "partial class C<T> { void F() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()")
})
});
}
[Fact]
public void PartialMember_DeleteInsert_Destructor()
{
var srcA1 = "partial class C { ~C() {} }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { ~C() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("Finalize"), preserveLocalVariables: false),
})
});
}
[Fact]
public void PartialNestedType_InsertDeleteAndChange()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { class D { void M() {} } interface I { } }";
var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class D", FeaturesResources.class_),
}),
DocumentResults()
});
}
[Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")]
public void PartialMember_RenameInsertDelete()
{
// The syntactic analysis for A and B produce rename edits since it doesn't see that the member was in fact moved.
// TODO: Currently, we don't even pass rename edits to semantic analysis where we could handle them as updates.
var srcA1 = "partial class C { void F1() {} }";
var srcB1 = "partial class C { void F2() {} }";
var srcA2 = "partial class C { void F2() {} }";
var srcB2 = "partial class C { void F1() {} }";
// current outcome:
GetTopEdits(srcA1, srcA2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F2()", FeaturesResources.method));
GetTopEdits(srcB1, srcB2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F1()", FeaturesResources.method));
// correct outcome:
//EditAndContinueValidation.VerifySemantics(
// new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
// new[]
// {
// DocumentResults(semanticEdits: new[]
// {
// SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")),
// }),
// DocumentResults(
// semanticEdits: new[]
// {
// SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F1")),
// })
// });
}
[Fact]
public void PartialMember_DeleteInsert_UpdateMethodBodyError()
{
var srcA1 = @"
using System.Collections.Generic;
partial class C
{
IEnumerable<int> F() { yield return 1; }
}
";
var srcB1 = @"
using System.Collections.Generic;
partial class C
{
}
";
var srcA2 = @"
using System.Collections.Generic;
partial class C
{
}
";
var srcB2 = @"
using System.Collections.Generic;
partial class C
{
IEnumerable<int> F() { yield return 1; yield return 2; }
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(diagnostics: new[]
{
Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_UpdatePropertyAccessors()
{
var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_UpdateAutoProperty()
{
var srcA1 = "partial class C { int P => 1; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int P => 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_AddFieldInitializer()
{
var srcA1 = "partial class C { int f; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int f = 1; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_RemoveFieldInitializer()
{
var srcA1 = "partial class C { int f = 1; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int f; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_ConstructorWithInitializers()
{
var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { int f = 1; }";
var srcB2 = "partial class C { C(int x) { f = x + 1; } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_MethodAddParameter()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { void F() {} }";
var srcA2 = "partial struct S { void F(int x) {} }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F"))
}),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()"))
})
});
}
[Fact]
public void PartialMember_DeleteInsert_UpdateMethodParameterType()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { void F(int x); }";
var srcA2 = "partial struct S { void F(byte x); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F"))
}),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F(int x)"))
})
});
}
[Fact]
public void PartialMember_DeleteInsert_MethodAddTypeParameter()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { void F(); }";
var srcA2 = "partial struct S { void F<T>(); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.InsertGenericMethod, "void F<T>()", FeaturesResources.method)
}),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()"))
})
});
}
#endregion
#region Methods
[Theory]
[InlineData("static")]
[InlineData("virtual")]
[InlineData("abstract")]
[InlineData("override")]
[InlineData("sealed override", "override")]
public void Method_Modifiers_Update(string oldModifiers, string newModifiers = "")
{
if (oldModifiers != "")
{
oldModifiers += " ";
}
if (newModifiers != "")
{
newModifiers += " ";
}
var src1 = "class C { " + oldModifiers + "int F() => 0; }";
var src2 = "class C { " + newModifiers + "int F() => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [" + oldModifiers + "int F() => 0;]@10 -> [" + newModifiers + "int F() => 0;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F()", FeaturesResources.method));
}
[Fact]
public void Method_NewModifier_Add()
{
var src1 = "class C { int F() => 0; }";
var src2 = "class C { new int F() => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [int F() => 0;]@10 -> [new int F() => 0;]@10");
// Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving.
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")));
}
[Fact]
public void Method_NewModifier_Remove()
{
var src1 = "class C { new int F() => 0; }";
var src2 = "class C { int F() => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [new int F() => 0;]@10 -> [int F() => 0;]@10");
// Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving.
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")));
}
[Fact]
public void Method_ReadOnlyModifier_Add_InMutableStruct()
{
var src1 = @"
struct S
{
public int M() => 1;
}";
var src2 = @"
struct S
{
public readonly int M() => 1;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly int M()", FeaturesResources.method));
}
[Fact]
public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1()
{
var src1 = @"
readonly struct S
{
public int M()
=> 1;
}";
var src2 = @"
readonly struct S
{
public readonly int M()
=> 1;
}";
var edits = GetTopEdits(src1, src2);
// Currently, an edit is produced eventhough the body nor IsReadOnly attribute have changed. Consider improving.
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IMethodSymbol>("M")));
}
[Fact]
public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2()
{
var src1 = @"
readonly struct S
{
public int M() => 1;
}";
var src2 = @"
struct S
{
public readonly int M() => 1;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct"));
}
[Fact]
public void Method_AsyncModifier_Remove()
{
var src1 = @"
class Test
{
public async Task<int> WaitAsync()
{
return 1;
}
}";
var src2 = @"
class Test
{
public Task<int> WaitAsync()
{
return Task.FromResult(1);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task<int> WaitAsync()", FeaturesResources.method));
}
[Fact]
public void Method_AsyncModifier_Add()
{
var src1 = @"
class Test
{
public Task<int> WaitAsync()
{
return 1;
}
}";
var src2 = @"
class Test
{
public async Task<int> WaitAsync()
{
await Task.Delay(1000);
return 1;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
VerifyPreserveLocalVariables(edits, preserveLocalVariables: false);
}
[Fact]
public void Method_AsyncModifier_Add_NotSupported()
{
var src1 = @"
class Test
{
public Task<int> WaitAsync()
{
return 1;
}
}";
var src2 = @"
class Test
{
public async Task<int> WaitAsync()
{
await Task.Delay(1000);
return 1;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.MakeMethodAsync, "public async Task<int> WaitAsync()"));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("object", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Method_ReturnType_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C { " + oldType + " M() => default; }";
var src2 = "class C { " + newType + " M() => default; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Method_ReturnType_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C { " + oldType + " M() => default; }";
var src2 = "class C { " + newType + " M() => default; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, newType + " M()", FeaturesResources.method));
}
[Fact]
public void Method_Update()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
System.Console.WriteLine(a + b);
}
}
";
var src2 = @"
class C
{
static void Main(string[] args)
{
int b = 2;
int a = 1;
System.Console.WriteLine(a + b);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Update [static void Main(string[] args)
{
int a = 1;
int b = 2;
System.Console.WriteLine(a + b);
}]@18 -> [static void Main(string[] args)
{
int b = 2;
int a = 1;
System.Console.WriteLine(a + b);
}]@18");
edits.VerifyRudeDiagnostics();
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) });
}
[Fact]
public void MethodWithExpressionBody_Update()
{
var src1 = @"
class C
{
static int Main(string[] args) => F(1);
static int F(int a) => 1;
}
";
var src2 = @"
class C
{
static int Main(string[] args) => F(2);
static int F(int a) => 1;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Update [static int Main(string[] args) => F(1);]@18 -> [static int Main(string[] args) => F(2);]@18");
edits.VerifyRudeDiagnostics();
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) });
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void MethodWithExpressionBody_Update_LiftedParameter()
{
var src1 = @"
using System;
class C
{
int M(int a) => new Func<int>(() => a + 1)();
}
";
var src2 = @"
using System;
class C
{
int M(int a) => new Func<int>(() => 2)(); // not capturing a anymore
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int M(int a) => new Func<int>(() => a + 1)();]@35 -> [int M(int a) => new Func<int>(() => 2)();]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a"));
}
[Fact]
public void MethodWithExpressionBody_ToBlockBody()
{
var src1 = "class C { static int F(int a) => 1; }";
var src2 = "class C { static int F(int a) { return 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [static int F(int a) => 1;]@10 -> [static int F(int a) { return 2; }]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false)
});
}
[Fact]
public void MethodWithBlockBody_ToExpressionBody()
{
var src1 = "class C { static int F(int a) { return 2; } }";
var src2 = "class C { static int F(int a) => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [static int F(int a) { return 2; }]@10 -> [static int F(int a) => 1;]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false)
});
}
[Fact]
public void MethodWithLambda_Update()
{
var src1 = @"
using System;
class C
{
static void F()
{
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
}
}
";
var src2 = @"
using System;
class C
{
static void F()
{
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
Console.WriteLine(1);
}
}";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap[0]) });
}
[Fact]
public void MethodUpdate_LocalVariableDeclaration()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
int x = 1;
Console.WriteLine(x);
}
}
";
var src2 = @"
class C
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(x);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Update [static void Main(string[] args)
{
int x = 1;
Console.WriteLine(x);
}]@18 -> [static void Main(string[] args)
{
int x = 2;
Console.WriteLine(x);
}]@18");
}
[Fact]
public void Method_Delete()
{
var src1 = @"
class C
{
void goo() { }
}
";
var src2 = @"
class C
{
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [void goo() { }]@18",
"Delete [()]@26");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()")));
}
[Fact]
public void MethodWithExpressionBody_Delete()
{
var src1 = @"
class C
{
int goo() => 1;
}
";
var src2 = @"
class C
{
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [int goo() => 1;]@18",
"Delete [()]@25");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()")));
}
[WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")]
[Fact]
public void MethodDelete_WithParameterAndAttribute()
{
var src1 = @"
class C
{
[Obsolete]
void goo(int a) { }
}
";
var src2 = @"
class C
{
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Delete [[Obsolete]
void goo(int a) { }]@18",
"Delete [(int a)]@42",
"Delete [int a]@43");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo(int a)")));
}
[WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")]
[Fact]
public void MethodDelete_PInvoke()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int puts(string c);
}
";
var src2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Delete [[DllImport(""msvcrt.dll"")]
public static extern int puts(string c);]@74",
"Delete [(string c)]@134",
"Delete [string c]@135");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)")));
}
[Fact]
public void MethodInsert_NotSupportedByRuntime()
{
var src1 = "class C { }";
var src2 = "class C { void goo() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "void goo()", FeaturesResources.method));
}
[Fact]
public void PrivateMethodInsert()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
Console.ReadLine();
}
}";
var src2 = @"
class C
{
void goo() { }
static void Main(string[] args)
{
Console.ReadLine();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [void goo() { }]@18",
"Insert [()]@26");
edits.VerifyRudeDiagnostics();
}
[WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")]
[Fact]
public void PrivateMethodInsert_WithParameters()
{
var src1 = @"
using System;
class C
{
static void Main(string[] args)
{
Console.ReadLine();
}
}";
var src2 = @"
using System;
class C
{
void goo(int a) { }
static void Main(string[] args)
{
Console.ReadLine();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [void goo(int a) { }]@35",
"Insert [(int a)]@43",
"Insert [int a]@44");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.goo")) });
}
[WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")]
[Fact]
public void PrivateMethodInsert_WithAttribute()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
Console.ReadLine();
}
}";
var src2 = @"
class C
{
[System.Obsolete]
void goo(int a) { }
static void Main(string[] args)
{
Console.ReadLine();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Insert [[System.Obsolete]
void goo(int a) { }]@18",
"Insert [(int a)]@49",
"Insert [int a]@50");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodInsert_Virtual()
{
var src1 = @"
class C
{
}";
var src2 = @"
class C
{
public virtual void F() {}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertVirtual, "public virtual void F()", FeaturesResources.method));
}
[Fact]
public void MethodInsert_Abstract()
{
var src1 = @"
abstract class C
{
}";
var src2 = @"
abstract class C
{
public abstract void F();
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertVirtual, "public abstract void F()", FeaturesResources.method));
}
[Fact]
public void MethodInsert_Override()
{
var src1 = @"
class C
{
}";
var src2 = @"
class C
{
public override void F() { }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertVirtual, "public override void F()", FeaturesResources.method));
}
[WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
[Fact]
public void ExternMethodInsert()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
}";
var src2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
private static extern int puts(string c);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Insert [[DllImport(""msvcrt.dll"")]
private static extern int puts(string c);]@74",
"Insert [(string c)]@135",
"Insert [string c]@136");
// CLR doesn't support methods without a body
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertExtern, "private static extern int puts(string c)", FeaturesResources.method));
}
[Fact]
[WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
public void ExternMethodDeleteInsert()
{
var srcA1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
private static extern int puts(string c);
}";
var srcA2 = @"
using System;
using System.Runtime.InteropServices;
";
var srcB1 = @"
using System;
using System.Runtime.InteropServices;
";
var srcB2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
private static extern int puts(string c);
}
";
// TODO: The method does not need to be updated since there are no sequence points generated for it.
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")),
})
});
}
[Fact]
[WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
public void ExternMethod_Attribute_DeleteInsert()
{
var srcA1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
private static extern int puts(string c);
}";
var srcA2 = @"
using System;
using System.Runtime.InteropServices;
";
var srcB1 = @"
using System;
using System.Runtime.InteropServices;
";
var srcB2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
[Obsolete]
private static extern int puts(string c);
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")),
})
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void MethodReorder1()
{
var src1 = "class C { void f(int a, int b) { a = b; } void g() { } }";
var src2 = "class C { void g() { } void f(int a, int b) { a = b; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Reorder [void g() { }]@42 -> @10");
}
[Fact]
public void MethodInsertDelete1()
{
var src1 = "class C { class D { } void f(int a, int b) { a = b; } }";
var src2 = "class C { class D { void f(int a, int b) { a = b; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [void f(int a, int b) { a = b; }]@20",
"Insert [(int a, int b)]@26",
"Insert [int a]@27",
"Insert [int b]@34",
"Delete [void f(int a, int b) { a = b; }]@22",
"Delete [(int a, int b)]@28",
"Delete [int a]@29",
"Delete [int b]@36");
}
[Fact]
public void MethodUpdate_AddParameter()
{
var src1 = @"
class C
{
static void Main()
{
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [string[] args]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "string[] args", FeaturesResources.parameter));
}
[Fact]
public void MethodUpdate_UpdateParameter()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
}
}";
var src2 = @"
class C
{
static void Main(string[] b)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [string[] args]@35 -> [string[] b]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void MethodUpdate_UpdateParameterAndBody()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
}
}";
var src2 = @"
class C
{
static void Main(string[] b)
{
System.Console.Write(1);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Method_Name_Update()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
}
}";
var src2 = @"
class C
{
static void EntryPoint(string[] args)
{
}
}";
var edits = GetTopEdits(src1, src2);
var expectedEdit = @"Update [static void Main(string[] args)
{
}]@18 -> [static void EntryPoint(string[] args)
{
}]@18";
edits.VerifyEdits(expectedEdit);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "static void EntryPoint(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_AsyncMethod0()
{
var src1 = @"
class Test
{
public async Task<int> WaitAsync()
{
await Task.Delay(1000);
return 1;
}
}";
var src2 = @"
class Test
{
public async Task<int> WaitAsync()
{
await Task.Delay(500);
return 1;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
VerifyPreserveLocalVariables(edits, preserveLocalVariables: true);
}
[Fact]
public void MethodUpdate_AsyncMethod1()
{
var src1 = @"
class Test
{
static void Main(string[] args)
{
Test f = new Test();
string result = f.WaitAsync().Result;
}
public async Task<string> WaitAsync()
{
await Task.Delay(1000);
return ""Done"";
}
}";
var src2 = @"
class Test
{
static void Main(string[] args)
{
Test f = new Test();
string result = f.WaitAsync().Result;
}
public async Task<string> WaitAsync()
{
await Task.Delay(1000);
return ""Not Done"";
}
}";
var edits = GetTopEdits(src1, src2);
var expectedEdit = @"Update [public async Task<string> WaitAsync()
{
await Task.Delay(1000);
return ""Done"";
}]@151 -> [public async Task<string> WaitAsync()
{
await Task.Delay(1000);
return ""Not Done"";
}]@151";
edits.VerifyEdits(expectedEdit);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_AddReturnTypeAttribute()
{
var src1 = @"
using System;
class Test
{
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[return: Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(@"Update [static void Main(string[] args)
{
System.Console.Write(5);
}]@38 -> [[return: Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}]@38");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_AddAttribute()
{
var src1 = @"
using System;
class Test
{
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(@"Update [static void Main(string[] args)
{
System.Console.Write(5);
}]@38 -> [[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}]@38");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_AddAttribute_SupportedByRuntime()
{
var src1 = @"
using System;
class Test
{
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(@"Update [static void Main(string[] args)
{
System.Console.Write(5);
}]@38 -> [[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}]@38");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Test.Main")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void MethodUpdate_Attribute_ArrayParameter()
{
var src1 = @"
class AAttribute : System.Attribute
{
public AAttribute(int[] nums) { }
}
class C
{
[A(new int[] { 1, 2, 3})]
void M()
{
}
}";
var src2 = @"
class AAttribute : System.Attribute
{
public AAttribute(int[] nums) { }
}
class C
{
[A(new int[] { 4, 5, 6})]
void M()
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void MethodUpdate_Attribute_ArrayParameter_NoChange()
{
var src1 = @"
class AAttribute : System.Attribute
{
public AAttribute(int[] nums) { }
}
class C
{
[A(new int[] { 1, 2, 3})]
void M()
{
var x = 1;
}
}";
var src2 = @"
class AAttribute : System.Attribute
{
public AAttribute(int[] nums) { }
}
class C
{
[A(new int[] { 1, 2, 3})]
void M()
{
var x = 2;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) });
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_AddAttribute2()
{
var src1 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete, STAThread]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_AddAttribute3()
{
var src1 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete]
[STAThread]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_AddAttribute4()
{
var src1 = @"
using System;
class Test
{
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete, STAThread]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_UpdateAttribute()
{
var src1 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete("""")]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")]
[Fact]
public void MethodUpdate_DeleteAttribute()
{
var src1 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_DeleteAttribute2()
{
var src1 = @"
using System;
class Test
{
[Obsolete, STAThread]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_DeleteAttribute3()
{
var src1 = @"
using System;
class Test
{
[Obsolete]
[STAThread]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_ExplicitlyImplemented1()
{
var src1 = @"
class C : I, J
{
void I.Goo() { Console.WriteLine(2); }
void J.Goo() { Console.WriteLine(1); }
}";
var src2 = @"
class C : I, J
{
void I.Goo() { Console.WriteLine(1); }
void J.Goo() { Console.WriteLine(2); }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void I.Goo() { Console.WriteLine(2); }]@25 -> [void I.Goo() { Console.WriteLine(1); }]@25",
"Update [void J.Goo() { Console.WriteLine(1); }]@69 -> [void J.Goo() { Console.WriteLine(2); }]@69");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_ExplicitlyImplemented2()
{
var src1 = @"
class C : I, J
{
void I.Goo() { Console.WriteLine(1); }
void J.Goo() { Console.WriteLine(2); }
}";
var src2 = @"
class C : I, J
{
void Goo() { Console.WriteLine(1); }
void J.Goo() { Console.WriteLine(2); }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void I.Goo() { Console.WriteLine(1); }]@25 -> [void Goo() { Console.WriteLine(1); }]@25");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "void Goo()", FeaturesResources.method));
}
[WorkItem(754255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754255")]
[Fact]
public void MethodUpdate_UpdateStackAlloc()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
int i = 10;
unsafe
{
int* px2 = &i;
}
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
int i = 10;
unsafe
{
char* buffer = stackalloc char[16];
int* px2 = &i;
}
}
}";
var expectedEdit = @"Update [static void Main(string[] args)
{
int i = 10;
unsafe
{
int* px2 = &i;
}
}]@18 -> [static void Main(string[] args)
{
int i = 10;
unsafe
{
char* buffer = stackalloc char[16];
int* px2 = &i;
}
}]@18";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(expectedEdit);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method));
}
[Theory]
[InlineData("stackalloc int[3]")]
[InlineData("stackalloc int[3] { 1, 2, 3 }")]
[InlineData("stackalloc int[] { 1, 2, 3 }")]
[InlineData("stackalloc[] { 1, 2, 3 }")]
public void MethodUpdate_UpdateStackAlloc2(string stackallocDecl)
{
var src1 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 1; } }";
var src2 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_UpdateStackAllocInLambda1()
{
var src1 = "unsafe class C { void M() { F(1, () => { int* a = stackalloc int[10]; }); } }";
var src2 = "unsafe class C { void M() { F(2, () => { int* a = stackalloc int[10]; }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateStackAllocInLambda2()
{
var src1 = "unsafe class C { void M() { F(1, x => { int* a = stackalloc int[10]; }); } }";
var src2 = "unsafe class C { void M() { F(2, x => { int* a = stackalloc int[10]; }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateStackAllocInAnonymousMethod()
{
var src1 = "unsafe class C { void M() { F(1, delegate(int x) { int* a = stackalloc int[10]; }); } }";
var src2 = "unsafe class C { void M() { F(2, delegate(int x) { int* a = stackalloc int[10]; }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateStackAllocInLocalFunction()
{
var src1 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(1); } }";
var src2 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(2); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_SwitchExpressionInLambda1()
{
var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }";
var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_SwitchExpressionInLambda2()
{
var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }";
var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_SwitchExpressionInAnonymousMethod()
{
var src1 = "class C { void M() { F(1, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }";
var src2 = "class C { void M() { F(2, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_SwitchExpressionInLocalFunction()
{
var src1 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(1); } }";
var src2 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(2); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_SwitchExpressionInQuery()
{
var src1 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 1; } }";
var src2 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateAnonymousMethod()
{
var src1 = "class C { void M() { F(1, delegate(int a) { return a; }); } }";
var src2 = "class C { void M() { F(2, delegate(int a) { return a; }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodWithExpressionBody_Update_UpdateAnonymousMethod()
{
var src1 = "class C { void M() => F(1, delegate(int a) { return a; }); }";
var src2 = "class C { void M() => F(2, delegate(int a) { return a; }); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_Query()
{
var src1 = "class C { void M() { F(1, from goo in bar select baz); } }";
var src2 = "class C { void M() { F(2, from goo in bar select baz); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodWithExpressionBody_Update_Query()
{
var src1 = "class C { void M() => F(1, from goo in bar select baz); }";
var src2 = "class C { void M() => F(2, from goo in bar select baz); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_AnonymousType()
{
var src1 = "class C { void M() { F(1, new { A = 1, B = 2 }); } }";
var src2 = "class C { void M() { F(2, new { A = 1, B = 2 }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodWithExpressionBody_Update_AnonymousType()
{
var src1 = "class C { void M() => F(new { A = 1, B = 2 }); }";
var src2 = "class C { void M() => F(new { A = 10, B = 20 }); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_Iterator_YieldReturn()
{
var src1 = "class C { IEnumerable<int> M() { yield return 1; } }";
var src2 = "class C { IEnumerable<int> M() { yield return 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
VerifyPreserveLocalVariables(edits, preserveLocalVariables: true);
}
[Fact]
public void MethodUpdate_AddYieldReturn()
{
var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }";
var src2 = "class C { IEnumerable<int> M() { yield return 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
VerifyPreserveLocalVariables(edits, preserveLocalVariables: false);
}
[Fact]
public void MethodUpdate_AddYieldReturn_NotSupported()
{
var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }";
var src2 = "class C { IEnumerable<int> M() { yield return 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.MakeMethodIterator, "IEnumerable<int> M()"));
}
[Fact]
public void MethodUpdate_Iterator_YieldBreak()
{
var src1 = "class C { IEnumerable<int> M() { F(); yield break; } }";
var src2 = "class C { IEnumerable<int> M() { G(); yield break; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
VerifyPreserveLocalVariables(edits, preserveLocalVariables: true);
}
[WorkItem(1087305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")]
[Fact]
public void MethodUpdate_LabeledStatement()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
goto Label1;
Label1:
{
Console.WriteLine(1);
}
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
goto Label1;
Label1:
{
Console.WriteLine(2);
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_LocalFunctionsParameterRefnessInBody()
{
var src1 = @"class C { public void M(int a) { void f(ref int b) => b = 1; } }";
var src2 = @"class C { public void M(int a) { void f(out int b) => b = 1; } } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public void M(int a) { void f(ref int b) => b = 1; }]@10 -> [public void M(int a) { void f(out int b) => b = 1; }]@10");
}
[Fact]
public void MethodUpdate_LambdaParameterRefnessInBody()
{
var src1 = @"class C { public void M(int a) { f((ref int b) => b = 1); } }";
var src2 = @"class C { public void M(int a) { f((out int b) => b = 1); } } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public void M(int a) { f((ref int b) => b = 1); }]@10 -> [public void M(int a) { f((out int b) => b = 1); }]@10");
}
[Fact]
public void Method_ReadOnlyRef_Parameter_InsertWhole()
{
var src1 = "class Test { }";
var src2 = "class Test { int M(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [int M(in int b) => throw null;]@13",
"Insert [(in int b)]@18",
"Insert [in int b]@19");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Method_ReadOnlyRef_Parameter_InsertParameter()
{
var src1 = "class Test { int M() => throw null; }";
var src2 = "class Test { int M(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [in int b]@19");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter));
}
[Fact]
public void Method_ReadOnlyRef_Parameter_Update()
{
var src1 = "class Test { int M(int b) => throw null; }";
var src2 = "class Test { int M(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int b]@19 -> [in int b]@19");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter));
}
[Fact]
public void Method_ReadOnlyRef_ReturnType_Insert()
{
var src1 = "class Test { }";
var src2 = "class Test { ref readonly int M() => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [ref readonly int M() => throw null;]@13",
"Insert [()]@31");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Method_ReadOnlyRef_ReturnType_Update()
{
var src1 = "class Test { int M() => throw null; }";
var src2 = "class Test { ref readonly int M() => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int M() => throw null;]@13 -> [ref readonly int M() => throw null;]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int M()", FeaturesResources.method));
}
[Fact]
public void Method_ImplementingInterface_Add()
{
var src1 = @"
using System;
public interface ISample
{
string Get();
}
public interface IConflict
{
string Get();
}
public class BaseClass : ISample
{
public virtual string Get() => string.Empty;
}
public class SubClass : BaseClass, IConflict
{
public override string Get() => string.Empty;
}
";
var src2 = @"
using System;
public interface ISample
{
string Get();
}
public interface IConflict
{
string Get();
}
public class BaseClass : ISample
{
public virtual string Get() => string.Empty;
}
public class SubClass : BaseClass, IConflict
{
public override string Get() => string.Empty;
string IConflict.Get() => String.Empty;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [string IConflict.Get() => String.Empty;]@325",
"Insert [()]@345");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, "string IConflict.Get()", FeaturesResources.method));
}
[Fact]
public void Method_Partial_DeleteInsert_DefinitionPart()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcC1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { partial void F() { } }";
var srcC2 = "partial class C { partial void F(); }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults(),
});
}
[Fact]
public void Method_Partial_DeleteInsert_ImplementationPart()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcC1 = "partial class C { }";
var srcA2 = "partial class C { partial void F(); }";
var srcB2 = "partial class C { }";
var srcC2 = "partial class C { partial void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }),
});
}
[Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")]
public void Method_Partial_Swap_ImplementationAndDefinitionParts()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcA2 = "partial class C { partial void F() { } }";
var srcB2 = "partial class C { partial void F(); }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }),
DocumentResults(),
});
}
[Fact]
public void Method_Partial_DeleteImplementation()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcA2 = "partial class C { partial void F(); }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) })
});
}
[Fact]
public void Method_Partial_DeleteBoth()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) })
});
}
[Fact]
public void Method_Partial_DeleteInsertBoth()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcC1 = "partial class C { }";
var srcD1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { }";
var srcC2 = "partial class C { partial void F(); }";
var srcD2 = "partial class C { partial void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) })
});
}
[Fact]
public void Method_Partial_Insert()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { partial void F(); }";
var srcB2 = "partial class C { partial void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }),
});
}
[Fact]
public void Method_Partial_Insert_Reloadable()
{
var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }";
var srcB1 = "partial class C { }";
var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }";
var srcB2 = "partial class C { partial void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }),
});
}
#endregion
#region Operators
[Theory]
[InlineData("implicit", "explicit")]
[InlineData("explicit", "implicit")]
public void Operator_Modifiers_Update(string oldModifiers, string newModifiers)
{
var src1 = "class C { public static " + oldModifiers + " operator int (C c) => 0; }";
var src2 = "class C { public static " + newModifiers + " operator int (C c) => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [public static " + oldModifiers + " operator int (C c) => 0;]@10 -> [public static " + newModifiers + " operator int (C c) => 0;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public static " + newModifiers + " operator int (C c)", CSharpFeaturesResources.conversion_operator));
}
[Fact]
public void Operator_Modifiers_Update_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static implicit operator int (C c) => 0; }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static explicit operator int (C c) => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Operator_Conversion_ExternModifiers_Add()
{
var src1 = "class C { public static implicit operator bool (C c) => default; }";
var src2 = "class C { extern public static implicit operator bool (C c); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "extern public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator));
}
[Fact]
public void Operator_Conversion_ExternModifiers_Remove()
{
var src1 = "class C { extern public static implicit operator bool (C c); }";
var src2 = "class C { public static implicit operator bool (C c) => default; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator));
}
[Fact]
public void OperatorInsert()
{
var src1 = @"
class C
{
}
";
var src2 = @"
class C
{
public static implicit operator bool (C c)
{
return false;
}
public static C operator +(C c, C d)
{
return c;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertOperator, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator),
Diagnostic(RudeEditKind.InsertOperator, "public static C operator +(C c, C d)", FeaturesResources.operator_));
}
[Fact]
public void OperatorDelete()
{
var src1 = @"
class C
{
public static implicit operator bool (C c)
{
return false;
}
public static C operator +(C c, C d)
{
return c;
}
}
";
var src2 = @"
class C
{
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(CSharpFeaturesResources.conversion_operator, "implicit operator bool(C c)")),
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.operator_, "operator +(C c, C d)")));
}
[Fact]
public void OperatorInsertDelete()
{
var srcA1 = @"
partial class C
{
public static implicit operator bool (C c) => false;
}
";
var srcB1 = @"
partial class C
{
public static C operator +(C c, C d) => c;
}
";
var srcA2 = srcB1;
var srcB2 = srcA1;
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Addition"))
}),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Implicit"))
}),
});
}
[Fact]
public void OperatorUpdate()
{
var src1 = @"
class C
{
public static implicit operator bool (C c)
{
return false;
}
public static C operator +(C c, C d)
{
return c;
}
}
";
var src2 = @"
class C
{
public static implicit operator bool (C c)
{
return true;
}
public static C operator +(C c, C d)
{
return d;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")),
});
}
[Fact]
public void OperatorWithExpressionBody_Update()
{
var src1 = @"
class C
{
public static implicit operator bool (C c) => false;
public static C operator +(C c, C d) => c;
}
";
var src2 = @"
class C
{
public static implicit operator bool (C c) => true;
public static C operator +(C c, C d) => d;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")),
});
}
[Fact]
public void OperatorWithExpressionBody_ToBlockBody()
{
var src1 = "class C { public static C operator +(C c, C d) => d; }";
var src2 = "class C { public static C operator +(C c, C d) { return c; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [public static C operator +(C c, C d) => d;]@10 -> [public static C operator +(C c, C d) { return c; }]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition"))
});
}
[Fact]
public void OperatorWithBlockBody_ToExpressionBody()
{
var src1 = "class C { public static C operator +(C c, C d) { return c; } }";
var src2 = "class C { public static C operator +(C c, C d) => d; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [public static C operator +(C c, C d) { return c; }]@10 -> [public static C operator +(C c, C d) => d;]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition"))
});
}
[Fact]
public void OperatorReorder1()
{
var src1 = @"
class C
{
public static implicit operator bool (C c) { return false; }
public static implicit operator int (C c) { return 1; }
}
";
var src2 = @"
class C
{
public static implicit operator int (C c) { return 1; }
public static implicit operator bool (C c) { return false; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [public static implicit operator int (C c) { return 1; }]@84 -> @18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void OperatorReorder2()
{
var src1 = @"
class C
{
public static C operator +(C c, C d) { return c; }
public static C operator -(C c, C d) { return d; }
}
";
var src2 = @"
class C
{
public static C operator -(C c, C d) { return d; }
public static C operator +(C c, C d) { return c; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [public static C operator -(C c, C d) { return d; }]@74 -> @18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Operator_ReadOnlyRef_Parameter_InsertWhole()
{
var src1 = "class Test { }";
var src2 = "class Test { public static bool operator !(in Test b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public static bool operator !(in Test b) => throw null;]@13",
"Insert [(in Test b)]@42",
"Insert [in Test b]@43");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertOperator, "public static bool operator !(in Test b)", FeaturesResources.operator_));
}
[Fact]
public void Operator_ReadOnlyRef_Parameter_Update()
{
var src1 = "class Test { public static bool operator !(Test b) => throw null; }";
var src2 = "class Test { public static bool operator !(in Test b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Test b]@43 -> [in Test b]@43");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "in Test b", FeaturesResources.parameter));
}
#endregion
#region Constructor, Destructor
[Fact]
public void Constructor_Parameter_AddAttribute()
{
var src1 = @"
class C
{
private int x = 1;
public C(int a)
{
}
}";
var src2 = @"
class C
{
private int x = 2;
public C([System.Obsolete]int a)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [x = 1]@30 -> [x = 2]@30",
"Update [int a]@53 -> [[System.Obsolete]int a]@53");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C..ctor"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
[WorkItem(2068, "https://github.com/dotnet/roslyn/issues/2068")]
public void Constructor_ExternModifier_Add()
{
var src1 = "class C { }";
var src2 = "class C { public extern C(); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public extern C();]@10",
"Insert [()]@25");
// This can be allowed as the compiler generates an empty constructor, but it's not worth the complexity.
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public extern C()", FeaturesResources.constructor));
}
[Fact]
public void ConstructorInitializer_Update1()
{
var src1 = @"
class C
{
public C(int a) : base(a) { }
}";
var src2 = @"
class C
{
public C(int a) : base(a + 1) { }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public C(int a) : base(a) { }]@18 -> [public C(int a) : base(a + 1) { }]@18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void ConstructorInitializer_Update2()
{
var src1 = @"
class C<T>
{
public C(int a) : base(a) { }
}";
var src2 = @"
class C<T>
{
public C(int a) { }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public C(int a) : base(a) { }]@21 -> [public C(int a) { }]@21");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)"));
}
[Fact]
public void ConstructorInitializer_Update3()
{
var src1 = @"
class C
{
public C(int a) { }
}";
var src2 = @"
class C
{
public C(int a) : base(a) { }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public C(int a) { }]@18 -> [public C(int a) : base(a) { }]@18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void ConstructorInitializer_Update4()
{
var src1 = @"
class C<T>
{
public C(int a) : base(a) { }
}";
var src2 = @"
class C<T>
{
public C(int a) : base(a + 1) { }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public C(int a) : base(a) { }]@21 -> [public C(int a) : base(a + 1) { }]@21");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)"));
}
[WorkItem(743552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743552")]
[Fact]
public void ConstructorUpdate_AddParameter()
{
var src1 = @"
class C
{
public C(int a) { }
}";
var src2 = @"
class C
{
public C(int a, int b) { }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int a)]@26 -> [(int a, int b)]@26",
"Insert [int b]@34");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "int b", FeaturesResources.parameter));
}
[Fact]
public void DestructorDelete()
{
var src1 = @"class B { ~B() { } }";
var src2 = @"class B { }";
var expectedEdit1 = @"Delete [~B() { }]@10";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(expectedEdit1);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()")));
}
[Fact]
public void DestructorDelete_InsertConstructor()
{
var src1 = @"class B { ~B() { } }";
var src2 = @"class B { B() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [B() { }]@10",
"Insert [()]@11",
"Delete [~B() { }]@10");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "B()", FeaturesResources.constructor),
Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()")));
}
[Fact]
[WorkItem(789577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789577")]
public void ConstructorUpdate_AnonymousTypeInFieldInitializer()
{
var src1 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 1; } }";
var src2 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Constructor_Static_Delete()
{
var src1 = "class C { static C() { } }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.static_constructor, "C()")));
}
[Fact]
public void Constructor_Static_Delete_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { static C() { } }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Constructor_Static_Insert()
{
var src1 = "class C { }";
var src2 = "class C { static C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) });
}
[Fact]
public void InstanceCtorDelete_Public()
{
var src1 = "class C { public C() { } }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("")]
[InlineData("private")]
[InlineData("protected")]
[InlineData("internal")]
[InlineData("private protected")]
[InlineData("protected internal")]
public void InstanceCtorDelete_NonPublic(string accessibility)
{
var src1 = "class C { [System.Obsolete] " + accessibility + " C() { } }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")),
Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")));
}
[Fact]
public void InstanceCtorDelete_Public_PartialWithInitializerUpdate()
{
var srcA1 = "partial class C { public C() { } }";
var srcB1 = "partial class C { int x = 1; }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int x = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) })
});
}
[Fact]
public void InstanceCtorInsert_Public_Implicit()
{
var src1 = "class C { }";
var src2 = "class C { public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void InstanceCtorInsert_Partial_Public_Implicit()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { public C() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// no change in document A
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }),
});
}
[Fact]
public void InstanceCtorInsert_Public_NoImplicit()
{
var src1 = "class C { public C(int a) { } }";
var src2 = "class C { public C(int a) { } public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty))
});
}
[Fact]
public void InstanceCtorInsert_Partial_Public_NoImplicit()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { public C(int a) { } }";
var srcA2 = "partial class C { public C() { } }";
var srcB2 = "partial class C { public C(int a) { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty))
}),
// no change in document B
DocumentResults(),
});
}
[Fact]
public void InstanceCtorInsert_Private_Implicit1()
{
var src1 = "class C { }";
var src2 = "class C { private C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "private C()", FeaturesResources.constructor));
}
[Fact]
public void InstanceCtorInsert_Private_Implicit2()
{
var src1 = "class C { }";
var src2 = "class C { C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "C()", FeaturesResources.constructor));
}
[Fact]
public void InstanceCtorInsert_Protected_PublicImplicit()
{
var src1 = "class C { }";
var src2 = "class C { protected C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "protected C()", FeaturesResources.constructor));
}
[Fact]
public void InstanceCtorInsert_Internal_PublicImplicit()
{
var src1 = "class C { }";
var src2 = "class C { internal C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor));
}
[Fact]
public void InstanceCtorInsert_Internal_ProtectedImplicit()
{
var src1 = "abstract class C { }";
var src2 = "abstract class C { internal C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor));
}
[Fact]
public void InstanceCtorUpdate_ProtectedImplicit()
{
var src1 = "abstract class C { }";
var src2 = "abstract class C { protected C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void InstanceCtorInsert_Private_NoImplicit()
{
var src1 = "class C { public C(int a) { } }";
var src2 = "class C { public C(int a) { } private C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C")
.InstanceConstructors.Single(ctor => ctor.DeclaredAccessibility == Accessibility.Private))
});
}
[Fact]
public void InstanceCtorInsert_Internal_NoImplicit()
{
var src1 = "class C { public C(int a) { } }";
var src2 = "class C { public C(int a) { } internal C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void InstanceCtorInsert_Protected_NoImplicit()
{
var src1 = "class C { public C(int a) { } }";
var src2 = "class C { public C(int a) { } protected C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void InstanceCtorInsert_InternalProtected_NoImplicit()
{
var src1 = "class C { public C(int a) { } }";
var src2 = "class C { public C(int a) { } internal protected C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void StaticCtor_Partial_DeleteInsert()
{
var srcA1 = "partial class C { static C() { } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { static C() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void InstanceCtor_Partial_DeletePrivateInsertPrivate()
{
var srcA1 = "partial class C { C() { } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { C() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void InstanceCtor_Partial_DeletePublicInsertPublic()
{
var srcA1 = "partial class C { public C() { } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { public C() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void InstanceCtor_Partial_DeletePrivateInsertPublic()
{
var srcA1 = "partial class C { C() { } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { public C() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility
DocumentResults(
semanticEdits: NoSemanticEdits),
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }),
});
}
[Fact]
public void StaticCtor_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { static C() { } }";
var srcA2 = "partial class C { static C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_InsertPublicDeletePublic()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { public C() { } }";
var srcA2 = "partial class C { public C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_InsertPrivateDeletePrivate()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { private C() { } }";
var srcA2 = "partial class C { private C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_DeleteInternalInsertInternal()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { internal C() { } }";
var srcA2 = "partial class C { internal C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_InsertInternalDeleteInternal_WithBody()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { internal C() { } }";
var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_InsertPublicDeletePrivate()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { private C() { } }";
var srcA2 = "partial class C { public C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }),
// delete of the constructor in partial part will be reported as rude in the the other document where it was inserted with changed accessibility
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_InsertInternalDeletePrivate()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { private C() { } }";
var srcA2 = "partial class C { internal C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor) }),
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_Update_LambdaInInitializer1()
{
var src1 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
public C()
{
F(<N:0.2>c => c + 1</N:0.2>);
}
}
";
var src2 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
public C()
{
F(<N:0.2>c => c + 2</N:0.2>);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void InstanceCtor_Partial_Update_LambdaInInitializer_Trivia1()
{
var src1 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
public C() { F(<N:0.2>c => c + 1</N:0.2>); }
}
";
var src2 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
/*new trivia*/public C() { F(<N:0.2>c => c + 1</N:0.2>); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void InstanceCtor_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1()
{
var src1 = @"
using System;
public interface I { int B { get; } }
public interface J { int B { get; } }
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C : I, J
{
int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>);
int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>);
public C()
{
F(<N:0.3>c => c + 1</N:0.3>);
}
}
";
var src2 = @"
using System;
public interface I { int B { get; } }
public interface J { int B { get; } }
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C : I, J
{
int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>);
int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>);
public C()
{
F(<N:0.3>c => c + 2</N:0.3>);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void InstanceCtor_Partial_Insert_Parameterless_LambdaInInitializer1()
{
var src1 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
}
";
var src2 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
public C() // new ctor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()"));
// TODO:
//var syntaxMap = GetSyntaxMap(src1, src2);
//edits.VerifySemantics(
// ActiveStatementsDescription.Empty,
// new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void InstanceCtor_Partial_Insert_WithParameters_LambdaInInitializer1()
{
var src1 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
}
";
var src2 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
public C(int x) // new ctor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
_ = GetSyntaxMap(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)"));
// TODO: bug https://github.com/dotnet/roslyn/issues/2504
//edits.VerifySemantics(
// ActiveStatementsDescription.Empty,
// new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void InstanceCtor_Partial_Explicit_Update()
{
var srcA1 = @"
using System;
partial class C
{
C(int arg) => Console.WriteLine(0);
C(bool arg) => Console.WriteLine(1);
}
";
var srcB1 = @"
using System;
partial class C
{
int a <N:0.0>= 1</N:0.0>;
C(uint arg) => Console.WriteLine(2);
}
";
var srcA2 = @"
using System;
partial class C
{
C(int arg) => Console.WriteLine(0);
C(bool arg) => Console.WriteLine(1);
}
";
var srcB2 = @"
using System;
partial class C
{
int a <N:0.0>= 2</N:0.0>; // updated field initializer
C(uint arg) => Console.WriteLine(2);
C(byte arg) => Console.WriteLine(3); // new ctor
}
";
var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0];
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// No changes in document A
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Int32"), partialType: "C", syntaxMap: syntaxMapB),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Boolean"), partialType: "C", syntaxMap: syntaxMapB),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "UInt32"), partialType: "C", syntaxMap: syntaxMapB),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Byte"), syntaxMap: null),
})
});
}
[Fact]
public void InstanceCtor_Partial_Explicit_Update_SemanticError()
{
var srcA1 = @"
using System;
partial class C
{
C(int arg) => Console.WriteLine(0);
C(int arg) => Console.WriteLine(1);
}
";
var srcB1 = @"
using System;
partial class C
{
int a = 1;
}
";
var srcA2 = @"
using System;
partial class C
{
C(int arg) => Console.WriteLine(0);
C(int arg) => Console.WriteLine(1);
}
";
var srcB2 = @"
using System;
partial class C
{
int a = 2;
C(int arg) => Console.WriteLine(2);
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// No changes in document A
DocumentResults(),
// The actual edits do not matter since there are semantic errors in the compilation.
// We just should not crash.
DocumentResults(diagnostics: Array.Empty<RudeEditDiagnosticDescription>())
});
}
[Fact]
public void InstanceCtor_Partial_Implicit_Update()
{
var srcA1 = "partial class C { int F = 1; }";
var srcB1 = "partial class C { int G = 1; }";
var srcA2 = "partial class C { int F = 2; }";
var srcB2 = "partial class C { int G = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void ParameterlessConstructor_SemanticError_Delete1()
{
var src1 = @"
class C
{
D() {}
}
";
var src2 = @"
class C
{
}
";
var edits = GetTopEdits(src1, src2);
// The compiler interprets D() as a constructor declaration.
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")));
}
[Fact]
public void Constructor_SemanticError_Partial()
{
var src1 = @"
partial class C
{
partial void C(int x);
}
partial class C
{
partial void C(int x)
{
System.Console.WriteLine(1);
}
}
";
var src2 = @"
partial class C
{
partial void C(int x);
}
partial class C
{
partial void C(int x)
{
System.Console.WriteLine(2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("C").PartialImplementationPart)
});
}
[Fact]
public void PartialDeclaration_Delete()
{
var srcA1 = "partial class C { public C() { } void F() { } }";
var srcB1 = "partial class C { int x = 1; }";
var srcA2 = "";
var srcB2 = "partial class C { int x = 2; void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void PartialDeclaration_Insert()
{
var srcA1 = "";
var srcB1 = "partial class C { int x = 1; void F() { } }";
var srcA2 = "partial class C { public C() { } void F() { } }";
var srcB2 = "partial class C { int x = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }),
});
}
[Fact]
public void PartialDeclaration_Insert_Reloadable()
{
var srcA1 = "";
var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }";
var srcA2 = "partial class C { public C() { } void F() { } }";
var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")
}),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")
}),
});
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void Constructor_DeleteParameterless(string typeKind)
{
var src1 = @"
" + typeKind + @" C
{
private int a = 10;
private int b;
public C() { b = 3; }
}
";
var src2 = @"
" + typeKind + @" C
{
private int a = 10;
private int b;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [public C() { b = 3; }]@66", "Delete [()]@74");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void Constructor_InsertParameterless(string typeKind)
{
var src1 = @"
" + typeKind + @" C
{
private int a = 10;
private int b;
}
";
var src2 = @"
" + typeKind + @" C
{
private int a = 10;
private int b;
public C() { b = 3; }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [public C() { b = 3; }]@66", "Insert [()]@74");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Constructor_BlockBodyToExpressionBody()
{
var src1 = @"
public class C
{
private int _value;
public C(int value) { _value = value; }
}
";
var src2 = @"
public class C
{
private int _value;
public C(int value) => _value = value;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void ConstructorWithInitializer_BlockBodyToExpressionBody()
{
var src1 = @"
public class B { B(int value) {} }
public class C : B
{
private int _value;
public C(int value) : base(value) { _value = value; }
}
";
var src2 = @"
public class B { B(int value) {} }
public class C : B
{
private int _value;
public C(int value) : base(value) => _value = value;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Constructor_ExpressionBodyToBlockBody()
{
var src1 = @"
public class C
{
private int _value;
public C(int value) => _value = value;
}
";
var src2 = @"
public class C
{
private int _value;
public C(int value) { _value = value; }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void ConstructorWithInitializer_ExpressionBodyToBlockBody()
{
var src1 = @"
public class B { B(int value) {} }
public class C : B
{
private int _value;
public C(int value) : base(value) => _value = value;
}
";
var src2 = @"
public class B { B(int value) {} }
public class C : B
{
private int _value;
public C(int value) : base(value) { _value = value; }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Destructor_BlockBodyToExpressionBody()
{
var src1 = @"
public class C
{
~C() { Console.WriteLine(0); }
}
";
var src2 = @"
public class C
{
~C() => Console.WriteLine(0);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Destructor_ExpressionBodyToBlockBody()
{
var src1 = @"
public class C
{
~C() => Console.WriteLine(0);
}
";
var src2 = @"
public class C
{
~C() { Console.WriteLine(0); }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false)
});
}
[Fact]
public void Constructor_ReadOnlyRef_Parameter_InsertWhole()
{
var src1 = "class Test { }";
var src2 = "class Test { Test(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [Test(in int b) => throw null;]@13",
"Insert [(in int b)]@17",
"Insert [in int b]@18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Constructor_ReadOnlyRef_Parameter_InsertParameter()
{
var src1 = "class Test { Test() => throw null; }";
var src2 = "class Test { Test(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [in int b]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter));
}
[Fact]
public void Constructor_ReadOnlyRef_Parameter_Update()
{
var src1 = "class Test { Test(int b) => throw null; }";
var src2 = "class Test { Test(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int b]@18 -> [in int b]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter));
}
#endregion
#region Fields and Properties with Initializers
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void FieldInitializer_Update1(string typeKind)
{
var src1 = typeKind + " C { int a = 0; }";
var src2 = typeKind + " C { int a = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 0]@15 -> [a = 1]@15");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void PropertyInitializer_Update1(string typeKind)
{
var src1 = typeKind + " C { int a { get; } = 0; }";
var src2 = typeKind + " C { int a { get; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a { get; } = 0;]@11 -> [int a { get; } = 1;]@11");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializer_Update2()
{
var src1 = "class C { int a = 0; }";
var src2 = "class C { int a; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 0]@14 -> [a]@14");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyInitializer_Update2()
{
var src1 = "class C { int a { get; } = 0; }";
var src2 = "class C { int a { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a { get; } = 0;]@10 -> [int a { get { return 1; } }]@10",
"Update [get;]@18 -> [get { return 1; }]@18");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true));
}
[Fact]
public void PropertyInitializer_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int a { get; } = 0; }";
var srcA2 = "partial class C { int a { get { return 1; } } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
DocumentResults()
});
}
[Fact]
public void FieldInitializer_Update3()
{
var src1 = "class C { int a; }";
var src2 = "class C { int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@14 -> [a = 0]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void PropertyInitializer_Update3()
{
var src1 = "class C { int a { get { return 1; } } }";
var src2 = "class C { int a { get; } = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a { get { return 1; } }]@10 -> [int a { get; } = 0;]@10",
"Update [get { return 1; }]@18 -> [get;]@18");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void FieldInitializerUpdate_StaticCtorUpdate1()
{
var src1 = "class C { static int a; static C() { } }";
var src2 = "class C { static int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@21 -> [a = 0]@21",
"Delete [static C() { }]@24",
"Delete [()]@32");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void PropertyInitializerUpdate_StaticCtorUpdate1()
{
var src1 = "class C { static int a { get; } = 1; static C() { } }";
var src2 = "class C { static int a { get; } = 2;}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void FieldInitializerUpdate_InstanceCtorUpdate_Private(string typeKind)
{
var src1 = typeKind + " C { int a; [System.Obsolete]C() { } }";
var src2 = typeKind + " C { int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")),
Diagnostic(RudeEditKind.ChangingAccessibility, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")));
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void PropertyInitializerUpdate_InstanceCtorUpdate_Private(string typeKind)
{
var src1 = typeKind + " C { int a { get; } = 1; C() { } }";
var src2 = typeKind + " C { int a { get; } = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")));
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void FieldInitializerUpdate_InstanceCtorUpdate_Public(string typeKind)
{
var src1 = typeKind + " C { int a; public C() { } }";
var src2 = typeKind + " C { int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void PropertyInitializerUpdate_InstanceCtorUpdate_Public(string typeKind)
{
var src1 = typeKind + " C { int a { get; } = 1; public C() { } }";
var src2 = typeKind + " C { int a { get; } = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializerUpdate_StaticCtorUpdate2()
{
var src1 = "class C { static int a; static C() { } }";
var src2 = "class C { static int a = 0; static C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@21 -> [a = 0]@21");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void PropertyInitializerUpdate_StaticCtorUpdate2()
{
var src1 = "class C { static int a { get; } = 1; static C() { } }";
var src2 = "class C { static int a { get; } = 2; static C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void FieldInitializerUpdate_InstanceCtorUpdate2(string typeKind)
{
var src1 = typeKind + " C { int a; public C() { } }";
var src2 = typeKind + " C { int a = 0; public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@15 -> [a = 0]@15");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void PropertyInitializerUpdate_InstanceCtorUpdate2(string typeKind)
{
var src1 = typeKind + " C { int a { get; } = 1; public C() { } }";
var src2 = typeKind + " C { int a { get; } = 2; public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializerUpdate_InstanceCtorUpdate3()
{
var src1 = "class C { int a; }";
var src2 = "class C { int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@14 -> [a = 0]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void PropertyInitializerUpdate_InstanceCtorUpdate3()
{
var src1 = "class C { int a { get; } = 1; }";
var src2 = "class C { int a { get; } = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializerUpdate_InstanceCtorUpdate4()
{
var src1 = "class C { int a = 0; }";
var src2 = "class C { int a; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 0]@14 -> [a]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializerUpdate_InstanceCtorUpdate5()
{
var src1 = "class C { int a; private C(int a) { } private C(bool a) { } }";
var src2 = "class C { int a = 0; private C(int a) { } private C(bool a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@14 -> [a = 0]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true),
});
}
[Fact]
public void FieldInitializerUpdate_Struct_InstanceCtorUpdate5()
{
var src1 = "struct C { int a; private C(int a) { } private C(bool a) { } }";
var src2 = "struct C { int a = 0; private C(int a) { } private C(bool a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@15 -> [a = 0]@15");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C()"), preserveLocalVariables: true),
});
}
[Fact]
public void PropertyInitializerUpdate_InstanceCtorUpdate5()
{
var src1 = "class C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }";
var src2 = "class C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true),
});
}
[Fact]
public void PropertyInitializerUpdate_Struct_InstanceCtorUpdate5()
{
var src1 = "struct C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }";
var src2 = "struct C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C()"), preserveLocalVariables: true),
});
}
[Fact]
public void FieldInitializerUpdate_InstanceCtorUpdate6()
{
var src1 = "class C { int a; private C(int a) : this(true) { } private C(bool a) { } }";
var src2 = "class C { int a = 0; private C(int a) : this(true) { } private C(bool a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@14 -> [a = 0]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true)
});
}
[Fact]
public void FieldInitializerUpdate_StaticCtorInsertImplicit()
{
var src1 = "class C { static int a; }";
var src2 = "class C { static int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@21 -> [a = 0]@21");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) });
}
[Fact]
public void FieldInitializerUpdate_StaticCtorInsertExplicit()
{
var src1 = "class C { static int a; }";
var src2 = "class C { static int a = 0; static C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [static C() { }]@28",
"Insert [()]@36",
"Update [a]@21 -> [a = 0]@21");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void FieldInitializerUpdate_InstanceCtorInsertExplicit(string typeKind)
{
var src1 = typeKind + " C { int a; }";
var src2 = typeKind + " C { int a = 0; public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void PropertyInitializerUpdate_InstanceCtorInsertExplicit(string typeKind)
{
var src1 = typeKind + " C { int a { get; } = 1; }";
var src2 = typeKind + " C { int a { get; } = 2; public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializerUpdate_GenericType()
{
var src1 = "class C<T> { int a = 1; }";
var src2 = "class C<T> { int a = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@17 -> [a = 2]@17");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericTypeUpdate, "a = 2"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"));
}
[Fact]
public void PropertyInitializerUpdate_GenericType()
{
var src1 = "class C<T> { int a { get; } = 1; }";
var src2 = "class C<T> { int a { get; } = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericTypeUpdate, "int a"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"));
}
[Fact]
public void FieldInitializerUpdate_StackAllocInConstructor()
{
var src1 = "unsafe class C { int a = 1; public C() { int* a = stackalloc int[10]; } }";
var src2 = "unsafe class C { int a = 2; public C() { int* a = stackalloc int[10]; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@21 -> [a = 2]@21");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor));
}
[Fact]
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")]
public void FieldInitializerUpdate_SwitchExpressionInConstructor()
{
var src1 = "class C { int a = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }";
var src2 = "class C { int a = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_StackAllocInConstructor1()
{
var src1 = "unsafe class C { int a { get; } = 1; public C() { int* a = stackalloc int[10]; } }";
var src2 = "unsafe class C { int a { get; } = 2; public C() { int* a = stackalloc int[10]; } }";
var edits = GetTopEdits(src1, src2);
// TODO (tomat): diagnostic should point to the property initializer
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor));
}
[Fact]
public void PropertyInitializerUpdate_StackAllocInConstructor2()
{
var src1 = "unsafe class C { int a { get; } = 1; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }";
var src2 = "unsafe class C { int a { get; } = 2; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_StackAllocInConstructor3()
{
var src1 = "unsafe class C { int a { get; } = 1; public C() { } public C(int b) { int* a = stackalloc int[10]; } }";
var src2 = "unsafe class C { int a { get; } = 2; public C() { } public C(int b) { int* a = stackalloc int[10]; } }";
var edits = GetTopEdits(src1, src2);
// TODO (tomat): diagnostic should point to the property initializer
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor));
}
[Fact]
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")]
public void PropertyInitializerUpdate_SwitchExpressionInConstructor1()
{
var src1 = "class C { int a { get; } = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }";
var src2 = "class C { int a { get; } = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")]
public void PropertyInitializerUpdate_SwitchExpressionInConstructor2()
{
var src1 = "class C { int a { get; } = 1; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }";
var src2 = "class C { int a { get; } = 2; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")]
public void PropertyInitializerUpdate_SwitchExpressionInConstructor3()
{
var src1 = "class C { int a { get; } = 1; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }";
var src2 = "class C { int a { get; } = 2; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_LambdaInConstructor()
{
var src1 = "class C { int a = 1; public C() { F(() => {}); } static void F(System.Action a) {} }";
var src2 = "class C { int a = 2; public C() { F(() => {}); } static void F(System.Action a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@14 -> [a = 2]@14");
edits.VerifySemanticDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_LambdaInConstructor()
{
var src1 = "class C { int a { get; } = 1; public C() { F(() => {}); } static void F(System.Action a) {} }";
var src2 = "class C { int a { get; } = 2; public C() { F(() => {}); } static void F(System.Action a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_QueryInConstructor()
{
var src1 = "using System.Linq; class C { int a = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }";
var src2 = "using System.Linq; class C { int a = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@33 -> [a = 2]@33");
edits.VerifySemanticDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_QueryInConstructor()
{
var src1 = "using System.Linq; class C { int a { get; } = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }";
var src2 = "using System.Linq; class C { int a { get; } = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_AnonymousTypeInConstructor()
{
var src1 = "class C { int a = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }";
var src2 = "class C { int a = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_AnonymousTypeInConstructor()
{
var src1 = "class C { int a { get; } = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }";
var src2 = "class C { int a { get; } = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_PartialTypeWithSingleDeclaration()
{
var src1 = "partial class C { int a = 1; }";
var src2 = "partial class C { int a = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@22 -> [a = 2]@22");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void PropertyInitializerUpdate_PartialTypeWithSingleDeclaration()
{
var src1 = "partial class C { int a { get; } = 1; }";
var src2 = "partial class C { int a { get; } = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void FieldInitializerUpdate_PartialTypeWithMultipleDeclarations()
{
var src1 = "partial class C { int a = 1; } partial class C { }";
var src2 = "partial class C { int a = 2; } partial class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@22 -> [a = 2]@22");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void PropertyInitializerUpdate_PartialTypeWithMultipleDeclarations()
{
var src1 = "partial class C { int a { get; } = 1; } partial class C { }";
var src2 = "partial class C { int a { get; } = 2; } partial class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void FieldInitializerUpdate_ParenthesizedLambda()
{
var src1 = "class C { int a = F(1, (x, y) => x + y); }";
var src2 = "class C { int a = F(2, (x, y) => x + y); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_ParenthesizedLambda()
{
var src1 = "class C { int a { get; } = F(1, (x, y) => x + y); }";
var src2 = "class C { int a { get; } = F(2, (x, y) => x + y); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_SimpleLambda()
{
var src1 = "class C { int a = F(1, x => x); }";
var src2 = "class C { int a = F(2, x => x); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_SimpleLambda()
{
var src1 = "class C { int a { get; } = F(1, x => x); }";
var src2 = "class C { int a { get; } = F(2, x => x); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_Query()
{
var src1 = "class C { int a = F(1, from goo in bar select baz); }";
var src2 = "class C { int a = F(2, from goo in bar select baz); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_Query()
{
var src1 = "class C { int a { get; } = F(1, from goo in bar select baz); }";
var src2 = "class C { int a { get; } = F(2, from goo in bar select baz); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_AnonymousType()
{
var src1 = "class C { int a = F(1, new { A = 1, B = 2 }); }";
var src2 = "class C { int a = F(2, new { A = 1, B = 2 }); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_AnonymousType()
{
var src1 = "class C { int a { get; } = F(1, new { A = 1, B = 2 }); }";
var src2 = "class C { int a { get; } = F(2, new { A = 1, B = 2 }); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 2</N:0.1>);
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithoutLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = 1;
int B = F(<N:0.0>b => b + 1</N:0.0>);
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = 2;
int B = F(<N:0.0>b => b + 1</N:0.0>);
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C() {}
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 2</N:0.1>);
public C() {}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithoutLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = 1;
int B = F(<N:0.0>b => b + 1</N:0.0>);
public C() {}
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = 2;
int B = F(<N:0.0>b => b + 1</N:0.0>);
public C() {}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) {}
public C(bool b) {}
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 2</N:0.1>);
public C(int a) {}
public C(bool b) {}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 2</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(d => d + 1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 2</N:0.2>); }
public C(bool b) { F(d => d + 1); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(d => d + 1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(d => d + 1); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(c => c + 1); }
public C(bool b) { Console.WriteLine(1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(c => c + 1); }
public C(bool b) { Console.WriteLine(2); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_EditConstructorNotIncludingInitializers()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(a => a + 1);
int B = F(b => b + 1);
public C(int a) { F(c => c + 1); }
public C(bool b) : this(1) { Console.WriteLine(1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(a => a + 1);
int B = F(b => b + 1);
public C(int a) { F(c => c + 1); }
public C(bool b) : this(1) { Console.WriteLine(2); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"))
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_RemoveCtorInitializer1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); }
public C(bool b) : this(1) { Console.WriteLine(1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); }
public C(bool b) { Console.WriteLine(1); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_AddCtorInitializer1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(a => a + 1);
int B = F(b => b + 1);
public C(int a) { F(c => c + 1); }
public C(bool b) { Console.WriteLine(1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(a => a + 1);
int B = F(b => b + 1);
public C(int a) { F(c => c + 1); }
public C(bool b) : this(1) { Console.WriteLine(1); }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"))
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_UpdateBaseCtorInitializerWithLambdas1()
{
var src1 = @"
using System;
class B
{
public B(int a) { }
}
class C : B
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(bool b)
: base(F(<N:0.2>c => c + 1</N:0.2>))
{
F(<N:0.3>d => d + 1</N:0.3>);
}
}
";
var src2 = @"
using System;
class B
{
public B(int a) { }
}
class C : B
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(bool b)
: base(F(<N:0.2>c => c + 2</N:0.2>))
{
F(<N:0.3>d => d + 1</N:0.3>);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_PartialDeclarationDelete_SingleDocument()
{
var src1 = @"
partial class C
{
int x = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int y = F(<N:0.1>a => a + 10</N:0.1>);
}
partial class C
{
public C() { }
static int F(Func<int, int> x) => 1;
}
";
var src2 = @"
partial class C
{
int x = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int y = F(<N:0.1>a => a + 10</N:0.1>);
static int F(Func<int, int> x) => 1;
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), syntaxMap[0]),
});
}
[Fact]
public void FieldInitializerUpdate_ActiveStatements1()
{
var src1 = @"
using System;
class C
{
<AS:0>int A = <N:0.0>1</N:0.0>;</AS:0>
int B = 1;
public C(int a) { Console.WriteLine(1); }
public C(bool b) { Console.WriteLine(1); }
}
";
var src2 = @"
using System;
class C
{
<AS:0>int A = <N:0.0>1</N:0.0>;</AS:0>
int B = 2;
public C(int a) { Console.WriteLine(1); }
public C(bool b) { Console.WriteLine(1); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
var activeStatements = GetActiveStatements(src1, src2);
edits.VerifySemantics(
activeStatements,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]),
});
}
[Fact]
public void PropertyWithInitializer_SemanticError_Partial()
{
var src1 = @"
partial class C
{
partial int P => 1;
}
partial class C
{
partial int P => 1;
}
";
var src2 = @"
partial class C
{
partial int P => 1;
}
partial class C
{
partial int P => 2;
public C() { }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => ((IPropertySymbol)c.GetMember<INamedTypeSymbol>("C").GetMembers("P").First()).GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void Field_Partial_DeleteInsert_InitializerRemoval()
{
var srcA1 = "partial class C { int F = 1; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int F; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void Field_Partial_DeleteInsert_InitializerUpdate()
{
var srcA1 = "partial class C { int F = 1; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int F = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
#endregion
#region Fields
[Fact]
public void Field_Rename()
{
var src1 = "class C { int a = 0; }";
var src2 = "class C { int b = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 0]@14 -> [b = 0]@14");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "b = 0", FeaturesResources.field));
}
[Fact]
public void Field_Kind_Update()
{
var src1 = "class C { Action a; }";
var src2 = "class C { event Action a; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Action a;]@10 -> [event Action a;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.FieldKindUpdate, "event Action a", FeaturesResources.event_));
}
[Theory]
[InlineData("static")]
[InlineData("volatile")]
[InlineData("const")]
public void Field_Modifiers_Update(string oldModifiers, string newModifiers = "")
{
if (oldModifiers != "")
{
oldModifiers += " ";
}
if (newModifiers != "")
{
newModifiers += " ";
}
var src1 = "class C { " + oldModifiers + "int F = 0; }";
var src2 = "class C { " + newModifiers + "int F = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [" + oldModifiers + "int F = 0;]@10 -> [" + newModifiers + "int F = 0;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F = 0", FeaturesResources.field));
}
[Fact]
public void Field_Modifier_Add_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int F; }";
var srcA2 = "partial class C { static int F; }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.ModifiersUpdate, "F", FeaturesResources.field)
}),
DocumentResults(),
});
}
[Fact]
public void Field_Attribute_Add_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int F; }";
var srcA2 = "partial class C { [System.Obsolete]int F; }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"))
}),
DocumentResults(),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Field_FixedSize_Update()
{
var src1 = "struct S { public unsafe fixed byte a[1], b[2]; }";
var src2 = "struct S { public unsafe fixed byte a[2], b[3]; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a[1]]@36 -> [a[2]]@36",
"Update [b[2]]@42 -> [b[3]]@42");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "a[2]", FeaturesResources.field),
Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "b[3]", FeaturesResources.field));
}
[WorkItem(1120407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120407")]
[Fact]
public void Field_Const_Update()
{
var src1 = "class C { const int x = 0; }";
var src2 = "class C { const int x = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [x = 0]@20 -> [x = 1]@20");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "x = 1", FeaturesResources.const_field));
}
[Fact]
public void Field_Event_VariableDeclarator_Update()
{
var src1 = "class C { event Action a; }";
var src2 = "class C { event Action a = () => { }; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@23 -> [a = () => { }]@23");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Field_Reorder()
{
var src1 = "class C { int a = 0; int b = 1; int c = 2; }";
var src2 = "class C { int c = 2; int a = 0; int b = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int c = 2;]@32 -> @10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "int c = 2", FeaturesResources.field));
}
[Fact]
public void Field_Insert()
{
var src1 = "class C { }";
var src2 = "class C { int a = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [int a = 1;]@10",
"Insert [int a = 1]@10",
"Insert [a = 1]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.a")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void Field_Insert_IntoStruct()
{
var src1 = @"
struct S
{
public int a;
public S(int z) { this = default(S); a = z; }
}
";
var src2 = @"
struct S
{
public int a;
private int b;
private static int c;
private static int f = 1;
private event System.Action d;
public S(int z) { this = default(S); a = z; }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoStruct, "b", FeaturesResources.field, CSharpFeaturesResources.struct_),
Diagnostic(RudeEditKind.InsertIntoStruct, "c", FeaturesResources.field, CSharpFeaturesResources.struct_),
Diagnostic(RudeEditKind.InsertIntoStruct, "f = 1", FeaturesResources.field, CSharpFeaturesResources.struct_),
Diagnostic(RudeEditKind.InsertIntoStruct, "d", CSharpFeaturesResources.event_field, CSharpFeaturesResources.struct_));
}
[Fact]
public void Field_Insert_IntoLayoutClass_Auto()
{
var src1 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Auto)]
class C
{
private int a;
}
";
var src2 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Auto)]
class C
{
private int a;
private int b;
private int c;
private static int d;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.b")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.c")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.d")),
});
}
[Fact]
public void Field_Insert_IntoLayoutClass_Explicit()
{
var src1 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Explicit)]
class C
{
[FieldOffset(0)]
private int a;
}
";
var src2 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Explicit)]
class C
{
[FieldOffset(0)]
private int a;
[FieldOffset(0)]
private int b;
[FieldOffset(4)]
private int c;
private static int d;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_));
}
[Fact]
public void Field_Insert_IntoLayoutClass_Sequential()
{
var src1 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
private int a;
}
";
var src2 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
private int a;
private int b;
private int c;
private static int d;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_));
}
[Fact]
public void Field_Insert_WithInitializersAndLambdas1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
public C()
{
F(<N:0.1>c => c + 1</N:0.1>);
}
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(b => b + 1); // new field
public C()
{
F(<N:0.1>c => c + 1</N:0.1>);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0])
});
}
[Fact]
public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(b => b + 1); // new field
public C() // new ctor replacing existing implicit constructor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0])
});
}
[Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
public C(int x) {}
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
public C(int x) {}
public C() // new ctor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()"));
// TODO (bug https://github.com/dotnet/roslyn/issues/2504):
//edits.VerifySemantics(
// ActiveStatementsDescription.Empty,
// new[]
// {
// SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0])
// });
}
[Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(b => b + 1); // new field
public C(int x) // new ctor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
_ = GetSyntaxMap(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)"));
// TODO (bug https://github.com/dotnet/roslyn/issues/2504):
//edits.VerifySemantics(
// ActiveStatementsDescription.Empty,
// new[]
// {
// SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")),
// SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0])
// });
}
[Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(null);
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(null);
int B = F(b => b + 1); // new field
public C(int x) // new ctor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single())
});
}
[Fact]
public void Field_Insert_NotSupportedByRuntime()
{
var src1 = "class C { }";
var src2 = "class C { public int a = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddStaticFieldToExistingType,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field));
}
[Fact]
public void Field_Insert_Static_NotSupportedByRuntime()
{
var src1 = "class C { }";
var src2 = "class C { public static int a = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddInstanceFieldToExistingType,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field));
}
[Fact]
public void Field_Attribute_Add_NotSupportedByRuntime()
{
var src1 = @"
class C
{
public int a = 1, x = 1;
}";
var src2 = @"
class C
{
[System.Obsolete]public int a = 1, x = 1;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public int a = 1, x = 1;]@18 -> [[System.Obsolete]public int a = 1, x = 1;]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field));
}
[Fact]
public void Field_Attribute_Add()
{
var src1 = @"
class C
{
public int a, b;
}";
var src2 = @"
class C
{
[System.Obsolete]public int a, b;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.b"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Field_Attribute_Add_WithInitializer()
{
var src1 = @"
class C
{
int a;
}";
var src2 = @"
class C
{
[System.Obsolete]int a = 0;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Field_Attribute_DeleteInsertUpdate_WithInitializer()
{
var srcA1 = "partial class C { int a = 1; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { [System.Obsolete]int a = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Field_Delete1()
{
var src1 = "class C { int a = 1; }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [int a = 1;]@10",
"Delete [int a = 1]@10",
"Delete [a = 1]@14");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a")));
}
[Fact]
public void Field_UnsafeModifier_Update()
{
var src1 = "struct Node { unsafe Node* left; }";
var src2 = "struct Node { Node* left; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [unsafe Node* left;]@14 -> [Node* left;]@14");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Field_ModifierAndType_Update()
{
var src1 = "struct Node { unsafe Node* left; }";
var src2 = "struct Node { Node left; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [unsafe Node* left;]@14 -> [Node left;]@14",
"Update [Node* left]@21 -> [Node left]@14");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "Node left", FeaturesResources.field));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("object", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Field_Type_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C { " + oldType + " F, G; }";
var src2 = "class C { " + newType + " F, G; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Field_Type_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C { " + oldType + " F, G; }";
var src2 = "class C { " + newType + " F, G; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field),
Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("object", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Field_Event_Type_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C { event System.Action<" + oldType + "> F, G; }";
var src2 = "class C { event System.Action<" + newType + "> F, G; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Field_Event_Type_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C { event System.Action<" + oldType + "> F, G; }";
var src2 = "class C { event System.Action<" + newType + "> F, G; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_),
Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_));
}
[Fact]
public void Field_Type_Update_ReorderRemoveAdd()
{
var src1 = "class C { int F, G, H; bool U; }";
var src2 = "class C { string G, F; double V, U; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int F, G, H]@10 -> [string G, F]@10",
"Reorder [G]@17 -> @17",
"Update [bool U]@23 -> [double V, U]@23",
"Insert [V]@30",
"Delete [H]@20");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "G", FeaturesResources.field),
Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field),
Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field),
Diagnostic(RudeEditKind.TypeUpdate, "double V, U", FeaturesResources.field),
Diagnostic(RudeEditKind.Delete, "string G, F", DeletedSymbolDisplay(FeaturesResources.field, "H")));
}
[Fact]
public void Field_Event_Reorder()
{
var src1 = "class C { int a = 0; int b = 1; event int c = 2; }";
var src2 = "class C { event int c = 2; int a = 0; int b = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [event int c = 2;]@32 -> @10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "event int c = 2", CSharpFeaturesResources.event_field));
}
[Fact]
public void Field_Event_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { event int E = 2; }";
var srcA2 = "partial class C { event int E = 2; }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
DocumentResults(),
});
}
#endregion
#region Properties
[Theory]
[InlineData("static")]
[InlineData("virtual")]
[InlineData("abstract")]
[InlineData("override")]
[InlineData("sealed override", "override")]
public void Property_Modifiers_Update(string oldModifiers, string newModifiers = "")
{
if (oldModifiers != "")
{
oldModifiers += " ";
}
if (newModifiers != "")
{
newModifiers += " ";
}
var src1 = "class C { " + oldModifiers + "int F => 0; }";
var src2 = "class C { " + newModifiers + "int F => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [" + oldModifiers + "int F => 0;]@10 -> [" + newModifiers + "int F => 0;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F", FeaturesResources.property_));
}
[Fact]
public void Property_ExpressionBody_Rename()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { int Q => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_));
}
[Fact]
public void Property_ExpressionBody_Update()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { int P => 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [int P => 1;]@10 -> [int P => 2;]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")]
public void Property_ExpressionBody_ModifierUpdate()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { unsafe int P => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [int P => 1;]@10 -> [unsafe int P => 1;]@10");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Property_ExpressionBodyToBlockBody1()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { int P { get { return 2; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P => 1;]@10 -> [int P { get { return 2; } }]@10",
"Insert [{ get { return 2; } }]@16",
"Insert [get { return 2; }]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false)
});
}
[Fact]
public void Property_ExpressionBodyToBlockBody2()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { int P { get { return 2; } set { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P => 1;]@10 -> [int P { get { return 2; } set { } }]@10",
"Insert [{ get { return 2; } set { } }]@16",
"Insert [get { return 2; }]@18",
"Insert [set { }]@36");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_P"), preserveLocalVariables: false)
});
}
[Fact]
public void Property_BlockBodyToExpressionBody1()
{
var src1 = "class C { int P { get { return 2; } } }";
var src2 = "class C { int P => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P { get { return 2; } }]@10 -> [int P => 1;]@10",
"Delete [{ get { return 2; } }]@16",
"Delete [get { return 2; }]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false)
});
}
[Fact]
public void Property_BlockBodyToExpressionBody2()
{
var src1 = "class C { int P { get { return 2; } set { } } }";
var src2 = "class C { int P => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P { get { return 2; } set { } }]@10 -> [int P => 1;]@10",
"Delete [{ get { return 2; } set { } }]@16",
"Delete [get { return 2; }]@18",
"Delete [set { }]@36");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set")));
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_ExpressionBodyToGetterExpressionBody()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { int P { get => 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P => 1;]@10 -> [int P { get => 2; }]@10",
"Insert [{ get => 2; }]@16",
"Insert [get => 2;]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_GetterExpressionBodyToExpressionBody()
{
var src1 = "class C { int P { get => 2; } }";
var src2 = "class C { int P => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P { get => 2; }]@10 -> [int P => 1;]@10",
"Delete [{ get => 2; }]@16",
"Delete [get => 2;]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_GetterBlockBodyToGetterExpressionBody()
{
var src1 = "class C { int P { get { return 2; } } }";
var src2 = "class C { int P { get => 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_SetterBlockBodyToSetterExpressionBody()
{
var src1 = "class C { int P { set { } } }";
var src2 = "class C { int P { set => F(); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [set { }]@18 -> [set => F();]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_InitBlockBodyToInitExpressionBody()
{
var src1 = "class C { int P { init { } } }";
var src2 = "class C { int P { init => F(); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [init { }]@18 -> [init => F();]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod, preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_GetterExpressionBodyToGetterBlockBody()
{
var src1 = "class C { int P { get => 2; } }";
var src2 = "class C { int P { get { return 2; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_GetterBlockBodyWithSetterToGetterExpressionBodyWithSetter()
{
var src1 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }";
var src2 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_GetterExpressionBodyWithSetterToGetterBlockBodyWithSetter()
{
var src1 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }";
var src2 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_P"), preserveLocalVariables: false)
});
}
[Fact]
public void Property_Rename1()
{
var src1 = "class C { int P { get { return 1; } } }";
var src2 = "class C { int Q { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_));
}
[Fact]
public void Property_Rename2()
{
var src1 = "class C { int I.P { get { return 1; } } }";
var src2 = "class C { int J.P { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "int J.P", FeaturesResources.property_));
}
[Fact]
public void Property_RenameAndUpdate()
{
var src1 = "class C { int P { get { return 1; } } }";
var src2 = "class C { int Q { get { return 2; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_));
}
[Fact]
public void PropertyDelete()
{
var src1 = "class C { int P { get { return 1; } } }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.property_, "P")));
}
[Fact]
public void PropertyReorder1()
{
var src1 = "class C { int P { get { return 1; } } int Q { get { return 1; } } }";
var src2 = "class C { int Q { get { return 1; } } int P { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int Q { get { return 1; } }]@38 -> @10");
// TODO: we can allow the move since the property doesn't have a backing field
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.property_));
}
[Fact]
public void PropertyReorder2()
{
var src1 = "class C { int P { get; set; } int Q { get; set; } }";
var src2 = "class C { int Q { get; set; } int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int Q { get; set; }]@30 -> @10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.auto_property));
}
[Fact]
public void PropertyAccessorReorder_GetSet()
{
var src1 = "class C { int P { get { return 1; } set { } } }";
var src2 = "class C { int P { set { } get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [set { }]@36 -> @18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyAccessorReorder_GetInit()
{
var src1 = "class C { int P { get { return 1; } init { } } }";
var src2 = "class C { int P { init { } get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [init { }]@36 -> @18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyTypeUpdate()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { char P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P { get; set; }]@10 -> [char P { get; set; }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "char P", FeaturesResources.property_));
}
[Fact]
public void PropertyUpdate_AddAttribute()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { [System.Obsolete]int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int P", FeaturesResources.property_));
}
[Fact]
public void PropertyUpdate_AddAttribute_SupportedByRuntime()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { [System.Obsolete]int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void PropertyAccessorUpdate_AddAttribute()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { [System.Obsolete]get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "get", CSharpFeaturesResources.property_getter));
}
[Fact]
public void PropertyAccessorUpdate_AddAttribute2()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { get; [System.Obsolete]set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "set", CSharpFeaturesResources.property_setter));
}
[Fact]
public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { [System.Obsolete]get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime2()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { get; [System.Obsolete]set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void PropertyInsert()
{
var src1 = "class C { }";
var src2 = "class C { int P { get => 1; set { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("P")));
}
[Fact]
public void PropertyInsert_NotSupportedByRuntime()
{
var src1 = "class C { }";
var src2 = "class C { int P { get => 1; set { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "int P", FeaturesResources.auto_property));
}
[WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
[Fact]
public void PropertyInsert_PInvoke()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
}";
var src2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
private static extern int P1 { [DllImport(""x.dll"")]get; }
private static extern int P2 { [DllImport(""x.dll"")]set; }
private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; }
}
";
var edits = GetTopEdits(src1, src2);
// CLR doesn't support methods without a body
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertExtern, "private static extern int P1", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertExtern, "private static extern int P2", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertExtern, "private static extern int P3", FeaturesResources.property_));
}
[Fact]
public void PropertyInsert_IntoStruct()
{
var src1 = @"
struct S
{
public int a;
public S(int z) { a = z; }
}
";
var src2 = @"
struct S
{
public int a;
private static int c { get; set; }
private static int e { get { return 0; } set { } }
private static int g { get; } = 1;
private static int i { get; set; } = 1;
private static int k => 1;
public S(int z) { a = z; }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoStruct, "private static int c { get; set; }", FeaturesResources.auto_property, CSharpFeaturesResources.struct_),
Diagnostic(RudeEditKind.InsertIntoStruct, "private static int g { get; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_),
Diagnostic(RudeEditKind.InsertIntoStruct, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_));
}
[Fact]
public void PropertyInsert_IntoLayoutClass_Sequential()
{
var src1 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
private int a;
}
";
var src2 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
private int a;
private int b { get; set; }
private static int c { get; set; }
private int d { get { return 0; } set { } }
private static int e { get { return 0; } set { } }
private int f { get; } = 1;
private static int g { get; } = 1;
private int h { get; set; } = 1;
private static int i { get; set; } = 1;
private int j => 1;
private static int k => 1;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int b { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int c { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int f { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int g { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int h { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_));
}
// Design: Adding private accessors should also be allowed since we now allow adding private methods
// and adding public properties and/or public accessors are not allowed.
[Fact]
public void PrivateProperty_AccessorAdd()
{
var src1 = "class C { int _p; int P { get { return 1; } } }";
var src2 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set { _p = value; }]@44");
edits.VerifyRudeDiagnostics();
}
[WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")]
[Fact]
public void PrivatePropertyAccessorDelete()
{
var src1 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }";
var src2 = "class C { int _p; int P { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [set { _p = value; }]@44");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set")));
}
[Fact]
public void PrivateAutoPropertyAccessorAdd1()
{
var src1 = "class C { int P { get; } }";
var src2 = "class C { int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set;]@23");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PrivateAutoPropertyAccessorAdd2()
{
var src1 = "class C { public int P { get; } }";
var src2 = "class C { public int P { get; private set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [private set;]@30");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PrivateAutoPropertyAccessorAdd4()
{
var src1 = "class C { public int P { get; } }";
var src2 = "class C { public int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set;]@30");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PrivateAutoPropertyAccessorAdd5()
{
var src1 = "class C { public int P { get; } }";
var src2 = "class C { public int P { get; internal set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [internal set;]@30");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PrivateAutoPropertyAccessorAdd6()
{
var src1 = "class C { int P { get; } = 1; }";
var src2 = "class C { int P { get; set; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set;]@23");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PrivateAutoPropertyAccessorAdd_Init()
{
var src1 = "class C { int P { get; } = 1; }";
var src2 = "class C { int P { get; init; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [init;]@23");
edits.VerifyRudeDiagnostics();
}
[WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")]
[Fact]
public void PrivateAutoPropertyAccessorDelete_Get()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [get;]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_getter, "P.get")));
}
[Fact]
public void AutoPropertyAccessor_SetToInit()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { get; init; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [set;]@23 -> [init;]@23");
// not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq)
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.AccessorKindUpdate, "init", CSharpFeaturesResources.property_setter));
}
[Fact]
public void AutoPropertyAccessor_InitToSet()
{
var src1 = "class C { int P { get; init; } }";
var src2 = "class C { int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [init;]@23 -> [set;]@23");
// not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq)
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter));
}
[Fact]
public void PrivateAutoPropertyAccessorDelete_Set()
{
var src1 = "class C { int P { get; set; } = 1; }";
var src2 = "class C { int P { get; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [set;]@23");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set")));
}
[Fact]
public void PrivateAutoPropertyAccessorDelete_Init()
{
var src1 = "class C { int P { get; init; } = 1; }";
var src2 = "class C { int P { get; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [init;]@23");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.init")));
}
[Fact]
public void AutoPropertyAccessorUpdate()
{
var src1 = "class C { int P { get; } }";
var src2 = "class C { int P { set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get;]@18 -> [set;]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter));
}
[WorkItem(992578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992578")]
[Fact]
public void InsertIncompleteProperty()
{
var src1 = "class C { }";
var src2 = "class C { public int P { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [public int P { }]@10", "Insert [{ }]@23");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Property_ReadOnlyRef_Insert()
{
var src1 = "class Test { }";
var src2 = "class Test { ref readonly int P { get; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [ref readonly int P { get; }]@13",
"Insert [{ get; }]@32",
"Insert [get;]@34");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Property_ReadOnlyRef_Update()
{
var src1 = "class Test { int P { get; } }";
var src2 = "class Test { ref readonly int P { get; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P { get; }]@13 -> [ref readonly int P { get; }]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int P", FeaturesResources.property_));
}
[Fact]
public void Property_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int P { get => 1; set { } } }";
var srcA2 = "partial class C { int P { get => 1; set { } } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod)
}),
DocumentResults(),
});
}
[Fact]
public void PropertyInit_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int Q { get => 1; init { } }}";
var srcA2 = "partial class C { int Q { get => 1; init { } }}";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod)
}),
DocumentResults(),
});
}
[Fact]
public void AutoProperty_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }";
var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }";
var srcB2 = "partial class C { }";
// Accessors need to be updated even though they do not have an explicit body.
// There is still a sequence point generated for them whose location needs to be updated.
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod),
}),
DocumentResults(),
});
}
[Fact]
public void AutoPropertyWithInitializer_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int P { get; set; } = 1; }";
var srcA2 = "partial class C { int P { get; set; } = 1; }";
var srcB2 = "partial class C { }";
// Accessors need to be updated even though they do not have an explicit body.
// There is still a sequence point generated for them whose location needs to be updated.
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
DocumentResults(),
});
}
[Fact]
public void PropertyWithExpressionBody_Partial_InsertDeleteUpdate()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int P => 1; }";
var srcA2 = "partial class C { int P => 2; }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }),
DocumentResults(),
});
}
[Fact]
public void AutoProperty_ReadOnly_Add()
{
var src1 = @"
struct S
{
int P { get; }
}";
var src2 = @"
struct S
{
readonly int P { get; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Property_InMutableStruct_ReadOnly_Add()
{
var src1 = @"
struct S
{
int P1 { get => 1; }
int P2 { get => 1; set {}}
int P3 { get => 1; set {}}
int P4 { get => 1; set {}}
}";
var src2 = @"
struct S
{
readonly int P1 { get => 1; }
int P2 { readonly get => 1; set {}}
int P3 { get => 1; readonly set {}}
readonly int P4 { get => 1; set {}}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P1", CSharpFeaturesResources.property_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_setter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.property_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.property_setter));
}
[Fact]
public void Property_InReadOnlyStruct_ReadOnly_Add()
{
// indent to align accessor bodies and avoid updates caused by sequence point location changes
var src1 = @"
readonly struct S
{
int P1 { get => 1; }
int P2 { get => 1; set {}}
int P3 { get => 1; set {}}
int P4 { get => 1; set {}}
}";
var src2 = @"
readonly struct S
{
readonly int P1 { get => 1; }
int P2 { readonly get => 1; set {}}
int P3 { get => 1; readonly set {}}
readonly int P4 { get => 1; set {}}
}";
var edits = GetTopEdits(src1, src2);
// updates only for accessors whose modifiers were explicitly updated
edits.VerifySemantics(new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P3").SetMethod, preserveLocalVariables: false)
});
}
#endregion
#region Indexers
[Theory]
[InlineData("virtual")]
[InlineData("abstract")]
[InlineData("override")]
[InlineData("sealed override", "override")]
public void Indexer_Modifiers_Update(string oldModifiers, string newModifiers = "")
{
if (oldModifiers != "")
{
oldModifiers += " ";
}
if (newModifiers != "")
{
newModifiers += " ";
}
var src1 = "class C { " + oldModifiers + "int this[int a] => 0; }";
var src2 = "class C { " + newModifiers + "int this[int a] => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [" + oldModifiers + "int this[int a] => 0;]@10 -> [" + newModifiers + "int this[int a] => 0;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int this[int a]", FeaturesResources.indexer_));
}
[Fact]
public void Indexer_GetterUpdate()
{
var src1 = "class C { int this[int a] { get { return 1; } } }";
var src2 = "class C { int this[int a] { get { return 2; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [get { return 1; }]@28 -> [get { return 2; }]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact]
public void Indexer_SetterUpdate()
{
var src1 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value); } } }";
var src2 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value + 1); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [set { System.Console.WriteLine(value); }]@46 -> [set { System.Console.WriteLine(value + 1); }]@46");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false)
});
}
[Fact]
public void Indexer_InitUpdate()
{
var src1 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value); } } }";
var src2 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value + 1); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [init { System.Console.WriteLine(value); }]@46 -> [init { System.Console.WriteLine(value + 1); }]@46");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false)
});
}
[Fact]
public void IndexerWithExpressionBody_Update()
{
var src1 = "class C { int this[int a] => 1; }";
var src2 = "class C { int this[int a] => 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => 1;]@10 -> [int this[int a] => 2;]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void IndexerWithExpressionBody_Update_LiftedParameter()
{
var src1 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => a + 1)() + 10;
}
";
var src2 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => 2)() + 11; // not capturing a anymore
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => new Func<int>(() => a + 1)() + 10;]@35 -> [int this[int a] => new Func<int>(() => 2)() + 11;]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a"));
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void IndexerWithExpressionBody_Update_LiftedParameter_2()
{
var src1 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => a + 1)();
}
";
var src2 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => 2)(); // not capturing a anymore
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => new Func<int>(() => a + 1)();]@35 -> [int this[int a] => new Func<int>(() => 2)();]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a"));
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void IndexerWithExpressionBody_Update_LiftedParameter_3()
{
var src1 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => { return a + 1; })();
}
";
var src2 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => { return 2; })(); // not capturing a anymore
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => new Func<int>(() => { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(() => { return 2; })();]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a"));
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void IndexerWithExpressionBody_Update_LiftedParameter_4()
{
var src1 = @"
using System;
class C
{
int this[int a] => new Func<int>(delegate { return a + 1; })();
}
";
var src2 = @"
using System;
class C
{
int this[int a] => new Func<int>(delegate { return 2; })(); // not capturing a anymore
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => new Func<int>(delegate { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(delegate { return 2; })();]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a"));
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_ExpressionBodyToBlockBody()
{
var src1 = "class C { int this[int a] => 1; }";
var src2 = "class C { int this[int a] { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } }]@10",
"Insert [{ get { return 1; } }]@26",
"Insert [get { return 1; }]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_BlockBodyToExpressionBody()
{
var src1 = "class C { int this[int a] { get { return 1; } } }";
var src2 = "class C { int this[int a] => 1; } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] { get { return 1; } }]@10 -> [int this[int a] => 1;]@10",
"Delete [{ get { return 1; } }]@26",
"Delete [get { return 1; }]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_GetterExpressionBodyToBlockBody()
{
var src1 = "class C { int this[int a] { get => 1; } }";
var src2 = "class C { int this[int a] { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_BlockBodyToGetterExpressionBody()
{
var src1 = "class C { int this[int a] { get { return 1; } } }";
var src2 = "class C { int this[int a] { get => 1; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28");
edits.VerifyRudeDiagnostics();
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_GetterExpressionBodyToExpressionBody()
{
var src1 = "class C { int this[int a] { get => 1; } }";
var src2 = "class C { int this[int a] => 1; } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] { get => 1; }]@10 -> [int this[int a] => 1;]@10",
"Delete [{ get => 1; }]@26",
"Delete [get => 1;]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_ExpressionBodyToGetterExpressionBody()
{
var src1 = "class C { int this[int a] => 1; }";
var src2 = "class C { int this[int a] { get => 1; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => 1;]@10 -> [int this[int a] { get => 1; }]@10",
"Insert [{ get => 1; }]@26",
"Insert [get => 1;]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_GetterBlockBodyToGetterExpressionBody()
{
var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }";
var src2 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_SetterBlockBodyToSetterExpressionBody()
{
var src1 = "class C { int this[int a] { set { } } void F() { } }";
var src2 = "class C { int this[int a] { set => F(); } void F() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [set { }]@28 -> [set => F();]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_InitBlockBodyToInitExpressionBody()
{
var src1 = "class C { int this[int a] { init { } } void F() { } }";
var src2 = "class C { int this[int a] { init => F(); } void F() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [init { }]@28 -> [init => F();]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_GetterExpressionBodyToGetterBlockBody()
{
var src1 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }";
var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_GetterAndSetterBlockBodiesToExpressionBody()
{
var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }";
var src2 = "class C { int this[int a] => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10 -> [int this[int a] => 1;]@10",
"Delete [{ get { return 1; } set { Console.WriteLine(0); } }]@26",
"Delete [get { return 1; }]@28",
"Delete [set { Console.WriteLine(0); }]@46");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set")));
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_ExpressionBodyToGetterAndSetterBlockBodies()
{
var src1 = "class C { int this[int a] => 1; }";
var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10",
"Insert [{ get { return 1; } set { Console.WriteLine(0); } }]@26",
"Insert [get { return 1; }]@28",
"Insert [set { Console.WriteLine(0); }]@46");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_Item"), preserveLocalVariables: false)
});
}
[Fact]
public void Indexer_Rename()
{
var src1 = "class C { int I.this[int a] { get { return 1; } } }";
var src2 = "class C { int J.this[int a] { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "int J.this[int a]", CSharpFeaturesResources.indexer));
}
[Fact]
public void Indexer_Reorder1()
{
var src1 = "class C { int this[int a] { get { return 1; } } int this[string a] { get { return 1; } } }";
var src2 = "class C { int this[string a] { get { return 1; } } int this[int a] { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int this[string a] { get { return 1; } }]@48 -> @10");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Indexer_AccessorReorder()
{
var src1 = "class C { int this[int a] { get { return 1; } set { } } }";
var src2 = "class C { int this[int a] { set { } get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [set { }]@46 -> @28");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Indexer_TypeUpdate()
{
var src1 = "class C { int this[int a] { get; set; } }";
var src2 = "class C { string this[int a] { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] { get; set; }]@10 -> [string this[int a] { get; set; }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "string this[int a]", CSharpFeaturesResources.indexer));
}
[Fact]
public void Tuple_TypeUpdate()
{
var src1 = "class C { (int, int) M() { throw new System.Exception(); } }";
var src2 = "class C { (string, int) M() { throw new System.Exception(); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int, int) M() { throw new System.Exception(); }]@10 -> [(string, int) M() { throw new System.Exception(); }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "(string, int) M()", FeaturesResources.method));
}
[Fact]
public void TupleElementDelete()
{
var src1 = "class C { (int, int, int a) M() { return (1, 2, 3); } }";
var src2 = "class C { (int, int) M() { return (1, 2); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int, int, int a) M() { return (1, 2, 3); }]@10 -> [(int, int) M() { return (1, 2); }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "(int, int) M()", FeaturesResources.method));
}
[Fact]
public void TupleElementAdd()
{
var src1 = "class C { (int, int) M() { return (1, 2); } }";
var src2 = "class C { (int, int, int a) M() { return (1, 2, 3); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int, int) M() { return (1, 2); }]@10 -> [(int, int, int a) M() { return (1, 2, 3); }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "(int, int, int a) M()", FeaturesResources.method));
}
[Fact]
public void Indexer_ParameterUpdate()
{
var src1 = "class C { int this[int a] { get; set; } }";
var src2 = "class C { int this[string a] { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "string a", FeaturesResources.parameter));
}
[Fact]
public void Indexer_AddGetAccessor()
{
var src1 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
set { arr[i] = value; }
}
}";
var src2 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { return arr[i]; }
set { arr[i] = value; }
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [get { return arr[i]; }]@304");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InsertIntoGenericType, "get", CSharpFeaturesResources.indexer_getter));
}
[Fact]
public void Indexer_AddSetAccessor()
{
var src1 = @"
class C
{
public int this[int i] { get { return default; } }
}";
var src2 = @"
class C
{
public int this[int i] { get { return default; } set { } }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set { }]@67");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod));
}
[Fact]
public void Indexer_AddSetAccessor_GenericType()
{
var src1 = @"
class C<T>
{
public T this[int i] { get { return default; } }
}";
var src2 = @"
class C<T>
{
public T this[int i] { get { return default; } set { } }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set { }]@68");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoGenericType, "set", CSharpFeaturesResources.indexer_setter));
}
[WorkItem(750109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")]
[Fact]
public void Indexer_DeleteGetAccessor()
{
var src1 = @"
class C<T>
{
public T this[int i]
{
get { return arr[i]; }
set { arr[i] = value; }
}
}";
var src2 = @"
class C<T>
{
public T this[int i]
{
set { arr[i] = value; }
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [get { return arr[i]; }]@58");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "public T this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_getter, "this[int i].get")));
}
[Fact]
public void Indexer_DeleteSetAccessor()
{
var src1 = @"
class C
{
public int this[int i] { get { return 0; } set { } }
}";
var src2 = @"
class C
{
public int this[int i] { get { return 0; } }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [set { }]@61");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "public int this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int i].set")));
}
[Fact, WorkItem(1174850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174850")]
public void Indexer_Insert()
{
var src1 = "struct C { }";
var src2 = "struct C { public int this[int x, int y] { get { return x + y; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Indexer_ReadOnlyRef_Parameter_InsertWhole()
{
var src1 = "class Test { }";
var src2 = "class Test { int this[in int i] => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [int this[in int i] => throw null;]@13",
"Insert [[in int i]]@21",
"Insert [in int i]@22");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Indexer_ReadOnlyRef_Parameter_Update()
{
var src1 = "class Test { int this[int i] => throw null; }";
var src2 = "class Test { int this[in int i] => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int i]@22 -> [in int i]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "in int i", FeaturesResources.parameter));
}
[Fact]
public void Indexer_ReadOnlyRef_ReturnType_Insert()
{
var src1 = "class Test { }";
var src2 = "class Test { ref readonly int this[int i] => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [ref readonly int this[int i] => throw null;]@13",
"Insert [[int i]]@34",
"Insert [int i]@35");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Indexer_ReadOnlyRef_ReturnType_Update()
{
var src1 = "class Test { int this[int i] => throw null; }";
var src2 = "class Test { ref readonly int this[int i] => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int i] => throw null;]@13 -> [ref readonly int this[int i] => throw null;]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int this[int i]", FeaturesResources.indexer_));
}
[Fact]
public void Indexer_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }";
var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)
}),
DocumentResults(),
});
}
[Fact]
public void IndexerInit_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}";
var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)
}),
DocumentResults(),
});
}
[Fact]
public void AutoIndexer_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int this[int x] { get; set; } }";
var srcA2 = "partial class C { int this[int x] { get; set; } }";
var srcB2 = "partial class C { }";
// Accessors need to be updated even though they do not have an explicit body.
// There is still a sequence point generated for them whose location needs to be updated.
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod),
}),
DocumentResults(),
});
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void IndexerWithExpressionBody_Partial_InsertDeleteUpdate_LiftedParameter()
{
var srcA1 = @"
partial class C
{
}";
var srcB1 = @"
partial class C
{
int this[int a] => new System.Func<int>(() => a + 1);
}";
var srcA2 = @"
partial class C
{
int this[int a] => new System.Func<int>(() => 2); // no capture
}";
var srcB2 = @"
partial class C
{
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a") }),
DocumentResults(),
});
}
[Fact]
public void AutoIndexer_ReadOnly_Add()
{
var src1 = @"
struct S
{
int this[int x] { get; }
}";
var src2 = @"
struct S
{
readonly int this[int x] { get; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter));
}
[Fact]
public void Indexer_InMutableStruct_ReadOnly_Add()
{
var src1 = @"
struct S
{
int this[int x] { get => 1; }
int this[uint x] { get => 1; set {}}
int this[byte x] { get => 1; set {}}
int this[sbyte x] { get => 1; set {}}
}";
var src2 = @"
struct S
{
readonly int this[int x] { get => 1; }
int this[uint x] { readonly get => 1; set {}}
int this[byte x] { get => 1; readonly set {}}
readonly int this[sbyte x] { get => 1; set {}}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_setter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.indexer_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.indexer_setter));
}
[Fact]
public void Indexer_InReadOnlyStruct_ReadOnly_Add()
{
// indent to align accessor bodies and avoid updates caused by sequence point location changes
var src1 = @"
readonly struct S
{
int this[int x] { get => 1; }
int this[uint x] { get => 1; set {}}
int this[byte x] { get => 1; set {}}
int this[sbyte x] { get => 1; set {}}
}";
var src2 = @"
readonly struct S
{
readonly int this[int x] { get => 1; }
int this[uint x] { readonly get => 1; set {}}
int this[byte x] { get => 1; readonly set {}}
readonly int this[sbyte x] { get => 1; set {}}
}";
var edits = GetTopEdits(src1, src2);
// updates only for accessors whose modifiers were explicitly updated
edits.VerifySemantics(new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "UInt32").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false)
});
}
#endregion
#region Events
[Theory]
[InlineData("static")]
[InlineData("virtual")]
[InlineData("abstract")]
[InlineData("override")]
[InlineData("sealed override", "override")]
public void Event_Modifiers_Update(string oldModifiers, string newModifiers = "")
{
if (oldModifiers != "")
{
oldModifiers += " ";
}
if (newModifiers != "")
{
newModifiers += " ";
}
var src1 = "class C { " + oldModifiers + "event Action F { add {} remove {} } }";
var src2 = "class C { " + newModifiers + "event Action F { add {} remove {} } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [" + oldModifiers + "event Action F { add {} remove {} }]@10 -> [" + newModifiers + "event Action F { add {} remove {} }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "event Action F", FeaturesResources.event_));
}
[Fact]
public void Event_Accessor_Reorder1()
{
var src1 = "class C { event int E { add { } remove { } } }";
var src2 = "class C { event int E { remove { } add { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [remove { }]@32 -> @24");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Event_Accessor_Reorder2()
{
var src1 = "class C { event int E1 { add { } remove { } } event int E1 { add { } remove { } } }";
var src2 = "class C { event int E2 { remove { } add { } } event int E2 { remove { } add { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [event int E1 { add { } remove { } }]@10 -> [event int E2 { remove { } add { } }]@10",
"Update [event int E1 { add { } remove { } }]@49 -> [event int E2 { remove { } add { } }]@49",
"Reorder [remove { }]@33 -> @25",
"Reorder [remove { }]@72 -> @64");
}
[Fact]
public void Event_Accessor_Reorder3()
{
var src1 = "class C { event int E1 { add { } remove { } } event int E2 { add { } remove { } } }";
var src2 = "class C { event int E2 { remove { } add { } } event int E1 { remove { } add { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [event int E2 { add { } remove { } }]@49 -> @10",
"Reorder [remove { }]@72 -> @25",
"Reorder [remove { }]@33 -> @64");
}
[Fact]
public void Event_Insert()
{
var src1 = "class C { }";
var src2 = "class C { event int E { remove { } add { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("E")));
}
[Fact]
public void Event_Delete()
{
var src1 = "class C { event int E { remove { } add { } } }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.event_, "E")));
}
[Fact]
public void Event_Insert_IntoLayoutClass_Sequential()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
}
";
var src2 = @"
using System;
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
private event Action c { add { } remove { } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Event_ExpressionBodyToBlockBody()
{
var src1 = @"
using System;
public class C
{
event Action E { add => F(); remove => F(); }
}
";
var src2 = @"
using System;
public class C
{
event Action E { add { F(); } remove { } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [add => F();]@57 -> [add { F(); }]@56",
"Update [remove => F();]@69 -> [remove { }]@69"
);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Event_BlockBodyToExpressionBody()
{
var src1 = @"
using System;
public class C
{
event Action E { add { F(); } remove { } }
}
";
var src2 = @"
using System;
public class C
{
event Action E { add => F(); remove => F(); }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [add { F(); }]@56 -> [add => F();]@57",
"Update [remove { }]@69 -> [remove => F();]@69"
);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Event_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { event int E { add { } remove { } } }";
var srcA2 = "partial class C { event int E { add { } remove { } } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod)
}),
DocumentResults(),
});
}
[Fact]
public void Event_InMutableStruct_ReadOnly_Add()
{
var src1 = @"
struct S
{
public event Action E { add {} remove {} }
}";
var src2 = @"
struct S
{
public readonly event Action E { add {} remove {} }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly event Action E", FeaturesResources.event_));
}
[Fact]
public void Event_InReadOnlyStruct_ReadOnly_Add1()
{
var src1 = @"
readonly struct S
{
public event Action E { add {} remove {} }
}";
var src2 = @"
readonly struct S
{
public readonly event Action E { add {} remove {} }
}";
var edits = GetTopEdits(src1, src2);
// Currently, an edit is produced eventhough bodies nor IsReadOnly attribute have changed. Consider improving.
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").AddMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").RemoveMethod));
}
[Fact]
public void Field_Event_Attribute_Add()
{
var src1 = @"
class C
{
event Action F;
}";
var src2 = @"
class C
{
[System.Obsolete]event Action F;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [event Action F;]@18 -> [[System.Obsolete]event Action F;]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Event_Attribute_Add()
{
var src1 = @"
class C
{
event Action F { add {} remove {} }
}";
var src2 = @"
class C
{
[System.Obsolete]event Action F { add {} remove {} }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [event Action F { add {} remove {} }]@18 -> [[System.Obsolete]event Action F { add {} remove {} }]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Event_Accessor_Attribute_Add()
{
var src1 = @"
class C
{
event Action F { add {} remove {} }
}";
var src2 = @"
class C
{
event Action F { add {} [System.Obsolete]remove {} }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [remove {}]@42 -> [[System.Obsolete]remove {}]@42");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Field_Event_Attribute_Delete()
{
var src1 = @"
class C
{
[System.Obsolete]event Action F;
}";
var src2 = @"
class C
{
event Action F;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete]event Action F;]@18 -> [event Action F;]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Event_Attribute_Delete()
{
var src1 = @"
class C
{
[System.Obsolete]event Action F { add {} remove {} }
}";
var src2 = @"
class C
{
event Action F { add {} remove {} }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete]event Action F { add {} remove {} }]@18 -> [event Action F { add {} remove {} }]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Event_Accessor_Attribute_Delete()
{
var src1 = @"
class C
{
event Action F { add {} [System.Obsolete]remove {} }
}";
var src2 = @"
class C
{
event Action F { add {} remove {} }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete]remove {}]@42 -> [remove {}]@42");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
#endregion
#region Parameter
[Fact]
public void ParameterRename_Method1()
{
var src1 = @"class C { public void M(int a) {} }";
var src2 = @"class C { public void M(int b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@24 -> [int b]@24");
}
[Fact]
public void ParameterRename_Ctor1()
{
var src1 = @"class C { public C(int a) {} }";
var src2 = @"class C { public C(int b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@19 -> [int b]@19");
}
[Fact]
public void ParameterRename_Operator1()
{
var src1 = @"class C { public static implicit operator int(C a) {} }";
var src2 = @"class C { public static implicit operator int(C b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [C a]@46 -> [C b]@46");
}
[Fact]
public void ParameterRename_Operator2()
{
var src1 = @"class C { public static int operator +(C a, C b) { return 0; } }";
var src2 = @"class C { public static int operator +(C a, C x) { return 0; } } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [C b]@44 -> [C x]@44");
}
[Fact]
public void ParameterRename_Indexer2()
{
var src1 = @"class C { public int this[int a, int b] { get { return 0; } } }";
var src2 = @"class C { public int this[int a, int x] { get { return 0; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int b]@33 -> [int x]@33");
}
[Fact]
public void ParameterInsert1()
{
var src1 = @"class C { public void M() {} }";
var src2 = @"class C { public void M(int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [int a]@24");
}
[Fact]
public void ParameterInsert2()
{
var src1 = @"class C { public void M(int a) {} }";
var src2 = @"class C { public void M(int a, ref int b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int a)]@23 -> [(int a, ref int b)]@23",
"Insert [ref int b]@31");
}
[Fact]
public void ParameterDelete1()
{
var src1 = @"class C { public void M(int a) {} }";
var src2 = @"class C { public void M() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [int a]@24");
}
[Fact]
public void ParameterDelete2()
{
var src1 = @"class C { public void M(int a, int b) {} }";
var src2 = @"class C { public void M(int b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int a, int b)]@23 -> [(int b)]@23",
"Delete [int a]@24");
}
[Fact]
public void ParameterUpdate()
{
var src1 = @"class C { public void M(int a) {} }";
var src2 = @"class C { public void M(int b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@24 -> [int b]@24");
}
[Fact]
public void ParameterReorder()
{
var src1 = @"class C { public void M(int a, int b) {} }";
var src2 = @"class C { public void M(int b, int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int b]@31 -> @24");
}
[Fact]
public void ParameterReorderAndUpdate()
{
var src1 = @"class C { public void M(int a, int b) {} }";
var src2 = @"class C { public void M(int b, int c) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int b]@31 -> @24",
"Update [int a]@24 -> [int c]@31");
}
[Theory]
[InlineData("string", "string?")]
[InlineData("object", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Parameter_Type_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C { static void M(" + oldType + " a) {} }";
var src2 = "class C { static void M(" + newType + " a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Parameter_Type_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C { static void M(" + oldType + " a) {} }";
var src2 = "class C { static void M(" + newType + " a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, newType + " a", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Type_Nullable()
{
var src1 = @"
#nullable enable
class C { static void M(string a) { } }
";
var src2 = @"
#nullable disable
class C { static void M(string a) { } }
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Theory]
[InlineData("this")]
[InlineData("ref")]
[InlineData("out")]
[InlineData("params")]
public void Parameter_Modifier_Remove(string modifier)
{
var src1 = @"static class C { static void F(" + modifier + " int[] a) { } }";
var src2 = @"static class C { static void F(int[] a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "int[] a", FeaturesResources.parameter));
}
[Theory]
[InlineData("int a = 1", "int a = 2")]
[InlineData("int a = 1", "int a")]
[InlineData("int a", "int a = 2")]
[InlineData("object a = null", "object a")]
[InlineData("object a", "object a = null")]
[InlineData("double a = double.NaN", "double a = 1.2")]
public void Parameter_Initializer_Update(string oldParameter, string newParameter)
{
var src1 = @"static class C { static void F(" + oldParameter + ") { } }";
var src2 = @"static class C { static void F(" + newParameter + ") { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, newParameter, FeaturesResources.parameter));
}
[Fact]
public void Parameter_Initializer_NaN()
{
var src1 = @"static class C { static void F(double a = System.Double.NaN) { } }";
var src2 = @"static class C { static void F(double a = double.NaN) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Parameter_Initializer_InsertDeleteUpdate()
{
var srcA1 = @"partial class C { }";
var srcB1 = @"partial class C { public static void F(int x = 1) {} }";
var srcA2 = @"partial class C { public static void F(int x = 2) {} }";
var srcB2 = @"partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter)
}),
DocumentResults(),
});
}
[Fact]
public void Parameter_Attribute_Insert()
{
var attribute = "public class A : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M(int a) {} }";
var src2 = attribute + @"class C { public void M([A]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@63 -> [[A]int a]@63");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute1()
{
var attribute = "public class AAttribute : System.Security.Permissions.SecurityAttribute { }\n\n";
var src1 = attribute + @"class C { public void M(int a) {} }";
var src2 = attribute + @"class C { public void M([A]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@101 -> [[A]int a]@101");
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.ChangingNonCustomAttribute, "int a", "AAttribute", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute2()
{
var attribute = "public class BAttribute : System.Security.Permissions.SecurityAttribute { }\n\n" +
"public class AAttribute : BAttribute { }\n\n";
var src1 = attribute + @"class C { public void M(int a) {} }";
var src2 = attribute + @"class C { public void M([A]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@143 -> [[A]int a]@143");
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.ChangingNonCustomAttribute, "int a", "AAttribute", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Insert_NotSupportedByRuntime1()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M(int a) {} }";
var src2 = attribute + @"class C { public void M([A]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@72 -> [[A]int a]@72");
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Insert_NotSupportedByRuntime2()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M([A]int a) {} }";
var src2 = attribute + @"class C { public void M([A, B]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]int a]@120 -> [[A, B]int a]@120");
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Delete_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M([A]int a) {} }";
var src2 = attribute + @"class C { public void M(int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]int a]@72 -> [int a]@72");
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Update_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M([System.Obsolete(""1""), B]int a) {} }";
var src2 = attribute + @"class C { public void M([System.Obsolete(""2""), A]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete(\"1\"), B]int a]@120 -> [[System.Obsolete(\"2\"), A]int a]@120");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Update()
{
var attribute = "class A : System.Attribute { public A(int x) {} } ";
var src1 = attribute + "class C { void F([A(0)]int a) {} }";
var src2 = attribute + "class C { void F([A(1)]int a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A(0)]int a]@67 -> [[A(1)]int a]@67");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Parameter_Attribute_Update_WithBodyUpdate()
{
var attribute = "class A : System.Attribute { public A(int x) {} } ";
var src1 = attribute + "class C { void F([A(0)]int a) { F(0); } }";
var src2 = attribute + "class C { void F([A(1)]int a) { F(1); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void F([A(0)]int a) { F(0); }]@60 -> [void F([A(1)]int a) { F(1); }]@60",
"Update [[A(0)]int a]@67 -> [[A(1)]int a]@67");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
#endregion
#region Method Type Parameter
[Fact]
public void MethodTypeParameterInsert1()
{
var src1 = @"class C { public void M() {} }";
var src2 = @"class C { public void M<A>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [<A>]@23",
"Insert [A]@24");
}
[Fact]
public void MethodTypeParameterInsert2()
{
var src1 = @"class C { public void M<A>() {} }";
var src2 = @"class C { public void M<A,B>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [<A>]@23 -> [<A,B>]@23",
"Insert [B]@26");
}
[Fact]
public void MethodTypeParameterDelete1()
{
var src1 = @"class C { public void M<A>() {} }";
var src2 = @"class C { public void M() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [<A>]@23",
"Delete [A]@24");
}
[Fact]
public void MethodTypeParameterDelete2()
{
var src1 = @"class C { public void M<A,B>() {} }";
var src2 = @"class C { public void M<B>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [<A,B>]@23 -> [<B>]@23",
"Delete [A]@24");
}
[Fact]
public void MethodTypeParameterUpdate()
{
var src1 = @"class C { public void M<A>() {} }";
var src2 = @"class C { public void M<B>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [A]@24 -> [B]@24");
}
[Fact]
public void MethodTypeParameterReorder()
{
var src1 = @"class C { public void M<A,B>() {} }";
var src2 = @"class C { public void M<B,A>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@26 -> @24");
}
[Fact]
public void MethodTypeParameterReorderAndUpdate()
{
var src1 = @"class C { public void M<A,B>() {} }";
var src2 = @"class C { public void M<B,C>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@26 -> @24",
"Update [A]@24 -> [C]@26");
}
[Fact]
public void MethodTypeParameter_Attribute_Insert1()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M<T>() {} }";
var src2 = attribute + @"class C { public void M<[A]T>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@72 -> [[A]T]@72");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"),
Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method));
}
[Fact]
public void MethodTypeParameter_Attribute_Insert2()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M<[A]T>() {} }";
var src2 = attribute + @"class C { public void M<[A, B]T>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]T]@120 -> [[A, B]T]@120");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"),
Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method));
}
[Fact]
public void MethodTypeParameter_Attribute_Delete()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M<[A]T>() {} }";
var src2 = attribute + @"class C { public void M<T>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]T]@72 -> [T]@72");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"));
}
[Fact]
public void MethodTypeParameter_Attribute_Update_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M<[System.Obsolete(""1""), B]T>() {} }";
var src2 = attribute + @"class C { public void M<[System.Obsolete(""2""), A]T>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete(\"1\"), B]T]@120 -> [[System.Obsolete(\"2\"), A]T]@120");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"));
}
[Fact]
public void MethodTypeParameter_Attribute_Update()
{
var attribute = "class A : System.Attribute { public A(int x) {} } ";
var src1 = attribute + "class C { void F<[A(0)]T>(T a) {} }";
var src2 = attribute + "class C { void F<[A(1)]T>(T a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A(0)]T]@67 -> [[A(1)]T]@67");
edits.VerifyRudeDiagnostics(
EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"));
}
[Fact]
public void MethodTypeParameter_Attribute_Update_WithBodyUpdate()
{
var attribute = "class A : System.Attribute { public A(int x) {} } ";
var src1 = attribute + "class C { void F<[A(0)]T>(T a) { F(0); } }";
var src2 = attribute + "class C { void F<[A(1)]T>(T a) { F(1); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void F<[A(0)]T>(T a) { F(0); }]@60 -> [void F<[A(1)]T>(T a) { F(1); }]@60",
"Update [[A(0)]T]@67 -> [[A(1)]T]@67");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<[A(1)]T>(T a)"),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"));
}
#endregion
#region Type Type Parameter
[Fact]
public void TypeTypeParameterInsert1()
{
var src1 = @"class C {}";
var src2 = @"class C<A> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [<A>]@7",
"Insert [A]@8");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "A", FeaturesResources.type_parameter));
}
[Fact]
public void TypeTypeParameterInsert2()
{
var src1 = @"class C<A> {}";
var src2 = @"class C<A,B> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [<A>]@7 -> [<A,B>]@7",
"Insert [B]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "B", FeaturesResources.type_parameter));
}
[Fact]
public void TypeTypeParameterDelete1()
{
var src1 = @"class C<A> { }";
var src2 = @"class C { } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [<A>]@7",
"Delete [A]@8");
}
[Fact]
public void TypeTypeParameterDelete2()
{
var src1 = @"class C<A,B> {}";
var src2 = @"class C<B> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [<A,B>]@7 -> [<B>]@7",
"Delete [A]@8");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C<B>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "A")));
}
[Fact]
public void TypeTypeParameterUpdate()
{
var src1 = @"class C<A> {}";
var src2 = @"class C<B> {} ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [A]@8 -> [B]@8");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "B", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "B"));
}
[Fact]
public void TypeTypeParameterReorder()
{
var src1 = @"class C<A,B> { }";
var src2 = @"class C<B,A> { } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@10 -> @8");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter));
}
[Fact]
public void TypeTypeParameterReorderAndUpdate()
{
var src1 = @"class C<A,B> {}";
var src2 = @"class C<B,C> {} ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@10 -> @8",
"Update [A]@8 -> [C]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.Renamed, "C", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "C"));
}
[Fact]
public void TypeTypeParameterAttributeInsert1()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C<T> {}";
var src2 = attribute + @"class C<[A]T> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@56 -> [[A]T]@56");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void TypeTypeParameterAttributeInsert2()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C<[A]T> {}";
var src2 = attribute + @"class C<[A, B]T> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]T]@104 -> [[A, B]T]@104");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void TypeTypeParameterAttributeInsert_SupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C<T> {}";
var src2 = attribute + @"class C<[A]T> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@56 -> [[A]T]@56");
edits.VerifyRudeDiagnostics(
EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void TypeTypeParameterAttributeDelete()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C<[A]T> {}";
var src2 = attribute + @"class C<T> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]T]@56 -> [T]@56");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void TypeTypeParameterAttributeUpdate()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C<[System.Obsolete(""1""), B]T> {}";
var src2 = attribute + @"class C<[System.Obsolete(""2""), A]T> {} ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete(\"1\"), B]T]@104 -> [[System.Obsolete(\"2\"), A]T]@104");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void TypeTypeParameter_Partial_Attribute_AddMultiple()
{
var attributes = @"
class A : System.Attribute {}
class B : System.Attribute {}
";
var srcA1 = "partial class C<T> { }" + attributes;
var srcB1 = "partial class C<T> { }";
var srcA2 = "partial class C<[A]T> { }" + attributes;
var srcB2 = "partial class C<[B]T> { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"),
}),
DocumentResults(diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"),
}),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable()
{
var attributes = @"
class A : System.Attribute {}
class B : System.Attribute {}
";
var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<T> { }" + attributes;
var srcB1 = "partial class C<T> { }";
var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes;
var srcB2 = "partial class C<[B]T> { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")
}),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")
}),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
#endregion
#region Type Parameter Constraints
[Theory]
[InlineData("nonnull")]
[InlineData("struct")]
[InlineData("class")]
[InlineData("new()")]
[InlineData("unmanaged")]
[InlineData("System.IDisposable")]
[InlineData("System.Delegate")]
public void TypeConstraint_Insert(string newConstraint)
{
var src1 = "class C<S,T> { }";
var src2 = "class C<S,T> where T : " + newConstraint + " { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [where T : " + newConstraint + "]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingConstraints, "where T : " + newConstraint, FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : " + newConstraint));
}
[Theory]
[InlineData("nonnull")]
[InlineData("struct")]
[InlineData("class")]
[InlineData("new()")]
[InlineData("unmanaged")]
[InlineData("System.IDisposable")]
[InlineData("System.Delegate")]
public void TypeConstraint_Delete(string oldConstraint)
{
var src1 = "class C<S,T> where T : " + oldConstraint + " { }";
var src2 = "class C<S,T> { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [where T : " + oldConstraint + "]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingConstraints, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void TypeConstraint_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
// note: dynamic is not allowed in constraints
var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}";
var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">"));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void TypeConstraint_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}";
var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingConstraints, "where T : System.Collections.Generic.List<" + newType + ">", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">"));
}
[Fact]
public void TypeConstraint_Delete_WithParameter()
{
var src1 = "class C<S,T> where S : new() where T : class { }";
var src2 = "class C<S> where S : new() { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C<S>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T")));
}
[Fact]
public void TypeConstraint_MultipleClauses_Insert()
{
var src1 = "class C<S,T> where T : class { }";
var src2 = "class C<S,T> where S : unmanaged where T : class { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [where S : unmanaged]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingConstraints, "where S : unmanaged", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : unmanaged"));
}
[Fact]
public void TypeConstraint_MultipleClauses_Delete()
{
var src1 = "class C<S,T> where S : new() where T : class { }";
var src2 = "class C<S,T> where T : class { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [where S : new()]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingConstraints, "S", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "S"));
}
[Fact]
public void TypeConstraint_MultipleClauses_Reorder()
{
var src1 = "class C<S,T> where S : struct where T : class { }";
var src2 = "class C<S,T> where T : class where S : struct { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [where T : class]@30 -> @13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void TypeConstraint_MultipleClauses_UpdateAndReorder()
{
var src1 = "class C<S,T> where S : new() where T : class { }";
var src2 = "class C<T,S> where T : class, I where S : class, new() { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [where T : class]@29 -> @13",
"Reorder [T]@10 -> @8",
"Update [where T : class]@29 -> [where T : class, I]@13",
"Update [where S : new()]@13 -> [where S : class, new()]@32");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.ChangingConstraints, "where T : class, I", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : class, I"),
Diagnostic(RudeEditKind.ChangingConstraints, "where S : class, new()", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : class, new()"));
}
#endregion
#region Top Level Statements
[Fact]
public void TopLevelStatements_Update()
{
var src1 = @"
using System;
Console.WriteLine(""Hello"");
";
var src2 = @"
using System;
Console.WriteLine(""Hello World"");
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19");
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_InsertAndUpdate()
{
var src1 = @"
using System;
Console.WriteLine(""Hello"");
";
var src2 = @"
using System;
Console.WriteLine(""Hello World"");
Console.WriteLine(""What is your name?"");
var name = Console.ReadLine();
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19",
"Insert [Console.WriteLine(\"What is your name?\");]@54",
"Insert [var name = Console.ReadLine();]@96");
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_Insert_NoImplicitMain()
{
var src1 = @"
using System;
";
var src2 = @"
using System;
Console.WriteLine(""Hello World"");
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19");
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_Insert_ImplicitMain()
{
var src1 = @"
using System;
Console.WriteLine(""Hello"");
";
var src2 = @"
using System;
Console.WriteLine(""Hello"");
Console.WriteLine(""World"");
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48");
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_Delete_NoImplicitMain()
{
var src1 = @"
using System;
Console.WriteLine(""Hello World"");
";
var src2 = @"
using System;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19");
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.global_statement));
}
[Fact]
public void TopLevelStatements_Delete_ImplicitMain()
{
var src1 = @"
using System;
Console.WriteLine(""Hello"");
Console.WriteLine(""World"");
";
var src2 = @"
using System;
Console.WriteLine(""Hello"");
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48");
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_StackAlloc()
{
var src1 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(1); }";
var src2 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(2); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", CSharpFeaturesResources.global_statement));
}
[Fact]
public void TopLevelStatements_VoidToInt1()
{
var src1 = @"
using System;
Console.Write(1);
";
var src2 = @"
using System;
Console.Write(1);
return 1;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;"));
}
[Fact]
public void TopLevelStatements_VoidToInt2()
{
var src1 = @"
using System;
Console.Write(1);
return;
";
var src2 = @"
using System;
Console.Write(1);
return 1;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;"));
}
[Fact]
public void TopLevelStatements_VoidToInt3()
{
var src1 = @"
using System;
Console.Write(1);
int Goo()
{
return 1;
}
";
var src2 = @"
using System;
Console.Write(1);
return 1;
int Goo()
{
return 1;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;"));
}
[Fact]
public void TopLevelStatements_AddAwait()
{
var src1 = @"
using System.Threading.Tasks;
await Task.Delay(100);
";
var src2 = @"
using System.Threading.Tasks;
await Task.Delay(100);
await Task.Delay(200);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression));
}
[Fact]
public void TopLevelStatements_DeleteAwait()
{
var src1 = @"
using System.Threading.Tasks;
await Task.Delay(100);
await Task.Delay(200);
";
var src2 = @"
using System.Threading.Tasks;
await Task.Delay(100);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression));
}
[Fact]
public void TopLevelStatements_VoidToTask()
{
var src1 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
";
var src2 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "await Task.Delay(100);"));
}
[Fact]
public void TopLevelStatements_TaskToTaskInt()
{
var src1 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
";
var src2 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
return 1;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;"));
}
[Fact]
public void TopLevelStatements_VoidToTaskInt()
{
var src1 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
";
var src2 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
return await GetInt();
Task<int> GetInt()
{
return Task.FromResult(1);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return await GetInt();"));
}
[Fact]
public void TopLevelStatements_IntToVoid1()
{
var src1 = @"
using System;
Console.Write(1);
return 1;
";
var src2 = @"
using System;
Console.Write(1);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"));
}
[Fact]
public void TopLevelStatements_IntToVoid2()
{
var src1 = @"
using System;
Console.Write(1);
return 1;
";
var src2 = @"
using System;
Console.Write(1);
return;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return;"));
}
[Fact]
public void TopLevelStatements_IntToVoid3()
{
var src1 = @"
using System;
Console.Write(1);
return 1;
int Goo()
{
return 1;
}
";
var src2 = @"
using System;
Console.Write(1);
int Goo()
{
return 1;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "int Goo()\r\n{\r\n return 1;\r\n}"));
}
[Fact]
public void TopLevelStatements_IntToVoid4()
{
var src1 = @"
using System;
Console.Write(1);
return 1;
public class C
{
public int Goo()
{
return 1;
}
}
";
var src2 = @"
using System;
Console.Write(1);
public class C
{
public int Goo()
{
return 1;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"));
}
[Fact]
public void TopLevelStatements_TaskToVoid()
{
var src1 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
";
var src2 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"),
Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression));
}
[Fact]
public void TopLevelStatements_TaskIntToTask()
{
var src1 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
return 1;
";
var src2 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"));
}
[Fact]
public void TopLevelStatements_TaskIntToVoid()
{
var src1 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
return await GetInt();
Task<int> GetInt()
{
return Task.FromResult(1);
}
";
var src2 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"),
Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression));
}
[Fact]
public void TopLevelStatements_WithLambda_Insert()
{
var src1 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
";
var src2 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
Console.WriteLine(1);
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) });
}
[Fact]
public void TopLevelStatements_WithLambda_Update()
{
var src1 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
Console.WriteLine(1);
public class C { }
";
var src2 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
Console.WriteLine(2);
public class C { }
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) });
}
[Fact]
public void TopLevelStatements_WithLambda_Delete()
{
var src1 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
Console.WriteLine(1);
public class C { }
";
var src2 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
public class C { }
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) });
}
[Fact]
public void TopLevelStatements_UpdateMultiple()
{
var src1 = @"
using System;
Console.WriteLine(1);
Console.WriteLine(2);
public class C { }
";
var src2 = @"
using System;
Console.WriteLine(3);
Console.WriteLine(4);
public class C { }
";
var edits = GetTopEdits(src1, src2);
// Since each individual statement is a separate update to a separate node, this just validates we correctly
// only analyze the things once
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_MoveToOtherFile()
{
var srcA1 = @"
using System;
Console.WriteLine(1);
public class A
{
}";
var srcB1 = @"
using System;
public class B
{
}";
var srcA2 = @"
using System;
public class A
{
}";
var srcB2 = @"
using System;
Console.WriteLine(2);
public class B
{
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new [] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")) }),
});
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
[UseExportProvider]
public class TopLevelEditingTests : EditingTestBase
{
#region Usings
[Fact]
public void Using_Global_Insert()
{
var src1 = @"
using System.Collections.Generic;
";
var src2 = @"
global using D = System.Diagnostics;
global using System.Collections;
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [global using D = System.Diagnostics;]@2",
"Insert [global using System.Collections;]@40");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Delete1()
{
var src1 = @"
using System.Diagnostics;
";
var src2 = @"";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [using System.Diagnostics;]@2");
Assert.IsType<UsingDirectiveSyntax>(edits.Edits.First().OldNode);
Assert.Null(edits.Edits.First().NewNode);
}
[Fact]
public void Using_Delete2()
{
var src1 = @"
using D = System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
";
var src2 = @"
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [using D = System.Diagnostics;]@2",
"Delete [using System.Collections;]@33");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Insert()
{
var src1 = @"
using System.Collections.Generic;
";
var src2 = @"
using D = System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [using D = System.Diagnostics;]@2",
"Insert [using System.Collections;]@33");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Update1()
{
var src1 = @"
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
";
var src2 = @"
using System.Diagnostics;
using X = System.Collections;
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [using System.Collections;]@29 -> [using X = System.Collections;]@29");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Update2()
{
var src1 = @"
using System.Diagnostics;
using X1 = System.Collections;
using System.Collections.Generic;
";
var src2 = @"
using System.Diagnostics;
using X2 = System.Collections;
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [using X1 = System.Collections;]@29 -> [using X2 = System.Collections;]@29");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Update3()
{
var src1 = @"
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
";
var src2 = @"
using System;
using System.Collections;
using System.Collections.Generic;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [using System.Diagnostics;]@2 -> [using System;]@2");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Using_Reorder1()
{
var src1 = @"
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
";
var src2 = @"
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [using System.Diagnostics;]@2 -> @64");
}
[Fact]
public void Using_InsertDelete1()
{
var src1 = @"
namespace N
{
using System.Collections;
}
namespace M
{
}
";
var src2 = @"
namespace N
{
}
namespace M
{
using System.Collections;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [using System.Collections;]@43",
"Delete [using System.Collections;]@22");
}
[Fact]
public void Using_InsertDelete2()
{
var src1 = @"
namespace N
{
using System.Collections;
}
";
var src2 = @"
using System.Collections;
namespace N
{
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [using System.Collections;]@2",
"Delete [using System.Collections;]@22");
}
[Fact]
public void Using_Delete_ChangesCodeMeaning()
{
// This test specifically validates the scenario we _don't_ support, namely when inserting or deleting
// a using directive, if existing code changes in meaning as a result, we don't issue edits for that code.
// If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself.
var src1 = @"
using System.IO;
using DirectoryInfo = N.C;
namespace N
{
public class C
{
public C(string a) { }
public FileAttributes Attributes { get; set; }
}
public class D
{
public void M()
{
var d = new DirectoryInfo(""aa"");
var x = directoryInfo.Attributes;
}
}
}";
var src2 = @"
using System.IO;
namespace N
{
public class C
{
public C(string a) { }
public FileAttributes Attributes { get; set; }
}
public class D
{
public void M()
{
var d = new DirectoryInfo(""aa"");
var x = directoryInfo.Attributes;
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [using DirectoryInfo = N.C;]@20");
edits.VerifySemantics();
}
[Fact]
public void Using_Insert_ForNewCode()
{
// As distinct from the above, this test validates a real world scenario of inserting a using directive
// and changing code that utilizes the new directive to some effect.
var src1 = @"
namespace N
{
class Program
{
static void Main(string[] args)
{
}
}
}";
var src2 = @"
using System;
namespace N
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main")));
}
[Fact]
public void Using_Delete_ForOldCode()
{
var src1 = @"
using System;
namespace N
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Hello World!"");
}
}
}";
var src2 = @"
namespace N
{
class Program
{
static void Main(string[] args)
{
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main")));
}
[Fact]
public void Using_Insert_CreatesAmbiguousCode()
{
// This test validates that we still issue edits for changed valid code, even when unchanged
// code has ambiguities after adding a using.
var src1 = @"
using System.Threading;
namespace N
{
class C
{
void M()
{
// Timer exists in System.Threading and System.Timers
var t = new Timer(s => System.Console.WriteLine(s));
}
}
}";
var src2 = @"
using System.Threading;
using System.Timers;
namespace N
{
class C
{
void M()
{
// Timer exists in System.Threading and System.Timers
var t = new Timer(s => System.Console.WriteLine(s));
}
void M2()
{
// TimersDescriptionAttribute only exists in System.Timers
System.Console.WriteLine(new TimersDescriptionAttribute(""""));
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("N.C.M2")));
}
#endregion
#region Extern Alias
[Fact]
public void ExternAliasUpdate()
{
var src1 = "extern alias X;";
var src2 = "extern alias Y;";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [extern alias X;]@0 -> [extern alias Y;]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Update, "extern alias Y;", CSharpFeaturesResources.extern_alias));
}
[Fact]
public void ExternAliasInsert()
{
var src1 = "";
var src2 = "extern alias Y;";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [extern alias Y;]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "extern alias Y;", CSharpFeaturesResources.extern_alias));
}
[Fact]
public void ExternAliasDelete()
{
var src1 = "extern alias Y;";
var src2 = "";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [extern alias Y;]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.extern_alias));
}
#endregion
#region Assembly/Module Attributes
[Fact]
public void Insert_TopLevelAttribute()
{
var src1 = "";
var src2 = "[assembly: System.Obsolete(\"2\")]";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [[assembly: System.Obsolete(\"2\")]]@0",
"Insert [System.Obsolete(\"2\")]@11");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "[assembly: System.Obsolete(\"2\")]", FeaturesResources.attribute));
}
[Fact]
public void Delete_TopLevelAttribute()
{
var src1 = "[assembly: System.Obsolete(\"2\")]";
var src2 = "";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [[assembly: System.Obsolete(\"2\")]]@0",
"Delete [System.Obsolete(\"2\")]@11");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, null, FeaturesResources.attribute));
}
[Fact]
public void Update_TopLevelAttribute()
{
var src1 = "[assembly: System.Obsolete(\"1\")]";
var src2 = "[assembly: System.Obsolete(\"2\")]";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[assembly: System.Obsolete(\"1\")]]@0 -> [[assembly: System.Obsolete(\"2\")]]@0",
"Update [System.Obsolete(\"1\")]@11 -> [System.Obsolete(\"2\")]@11");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Update, "System.Obsolete(\"2\")", FeaturesResources.attribute));
}
[Fact]
public void Reorder_TopLevelAttribute()
{
var src1 = "[assembly: System.Obsolete(\"1\")][assembly: System.Obsolete(\"2\")]";
var src2 = "[assembly: System.Obsolete(\"2\")][assembly: System.Obsolete(\"1\")]";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [[assembly: System.Obsolete(\"2\")]]@32 -> @0");
edits.VerifyRudeDiagnostics();
}
#endregion
#region Types
[Theory]
[InlineData("class", "struct")]
[InlineData("class", "record")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874
[InlineData("class", "record struct")]
[InlineData("class", "interface")]
[InlineData("struct", "record struct")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874
public void Type_Kind_Update(string oldKeyword, string newKeyword)
{
var src1 = oldKeyword + " C { }";
var src2 = newKeyword + " C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [" + oldKeyword + " C { }]@0 -> [" + newKeyword + " C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeKindUpdate, newKeyword + " C"));
}
[Theory]
[InlineData("class", "struct")]
[InlineData("class", "record")]
[InlineData("class", "record struct")]
[InlineData("class", "interface")]
[InlineData("struct", "record struct")]
public void Type_Kind_Update_Reloadable(string oldKeyword, string newKeyword)
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + newKeyword + " C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }]@145 -> [[CreateNewOnMetadataUpdate]" + newKeyword + " C { }]@145");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Modifiers_Static_Remove()
{
var src1 = "public static class C { }";
var src2 = "public class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public static class C { }]@0 -> [public class C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public class C", FeaturesResources.class_));
}
[Theory]
[InlineData("public")]
[InlineData("protected")]
[InlineData("private")]
[InlineData("private protected")]
[InlineData("internal protected")]
public void Type_Modifiers_Accessibility_Change(string accessibility)
{
var src1 = accessibility + " class C { }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [" + accessibility + " class C { }]@0 -> [class C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "class C", FeaturesResources.class_));
}
[Theory]
[InlineData("public", "public")]
[InlineData("internal", "internal")]
[InlineData("", "internal")]
[InlineData("internal", "")]
[InlineData("protected", "protected")]
[InlineData("private", "private")]
[InlineData("private protected", "private protected")]
[InlineData("internal protected", "internal protected")]
public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB)
{
var srcA1 = accessibilityA + " partial class C { }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = accessibilityB + " partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(),
});
}
[Fact]
public void Type_Modifiers_Internal_Remove()
{
var src1 = "internal interface C { }";
var src2 = "interface C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact]
public void Type_Modifiers_Internal_Add()
{
var src1 = "struct C { }";
var src2 = "internal struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact]
public void Type_Modifiers_Accessibility_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[CreateNewOnMetadataUpdate]public class C { }]@145 -> [[CreateNewOnMetadataUpdate]internal class C { }]@145");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Theory]
[InlineData("class")]
[InlineData("struct")]
[InlineData("interface")]
[InlineData("record")]
[InlineData("record struct")]
public void Type_Modifiers_NestedPrivateInInterface_Remove(string keyword)
{
var src1 = "interface C { private " + keyword + " S { } }";
var src2 = "interface C { " + keyword + " S { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, keyword + " S", GetResource(keyword)));
}
[Theory]
[InlineData("class")]
[InlineData("struct")]
[InlineData("interface")]
[InlineData("record")]
[InlineData("record struct")]
public void Type_Modifiers_NestedPrivateInClass_Add(string keyword)
{
var src1 = "class C { " + keyword + " S { } }";
var src2 = "class C { private " + keyword + " S { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Theory]
[InlineData("class")]
[InlineData("struct")]
[InlineData("interface")]
[InlineData("record")]
[InlineData("record struct")]
public void Type_Modifiers_NestedPublicInInterface_Add(string keyword)
{
var src1 = "interface C { " + keyword + " S { } }";
var src2 = "interface C { public " + keyword + " S { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")]
public void Type_Modifiers_Unsafe_Add()
{
var src1 = "public class C { }";
var src2 = "public unsafe class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public class C { }]@0 -> [public unsafe class C { }]@0");
edits.VerifyRudeDiagnostics();
}
[Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")]
public void Type_Modifiers_Unsafe_Remove()
{
var src1 = @"
using System;
unsafe delegate void D();
class C
{
unsafe class N { }
public unsafe event Action<int> A { add { } remove { } }
unsafe int F() => 0;
unsafe int X;
unsafe int Y { get; }
unsafe C() {}
unsafe ~C() {}
}
";
var src2 = @"
using System;
delegate void D();
class C
{
class N { }
public event Action<int> A { add { } remove { } }
int F() => 0;
int X;
int Y { get; }
C() {}
~C() {}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [unsafe delegate void D();]@17 -> [delegate void D();]@17",
"Update [unsafe class N { }]@60 -> [class N { }]@53",
"Update [public unsafe event Action<int> A { add { } remove { } }]@84 -> [public event Action<int> A { add { } remove { } }]@70",
"Update [unsafe int F() => 0;]@146 -> [int F() => 0;]@125",
"Update [unsafe int X;]@172 -> [int X;]@144",
"Update [unsafe int Y { get; }]@191 -> [int Y { get; }]@156",
"Update [unsafe C() {}]@218 -> [C() {}]@176",
"Update [unsafe ~C() {}]@237 -> [~C() {}]@188");
edits.VerifyRudeDiagnostics();
}
[Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")]
public void Type_Modifiers_Unsafe_DeleteInsert()
{
var srcA1 = "partial class C { unsafe void F() { } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"))
}),
});
}
[Fact]
public void Type_Modifiers_Ref_Add()
{
var src1 = "public struct C { }";
var src2 = "public ref struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public struct C { }]@0 -> [public ref struct C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public ref struct C", CSharpFeaturesResources.struct_));
}
[Fact]
public void Type_Modifiers_Ref_Remove()
{
var src1 = "public ref struct C { }";
var src2 = "public struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public ref struct C { }]@0 -> [public struct C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_));
}
[Fact]
public void Type_Modifiers_ReadOnly_Add()
{
var src1 = "public struct C { }";
var src2 = "public readonly struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public struct C { }]@0 -> [public readonly struct C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly struct C", CSharpFeaturesResources.struct_));
}
[Fact]
public void Type_Modifiers_ReadOnly_Remove()
{
var src1 = "public readonly struct C { }";
var src2 = "public struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public readonly struct C { }]@0 -> [public struct C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_));
}
[Theory]
[InlineData("[System.CLSCompliantAttribute]", "CLSCompliantAttribute")]
[InlineData("[System.Diagnostics.CodeAnalysis.AllowNullAttribute]", "AllowNullAttribute")]
[InlineData("[System.Diagnostics.CodeAnalysis.DisallowNullAttribute]", "DisallowNullAttribute")]
[InlineData("[System.Diagnostics.CodeAnalysis.MaybeNullAttribute]", "MaybeNullAttribute")]
[InlineData("[System.Diagnostics.CodeAnalysis.NotNullAttribute]", "NotNullAttribute")]
[InlineData("[System.NonSerializedAttribute]", "NonSerializedAttribute")]
[InlineData("[System.Reflection.AssemblyAlgorithmIdAttribute]", "AssemblyAlgorithmIdAttribute")]
[InlineData("[System.Reflection.AssemblyCultureAttribute]", "AssemblyCultureAttribute")]
[InlineData("[System.Reflection.AssemblyFlagsAttribute]", "AssemblyFlagsAttribute")]
[InlineData("[System.Reflection.AssemblyVersionAttribute]", "AssemblyVersionAttribute")]
[InlineData("[System.Runtime.CompilerServices.DllImportAttribute]", "DllImportAttribute")]
[InlineData("[System.Runtime.CompilerServices.IndexerNameAttribute]", "IndexerNameAttribute")]
[InlineData("[System.Runtime.CompilerServices.MethodImplAttribute]", "MethodImplAttribute")]
[InlineData("[System.Runtime.CompilerServices.SpecialNameAttribute]", "SpecialNameAttribute")]
[InlineData("[System.Runtime.CompilerServices.TypeForwardedToAttribute]", "TypeForwardedToAttribute")]
[InlineData("[System.Runtime.InteropServices.ComImportAttribute]", "ComImportAttribute")]
[InlineData("[System.Runtime.InteropServices.DefaultParameterValueAttribute]", "DefaultParameterValueAttribute")]
[InlineData("[System.Runtime.InteropServices.FieldOffsetAttribute]", "FieldOffsetAttribute")]
[InlineData("[System.Runtime.InteropServices.InAttribute]", "InAttribute")]
[InlineData("[System.Runtime.InteropServices.MarshalAsAttribute]", "MarshalAsAttribute")]
[InlineData("[System.Runtime.InteropServices.OptionalAttribute]", "OptionalAttribute")]
[InlineData("[System.Runtime.InteropServices.OutAttribute]", "OutAttribute")]
[InlineData("[System.Runtime.InteropServices.PreserveSigAttribute]", "PreserveSigAttribute")]
[InlineData("[System.Runtime.InteropServices.StructLayoutAttribute]", "StructLayoutAttribute")]
[InlineData("[System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute]", "WindowsRuntimeImportAttribute")]
[InlineData("[System.Security.DynamicSecurityMethodAttribute]", "DynamicSecurityMethodAttribute")]
[InlineData("[System.SerializableAttribute]", "SerializableAttribute")]
[InlineData("[System.Runtime.CompilerServices.AsyncMethodBuilderAttribute]", "AsyncMethodBuilderAttribute")]
public void Type_Attribute_Insert_SupportedByRuntime_NonCustomAttribute(string attributeType, string attributeName)
{
var src1 = @"class C { public void M(int a) {} }";
var src2 = attributeType + @"class C { public void M(int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { public void M(int a) {} }]@0 -> [" + attributeType + "class C { public void M(int a) {} }]@0");
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.ChangingNonCustomAttribute, "class C", attributeName, FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Update_NotSupportedByRuntime1()
{
var attribute = "public class A1Attribute : System.Attribute { }\n\n" +
"public class A2Attribute : System.Attribute { }\n\n";
var src1 = attribute + "[A1]class C { }";
var src2 = attribute + "[A2]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A1]class C { }]@98 -> [[A2]class C { }]@98");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Update_NotSupportedByRuntime2()
{
var src1 = "[System.Obsolete(\"1\")]class C { }";
var src2 = "[System.Obsolete(\"2\")]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete(\"1\")]class C { }]@0 -> [[System.Obsolete(\"2\")]class C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Delete_NotSupportedByRuntime1()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + "[A, B]class C { }";
var src2 = attribute + "[A]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A, B]class C { }]@96 -> [[A]class C { }]@96");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Delete_NotSupportedByRuntime2()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + "[B, A]class C { }";
var src2 = attribute + "[A]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[B, A]class C { }]@96 -> [[A]class C { }]@96");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Change_Reloadable()
{
var attributeSrc = @"
public class A1 : System.Attribute { }
public class A2 : System.Attribute { }
public class A3 : System.Attribute { }
";
var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }";
var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[CreateNewOnMetadataUpdate, A1, A2]class C { }]@267 -> [[CreateNewOnMetadataUpdate, A2, A3]class C { }]@267");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Attribute_ReloadableRemove()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var src2 = ReloadableAttributeSrc + "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Attribute_ReloadableAdd()
{
var src1 = ReloadableAttributeSrc + "class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_Attribute_ReloadableBase()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { void F() {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Attribute_Add()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + "[A]class C { }";
var src2 = attribute + "[A, B]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]class C { }]@96 -> [[A, B]class C { }]@96");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_Attribute_Add_NotSupportedByRuntime1()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + "[A]class C { }";
var src2 = attribute + "[A, B]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]class C { }]@96 -> [[A, B]class C { }]@96");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Add_NotSupportedByRuntime2()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "class C { }";
var src2 = attribute + "[A]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { }]@48 -> [[A]class C { }]@48");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Attribute_Reorder1()
{
var src1 = "[A(1), B(2), C(3)]class C { }";
var src2 = "[C(3), A(1), B(2)]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A(1), B(2), C(3)]class C { }]@0 -> [[C(3), A(1), B(2)]class C { }]@0");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Type_Attribute_Reorder2()
{
var src1 = "[A, B, C]class C { }";
var src2 = "[B, C, A]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A, B, C]class C { }]@0 -> [[B, C, A]class C { }]@0");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Type_Attribute_ReorderAndUpdate_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + "[System.Obsolete(\"1\"), A, B]class C { }";
var src2 = attribute + "[A, B, System.Obsolete(\"2\")]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete(\"1\"), A, B]class C { }]@96 -> [[A, B, System.Obsolete(\"2\")]class C { }]@96");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_));
}
[Theory]
[InlineData("class")]
[InlineData("struct")]
[InlineData("interface")]
[InlineData("record")]
[InlineData("record struct")]
public void Type_Rename(string keyword)
{
var src1 = keyword + " C { }";
var src2 = keyword + " D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [" + keyword + " C { }]@0 -> [" + keyword + " D { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, keyword + " D", GetResource(keyword)));
}
[Fact]
public void Type_Rename_AddAndDeleteMember()
{
var src1 = "class C { int x = 1; }";
var src2 = "class D { void F() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { int x = 1; }]@0 -> [class D { void F() { } }]@0",
"Insert [void F() { }]@10",
"Insert [()]@16",
"Delete [int x = 1;]@10",
"Delete [int x = 1]@10",
"Delete [x = 1]@14");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_));
}
[Fact]
[WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")]
public void Type_Rename_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[CreateNewOnMetadataUpdate]class C { }]@145 -> [[CreateNewOnMetadataUpdate]class D { }]@145");
// TODO: expected: Replace edit of D
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_));
}
[Fact]
[WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")]
public void Type_Rename_Reloadable_AddAndDeleteMember()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { int x = 1; }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { void F() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[CreateNewOnMetadataUpdate]class C { int x = 1; }]@145 -> [[CreateNewOnMetadataUpdate]class D { void F() { } }]@145",
"Insert [void F() { }]@182",
"Insert [()]@188",
"Delete [int x = 1;]@182",
"Delete [int x = 1]@182",
"Delete [x = 1]@186");
// TODO: expected: Replace edit of D
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_));
}
[Fact]
public void Interface_NoModifiers_Insert()
{
var src1 = "";
var src2 = "interface C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Interface_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { } ";
var src2 = "namespace N { interface C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Interface_NoModifiers_IntoType_Insert()
{
var src1 = "interface N { }";
var src2 = "interface N { interface C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Class_NoModifiers_Insert()
{
var src1 = "";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Class_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { }";
var src2 = "namespace N { class C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Class_NoModifiers_IntoType_Insert()
{
var src1 = "struct N { }";
var src2 = "struct N { class C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Struct_NoModifiers_Insert()
{
var src1 = "";
var src2 = "struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Struct_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { }";
var src2 = "namespace N { struct C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Struct_NoModifiers_IntoType_Insert()
{
var src1 = "struct N { }";
var src2 = "struct N { struct C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Type_BaseType_Add_Unchanged()
{
var src1 = "class C { }";
var src2 = "class C : object { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { }]@0 -> [class C : object { }]@0");
edits.VerifySemantics();
}
[Fact]
public void Type_BaseType_Add_Changed()
{
var src1 = "class C { }";
var src2 = "class C : D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { }]@0 -> [class C : D { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("string[]", "string[]?")]
[InlineData("object", "dynamic")]
[InlineData("dynamic?", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Type_BaseType_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}";
var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Type_BaseType_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}";
var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_BaseType_Update_CompileTimeTypeUnchanged()
{
var src1 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<A> {}";
var src2 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<B> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact]
public void Type_BaseInterface_Add()
{
var src1 = "class C { }";
var src2 = "class C : IDisposable { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C { }]@0 -> [class C : IDisposable { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_BaseInterface_Delete_Inherited()
{
var src1 = @"
interface B {}
interface A : B {}
class C : A, B {}
";
var src2 = @"
interface B {}
interface A : B {}
class C : A {}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact]
public void Type_BaseInterface_Reorder()
{
var src1 = "class C : IGoo, IBar { }";
var src2 = "class C : IBar, IGoo { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [class C : IGoo, IBar { }]@0 -> [class C : IBar, IGoo { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("object", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Type_BaseInterface_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}";
var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}";
var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_));
}
[Fact]
public void Type_Base_Partial()
{
var srcA1 = "partial class C : B, I { }";
var srcB1 = "partial class C : J { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C : B, I, J { }";
var srcC = @"
class B {}
interface I {}
interface J {}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults()
});
}
[Fact]
public void Type_Base_Partial_InsertDeleteAndUpdate()
{
var srcA1 = "partial class C { }";
var srcB1 = "";
var srcC1 = "partial class C { }";
var srcA2 = "";
var srcB2 = "partial class C : D { }";
var srcC2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "partial class C", FeaturesResources.class_) }),
DocumentResults(),
});
}
[Fact]
public void Type_Base_InsertDelete()
{
var srcA1 = "";
var srcB1 = "class C : B, I { }";
var srcA2 = "class C : B, I { }";
var srcB2 = "";
var srcC = @"
class B {}
interface I {}
interface J {}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults()
});
}
[Fact]
public void Type_Reloadable_NotSupportedByRuntime()
{
var src1 = ReloadableAttributeSrc + @"
[CreateNewOnMetadataUpdate]
public class C
{
void F() { System.Console.WriteLine(1); }
}";
var src2 = ReloadableAttributeSrc + @"
[CreateNewOnMetadataUpdate]
public class C
{
void F() { System.Console.WriteLine(2); }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void F()", "CreateNewOnMetadataUpdateAttribute"));
}
[Fact]
public void Type_Insert_AbstractVirtualOverride()
{
var src1 = "";
var src2 = @"
public abstract class C<T>
{
public abstract void F();
public virtual void G() {}
public override string ToString() => null;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Type_Insert_NotSupportedByRuntime()
{
var src1 = @"
public class C
{
void F()
{
}
}";
var src2 = @"
public class C
{
void F()
{
}
}
public class D
{
void M()
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "public class D", FeaturesResources.class_));
}
[Fact]
public void Type_Insert_Reloadable()
{
var src1 = ReloadableAttributeSrc + "";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C")));
}
[Fact]
public void InterfaceInsert()
{
var src1 = "";
var src2 = @"
public interface I
{
void F();
static void G() {}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void RefStructInsert()
{
var src1 = "";
var src2 = "ref struct X { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [ref struct X { }]@0");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Struct_ReadOnly_Insert()
{
var src1 = "";
var src2 = "readonly struct X { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [readonly struct X { }]@0");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Struct_RefModifier_Add()
{
var src1 = "struct X { }";
var src2 = "ref struct X { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [struct X { }]@0 -> [ref struct X { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "ref struct X", CSharpFeaturesResources.struct_));
}
[Fact]
public void Struct_ReadonlyModifier_Add()
{
var src1 = "struct X { }";
var src2 = "readonly struct X { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [struct X { }]@0 -> [readonly struct X { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly struct X", SyntaxFacts.GetText(SyntaxKind.StructKeyword)));
}
[Theory]
[InlineData("ref")]
[InlineData("readonly")]
public void Struct_Modifiers_Partial_InsertDelete(string modifier)
{
var srcA1 = modifier + " partial struct S { }";
var srcB1 = "partial struct S { }";
var srcA2 = "partial struct S { }";
var srcB2 = modifier + " partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults()
});
}
[Fact]
public void Class_ImplementingInterface_Add()
{
var src1 = @"
using System;
public interface ISample
{
string Get();
}
public interface IConflict
{
string Get();
}
public class BaseClass : ISample
{
public virtual string Get() => string.Empty;
}
";
var src2 = @"
using System;
public interface ISample
{
string Get();
}
public interface IConflict
{
string Get();
}
public class BaseClass : ISample
{
public virtual string Get() => string.Empty;
}
public class SubClass : BaseClass, IConflict
{
public override string Get() => string.Empty;
string IConflict.Get() => String.Empty;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Insert [public class SubClass : BaseClass, IConflict
{
public override string Get() => string.Empty;
string IConflict.Get() => String.Empty;
}]@219",
"Insert [public override string Get() => string.Empty;]@272",
"Insert [string IConflict.Get() => String.Empty;]@325",
"Insert [()]@298",
"Insert [()]@345");
// Here we add a class implementing an interface and a method inside it with explicit interface specifier.
// We want to be sure that adding the method will not tirgger a rude edit as it happens if adding a single method with explicit interface specifier.
edits.VerifyRudeDiagnostics();
}
[WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")]
[Fact]
public void Interface_InsertMembers()
{
var src1 = @"
using System;
interface I
{
}
";
var src2 = @"
using System;
interface I
{
static int StaticField = 10;
static void StaticMethod() { }
void VirtualMethod1() { }
virtual void VirtualMethod2() { }
abstract void AbstractMethod();
sealed void NonVirtualMethod() { }
public static int operator +(I a, I b) => 1;
static int StaticProperty1 { get => 1; set { } }
static int StaticProperty2 => 1;
virtual int VirtualProperty1 { get => 1; set { } }
virtual int VirtualProperty2 { get => 1; }
int VirtualProperty3 { get => 1; set { } }
int VirtualProperty4 { get => 1; }
abstract int AbstractProperty1 { get; set; }
abstract int AbstractProperty2 { get; }
sealed int NonVirtualProperty => 1;
int this[byte virtualIndexer] => 1;
int this[sbyte virtualIndexer] { get => 1; }
virtual int this[ushort virtualIndexer] { get => 1; set {} }
virtual int this[short virtualIndexer] { get => 1; set {} }
abstract int this[uint abstractIndexer] { get; set; }
abstract int this[int abstractIndexer] { get; }
sealed int this[ulong nonVirtualIndexer] { get => 1; set {} }
sealed int this[long nonVirtualIndexer] { get => 1; set {} }
static event Action StaticEvent;
static event Action StaticEvent2 { add { } remove { } }
event Action VirtualEvent { add { } remove { } }
abstract event Action AbstractEvent;
sealed event Action NonVirtualEvent { add { } remove { } }
abstract class C { }
interface J { }
enum E { }
delegate void D();
}
";
var edits = GetTopEdits(src1, src2);
// TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128.
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoInterface, "static void StaticMethod()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertVirtual, "void VirtualMethod1()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertVirtual, "virtual void VirtualMethod2()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertVirtual, "abstract void AbstractMethod()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed void NonVirtualMethod()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertOperator, "public static int operator +(I a, I b)", FeaturesResources.operator_),
Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty1", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", CSharpFeaturesResources.property_getter),
Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty1", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty2", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty3", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty4", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty1", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty2", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", CSharpFeaturesResources.property_getter),
Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", CSharpFeaturesResources.indexer_getter),
Diagnostic(RudeEditKind.InsertVirtual, "int this[sbyte virtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[ushort virtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[short virtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[uint abstractIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[int abstractIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[ulong nonVirtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[long nonVirtualIndexer]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertIntoInterface, "static event Action StaticEvent2", FeaturesResources.event_),
Diagnostic(RudeEditKind.InsertVirtual, "event Action VirtualEvent", FeaturesResources.event_),
Diagnostic(RudeEditKind.InsertIntoInterface, "sealed event Action NonVirtualEvent", FeaturesResources.event_),
Diagnostic(RudeEditKind.InsertIntoInterface, "StaticField = 10", FeaturesResources.field),
Diagnostic(RudeEditKind.InsertIntoInterface, "StaticEvent", CSharpFeaturesResources.event_field),
Diagnostic(RudeEditKind.InsertVirtual, "AbstractEvent", CSharpFeaturesResources.event_field));
}
[Fact]
public void Interface_InsertDelete()
{
var srcA1 = @"
interface I
{
static void M() { }
}
";
var srcB1 = @"
";
var srcA2 = @"
";
var srcB2 = @"
interface I
{
static void M() { }
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("M"))
}),
});
}
[Fact]
public void Type_Generic_InsertMembers()
{
var src1 = @"
using System;
class C<T>
{
}
";
var src2 = @"
using System;
class C<T>
{
void M() {}
int P1 { get; set; }
int P2 { get => 1; set {} }
int this[int i] { get => 1; set {} }
event Action E { add {} remove {} }
event Action EF;
int F1, F2;
enum E {}
interface I {}
class D {}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoGenericType, "void M()", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertIntoGenericType, "int P1", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertIntoGenericType, "int P2", FeaturesResources.auto_property),
Diagnostic(RudeEditKind.InsertIntoGenericType, "int this[int i]", FeaturesResources.indexer_),
Diagnostic(RudeEditKind.InsertIntoGenericType, "event Action E", FeaturesResources.event_),
Diagnostic(RudeEditKind.InsertIntoGenericType, "EF", CSharpFeaturesResources.event_field),
Diagnostic(RudeEditKind.InsertIntoGenericType, "F1", FeaturesResources.field),
Diagnostic(RudeEditKind.InsertIntoGenericType, "F2", FeaturesResources.field));
}
[Fact]
public void Type_Generic_InsertMembers_Reloadable()
{
var src1 = ReloadableAttributeSrc + @"
[CreateNewOnMetadataUpdate]
class C<T>
{
}
";
var src2 = ReloadableAttributeSrc + @"
[CreateNewOnMetadataUpdate]
class C<T>
{
void M() {}
int P1 { get; set; }
int P2 { get => 1; set {} }
int this[int i] { get => 1; set {} }
event System.Action E { add {} remove {} }
event System.Action EF;
int F1, F2;
enum E {}
interface I {}
class D {}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Generic_DeleteInsert()
{
var srcA1 = @"
class C<T> { void F() {} }
struct S<T> { void F() {} }
interface I<T> { void F() {} }
";
var srcB1 = "";
var srcA2 = srcB1;
var srcB2 = srcA1;
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "struct S<T>"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "interface I<T>"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"),
})
});
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")]
[WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")]
public void Type_TypeParameter_Insert_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C<T> { void F() { } }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C<T, S> { int x = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Type_Delete()
{
var src1 = @"
class C { void F() {} }
struct S { void F() {} }
interface I { void F() {} }
";
var src2 = "";
GetTopEdits(src1, src2).VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")),
Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(CSharpFeaturesResources.struct_, "S")),
Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I")));
}
[Fact]
public void Type_Delete_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }";
var src2 = ReloadableAttributeSrc;
GetTopEdits(src1, src2).VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")));
}
[Fact]
public void Type_Partial_DeleteDeclaration()
{
var srcA1 = "partial class C { void F() {} void M() { } }";
var srcB1 = "partial class C { void G() {} }";
var srcA2 = "";
var srcB2 = "partial class C { void G() {} void M() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.method, "C.F()")) }),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("M")),
})
});
}
[Fact]
public void Type_Partial_InsertFirstDeclaration()
{
var src1 = "";
var src2 = "partial class C { void F() {} }";
GetTopEdits(src1, src2).VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C"), preserveLocalVariables: false) });
}
[Fact]
public void Type_Partial_InsertSecondDeclaration()
{
var srcA1 = "partial class C { void F() {} }";
var srcB1 = "";
var srcA2 = "partial class C { void F() {} }";
var srcB2 = "partial class C { void G() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G"), preserveLocalVariables: false)
}),
});
}
[Fact]
public void Type_Partial_Reloadable()
{
var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }";
var srcB1 = "";
var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }";
var srcB2 = "partial class C { void G() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")
}),
});
}
[Fact]
public void Type_DeleteInsert()
{
var srcA1 = @"
class C { void F() {} }
struct S { void F() {} }
interface I { void F() {} }
";
var srcB1 = "";
var srcA2 = srcB1;
var srcB2 = srcA1;
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember("F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")),
})
});
}
[Fact]
public void Type_DeleteInsert_Reloadable()
{
var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }";
var srcB1 = "";
var srcA2 = ReloadableAttributeSrc;
var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")),
})
});
}
[Fact]
public void Type_NonInsertableMembers_DeleteInsert()
{
var srcA1 = @"
abstract class C
{
public abstract void AbstractMethod();
public virtual void VirtualMethod() {}
public override string ToString() => null;
public void I.G() {}
}
interface I
{
void G();
void F() {}
}
";
var srcB1 = "";
var srcA2 = srcB1;
var srcB2 = srcA1;
// TODO: The methods without bodies do not need to be updated.
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")),
})
});
}
[Fact]
public void Type_Attribute_NonInsertableMembers_DeleteInsert()
{
var srcA1 = @"
abstract class C
{
public abstract void AbstractMethod();
public virtual void VirtualMethod() {}
public override string ToString() => null;
public void I.G() {}
}
interface I
{
void G();
void F() {}
}
";
var srcB1 = "";
var srcA2 = "";
var srcB2 = @"
abstract class C
{
[System.Obsolete]public abstract void AbstractMethod();
public virtual void VirtualMethod() {}
public override string ToString() => null;
public void I.G() {}
}
interface I
{
[System.Obsolete]void G();
void F() {}
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")),
})
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_DeleteInsert_DataMembers()
{
var srcA1 = @"
class C
{
public int x = 1;
public int y = 2;
public int P { get; set; } = 3;
public event System.Action E = new System.Action(null);
}
";
var srcB1 = "";
var srcA2 = "";
var srcB2 = @"
class C
{
public int x = 1;
public int y = 2;
public int P { get; set; } = 3;
public event System.Action E = new System.Action(null);
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true),
})
});
}
[Fact]
public void Type_DeleteInsert_DataMembers_PartialSplit()
{
var srcA1 = @"
class C
{
public int x = 1;
public int y = 2;
public int P { get; set; } = 3;
}
";
var srcB1 = "";
var srcA2 = @"
partial class C
{
public int x = 1;
public int y = 2;
}
";
var srcB2 = @"
partial class C
{
public int P { get; set; } = 3;
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true),
})
});
}
[Fact]
public void Type_DeleteInsert_DataMembers_PartialMerge()
{
var srcA1 = @"
partial class C
{
public int x = 1;
public int y = 2;
}
";
var srcB1 = @"
partial class C
{
public int P { get; set; } = 3;
}";
var srcA2 = @"
class C
{
public int x = 1;
public int y = 2;
public int P { get; set; } = 3;
}
";
var srcB2 = @"
";
// note that accessors are not updated since they do not have bodies
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true),
}),
DocumentResults()
});
}
#endregion
#region Records
[Fact]
public void Record_Partial_MovePrimaryConstructor()
{
var src1 = @"
partial record C { }
partial record C(int X);";
var src2 = @"
partial record C(int X);
partial record C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_Name_Update()
{
var src1 = "record C { }";
var src2 = "record D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C { }]@0 -> [record D { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "record D", CSharpFeaturesResources.record_));
}
[Fact]
public void RecordStruct_NoModifiers_Insert()
{
var src1 = "";
var src2 = "record struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void RecordStruct_AddField()
{
var src1 = @"
record struct C(int X)
{
}";
var src2 = @"
record struct C(int X)
{
private int _y = 0;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoStruct, "_y = 0", FeaturesResources.field, CSharpFeaturesResources.record_struct));
}
[Fact]
public void RecordStruct_AddProperty()
{
var src1 = @"
record struct C(int X)
{
}";
var src2 = @"
record struct C(int X)
{
public int Y { get; set; } = 0;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoStruct, "public int Y { get; set; } = 0;", FeaturesResources.auto_property, CSharpFeaturesResources.record_struct));
}
[Fact]
public void Record_NoModifiers_Insert()
{
var src1 = "";
var src2 = "record C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { }";
var src2 = "namespace N { record C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_NoModifiers_IntoType_Insert()
{
var src1 = "struct N { }";
var src2 = "struct N { record C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_BaseTypeUpdate1()
{
var src1 = "record C { }";
var src2 = "record C : D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C { }]@0 -> [record C : D { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_));
}
[Fact]
public void Record_BaseTypeUpdate2()
{
var src1 = "record C : D1 { }";
var src2 = "record C : D2 { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C : D1 { }]@0 -> [record C : D2 { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_));
}
[Fact]
public void Record_BaseInterfaceUpdate1()
{
var src1 = "record C { }";
var src2 = "record C : IDisposable { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C { }]@0 -> [record C : IDisposable { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_));
}
[Fact]
public void Record_BaseInterfaceUpdate2()
{
var src1 = "record C : IGoo, IBar { }";
var src2 = "record C : IGoo { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C : IGoo, IBar { }]@0 -> [record C : IGoo { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_));
}
[Fact]
public void Record_BaseInterfaceUpdate3()
{
var src1 = "record C : IGoo, IBar { }";
var src2 = "record C : IBar, IGoo { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [record C : IGoo, IBar { }]@0 -> [record C : IBar, IGoo { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_));
}
[Fact]
public void RecordInsert_AbstractVirtualOverride()
{
var src1 = "";
var src2 = @"
public abstract record C<T>
{
public abstract void F();
public virtual void G() {}
public override void H() {}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_ParameterlessConstructor()
{
var src1 = "record C { }";
var src2 = @"
record C
{
public C()
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void RecordStruct_ImplementSynthesized_ParameterlessConstructor()
{
var src1 = "record struct C { }";
var src2 = @"
record struct C
{
public C()
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_PrintMembers()
{
var src1 = "record C { }";
var src2 = @"
record C
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void RecordStruct_ImplementSynthesized_PrintMembers()
{
var src1 = "record struct C { }";
var src2 = @"
record struct C
{
private readonly bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_WrongParameterName()
{
var src1 = "record C { }";
var src2 = @"
record C
{
protected virtual bool PrintMembers(System.Text.StringBuilder sb)
{
return false;
}
public virtual bool Equals(C rhs)
{
return false;
}
protected C(C other)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected virtual bool PrintMembers(System.Text.StringBuilder sb)", "PrintMembers(System.Text.StringBuilder builder)"),
Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "public virtual bool Equals(C rhs)", "Equals(C other)"),
Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected C(C other)", "C(C original)"));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.FirstOrDefault()?.Type.ToDisplayString() == "C"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true),
},
EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Record_ImplementSynthesized_ToString()
{
var src1 = "record C { }";
var src2 = @"
record C
{
public override string ToString()
{
return ""R"";
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_UnImplementSynthesized_ToString()
{
var src1 = @"
record C
{
public override string ToString()
{
return ""R"";
}
}";
var src2 = "record C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddProperty_Primary()
{
var src1 = "record C(int X);";
var src2 = "record C(int X, int Y);";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "int Y", FeaturesResources.parameter));
}
[Fact]
public void Record_UnimplementSynthesized_ParameterlessConstructor()
{
var src1 = @"
record C
{
public C()
{
}
}";
var src2 = "record C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void RecordStruct_UnimplementSynthesized_ParameterlessConstructor()
{
var src1 = @"
record struct C
{
public C()
{
}
}";
var src2 = "record struct C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddProperty_NotPrimary()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int Y { get; set; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddProperty_NotPrimary_WithConstructor()
{
var src1 = @"
record C(int X)
{
public C(string fromAString)
{
}
}";
var src2 = @"
record C(int X)
{
public int Y { get; set; }
public C(string fromAString)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddProperty_NotPrimary_WithExplicitMembers()
{
var src1 = @"
record C(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return false;
}
public override int GetHashCode()
{
return 0;
}
public virtual bool Equals(C other)
{
return false;
}
public C(C original)
{
}
}";
var src2 = @"
record C(int X)
{
public int Y { get; set; }
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return false;
}
public override int GetHashCode()
{
return 0;
}
public virtual bool Equals(C other)
{
return false;
}
public C(C original)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddProperty_NotPrimary_WithInitializer()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int Y { get; set; } = 1;
}";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddField()
{
var src1 = "record C(int X) { }";
var src2 = "record C(int X) { private int _y; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddField_WithExplicitMembers()
{
var src1 = @"
record C(int X)
{
public C(C other)
{
}
}";
var src2 = @"
record C(int X)
{
private int _y;
public C(C other)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddField_WithInitializer()
{
var src1 = "record C(int X) { }";
var src2 = "record C(int X) { private int _y = 1; }";
var syntaxMap = GetSyntaxMap(src1, src2);
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddField_WithExistingInitializer()
{
var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }";
var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z; }";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_AddField_WithInitializerAndExistingInitializer()
{
var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }";
var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z = 1; }";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_DeleteField()
{
var src1 = "record C(int X) { private int _y; }";
var src2 = "record C(int X) { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.field, "_y")));
}
[Fact]
public void Record_DeleteProperty_Primary()
{
var src1 = "record C(int X, int Y) { }";
var src2 = "record C(int X) { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.parameter, "int Y")));
}
[Fact]
public void Record_DeleteProperty_NotPrimary()
{
var src1 = "record C(int X) { public int P { get; set; } }";
var src2 = "record C(int X) { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "P")));
}
[Fact]
public void Record_ImplementSynthesized_Property()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int X { get; init; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_Property_WithBody()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int X
{
get
{
return 4;
}
init
{
throw null;
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_Property_WithExpressionBody()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int X { get => 4; init => throw null; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_Property_InitToSet()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int X { get; set; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ImplementRecordParameterWithSet, "public int X", "X"));
}
[Fact]
public void Record_ImplementSynthesized_Property_MakeReadOnly()
{
var src1 = "record C(int X);";
var src2 = @"
record C(int X)
{
public int X { get; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ImplementRecordParameterAsReadOnly, "public int X", "X"));
}
[Fact]
public void Record_UnImplementSynthesized_Property()
{
var src1 = @"
record C(int X)
{
public int X { get; init; }
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_UnImplementSynthesized_Property_WithExpressionBody()
{
var src1 = @"
record C(int X)
{
public int X { get => 4; init => throw null; }
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_UnImplementSynthesized_Property_WithBody()
{
var src1 = @"
record C(int X)
{
public int X { get { return 4; } init { } }
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_ImplementSynthesized_Property_Partial()
{
var srcA1 = @"partial record C(int X);";
var srcB1 = @"partial record C;";
var srcA2 = @"partial record C(int X);";
var srcB2 = @"
partial record C
{
public int X { get; init; }
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true)
})
});
}
[Fact]
public void Record_UnImplementSynthesized_Property_Partial()
{
var srcA1 = @"partial record C(int X);";
var srcB1 = @"
partial record C
{
public int X { get; init; }
}";
var srcA2 = @"partial record C(int X);";
var srcB2 = @"partial record C;";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true)
})
});
}
[Fact]
public void Record_ImplementSynthesized_Property_Partial_WithBody()
{
var srcA1 = @"partial record C(int X);";
var srcB1 = @"partial record C;";
var srcA2 = @"partial record C(int X);";
var srcB2 = @"
partial record C
{
public int X
{
get
{
return 4;
}
init
{
throw null;
}
}
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))
})
});
}
[Fact]
public void Record_UnImplementSynthesized_Property_Partial_WithBody()
{
var srcA1 = @"partial record C(int X);";
var srcB1 = @"
partial record C
{
public int X
{
get
{
return 4;
}
init
{
throw null;
}
}
}";
var srcA2 = @"partial record C(int X);";
var srcB2 = @"partial record C;";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))
})
});
}
[Fact]
public void Record_MoveProperty_Partial()
{
var srcA1 = @"
partial record C(int X)
{
public int Y { get; init; }
}";
var srcB1 = @"
partial record C;
";
var srcA2 = @"
partial record C(int X);
";
var srcB2 = @"
partial record C
{
public int Y { get; init; }
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").SetMethod)
}),
});
}
[Fact]
public void Record_UnImplementSynthesized_Property_WithInitializer()
{
var src1 = @"
record C(int X)
{
public int X { get; init; } = 1;
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_UnImplementSynthesized_Property_WithInitializerMatchingCompilerGenerated()
{
var src1 = @"
record C(int X)
{
public int X { get; init; } = X;
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Record_Property_Delete_NotPrimary()
{
var src1 = @"
record C(int X)
{
public int Y { get; init; }
}";
var src2 = "record C(int X);";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "Y")));
}
[Fact]
public void Record_PropertyInitializer_Update_NotPrimary()
{
var src1 = "record C { int X { get; } = 0; }";
var src2 = "record C { int X { get; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true));
}
[Fact]
public void Record_PropertyInitializer_Update_Primary()
{
var src1 = "record C(int X) { int X { get; } = 0; }";
var src2 = "record C(int X) { int X { get; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true));
}
#endregion
#region Enums
[Fact]
public void Enum_NoModifiers_Insert()
{
var src1 = "";
var src2 = "enum C { A }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Enum_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { }";
var src2 = "namespace N { enum C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Enum_NoModifiers_IntoType_Insert()
{
var src1 = "struct N { }";
var src2 = "struct N { enum C { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Enum_Attribute_Insert()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "enum E { }";
var src2 = attribute + "[A]enum E { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum E { }]@48 -> [[A]enum E { }]@48");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "enum E", FeaturesResources.enum_));
}
[Fact]
public void Enum_Member_Attribute_Delete()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "enum E { [A]X }";
var src2 = attribute + "enum E { X }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]X]@57 -> [X]@57");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "X", FeaturesResources.enum_value));
}
[Fact]
public void Enum_Member_Attribute_Insert()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "enum E { X }";
var src2 = attribute + "enum E { [A]X }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [X]@57 -> [[A]X]@57");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A]X", FeaturesResources.enum_value));
}
[Fact]
public void Enum_Member_Attribute_Update()
{
var attribute = "public class A1Attribute : System.Attribute { }\n\n" +
"public class A2Attribute : System.Attribute { }\n\n";
var src1 = attribute + "enum E { [A1]X }";
var src2 = attribute + "enum E { [A2]X }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A1]X]@107 -> [[A2]X]@107");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A2]X", FeaturesResources.enum_value));
}
[Fact]
public void Enum_Member_Attribute_InsertDeleteAndUpdate()
{
var srcA1 = "";
var srcB1 = "enum N { A = 1 }";
var srcA2 = "enum N { [System.Obsolete]A = 1 }";
var srcB2 = "";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.A"))
}),
DocumentResults()
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Enum_Rename()
{
var src1 = "enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Colors { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Colors { Red = 1, Blue = 2, }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "enum Colors", FeaturesResources.enum_));
}
[Fact]
public void Enum_BaseType_Add()
{
var src1 = "enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color : ushort { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : ushort { Red = 1, Blue = 2, }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_));
}
[Fact]
public void Enum_BaseType_Add_Unchanged()
{
var src1 = "enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color : int { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : int { Red = 1, Blue = 2, }]@0");
edits.VerifySemantics();
}
[Fact]
public void Enum_BaseType_Update()
{
var src1 = "enum Color : ushort { Red = 1, Blue = 2, }";
var src2 = "enum Color : long { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color : long { Red = 1, Blue = 2, }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_));
}
[Fact]
public void Enum_BaseType_Delete_Unchanged()
{
var src1 = "enum Color : int { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color : int { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0");
edits.VerifySemantics();
}
[Fact]
public void Enum_BaseType_Delete_Changed()
{
var src1 = "enum Color : ushort { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_));
}
[Fact]
public void EnumAccessibilityChange()
{
var src1 = "public enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "enum Color", FeaturesResources.enum_));
}
[Fact]
public void EnumAccessibilityNoChange()
{
var src1 = "internal enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1, Blue = 2, }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Fact]
public void EnumInitializerUpdate()
{
var src1 = "enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1, Blue = 3, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Blue = 2]@22 -> [Blue = 3]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 3", FeaturesResources.enum_value));
}
[Fact]
public void EnumInitializerUpdate2()
{
var src1 = "enum Color { Red = 1, Blue = 2, }";
var src2 = "enum Color { Red = 1 << 0, Blue = 2 << 1, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [Red = 1]@13 -> [Red = 1 << 0]@13",
"Update [Blue = 2]@22 -> [Blue = 2 << 1]@27");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 2 << 1", FeaturesResources.enum_value));
}
[Fact]
public void EnumInitializerUpdate3()
{
var src1 = "enum Color { Red = int.MinValue }";
var src2 = "enum Color { Red = int.MaxValue }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [Red = int.MinValue]@13 -> [Red = int.MaxValue]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "Red = int.MaxValue", FeaturesResources.enum_value));
}
[Fact]
public void EnumInitializerUpdate_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 1 }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 2 }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [Red = 1]@185 -> [Red = 2]@185");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("Color")));
}
[Fact]
public void EnumInitializerAdd()
{
var src1 = "enum Color { Red, }";
var src2 = "enum Color { Red = 1, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Red]@13 -> [Red = 1]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "Red = 1", FeaturesResources.enum_value));
}
[Fact]
public void EnumInitializerDelete()
{
var src1 = "enum Color { Red = 1, }";
var src2 = "enum Color { Red, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Red = 1]@13 -> [Red]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "Red", FeaturesResources.enum_value));
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")]
[Fact]
public void EnumMemberAdd()
{
var src1 = "enum Color { Red }";
var src2 = "enum Color { Red, Blue}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum Color { Red }]@0 -> [enum Color { Red, Blue}]@0",
"Insert [Blue]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value));
}
[Fact]
public void EnumMemberAdd2()
{
var src1 = "enum Color { Red, }";
var src2 = "enum Color { Red, Blue}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [Blue]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value));
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")]
[Fact]
public void EnumMemberAdd3()
{
var src1 = "enum Color { Red, }";
var src2 = "enum Color { Red, Blue,}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red, Blue,}]@0",
"Insert [Blue]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value));
}
[Fact]
public void EnumMemberUpdate()
{
var src1 = "enum Color { Red }";
var src2 = "enum Color { Orange }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Red]@13 -> [Orange]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "Orange", FeaturesResources.enum_value));
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")]
[Fact]
public void EnumMemberDelete()
{
var src1 = "enum Color { Red, Blue}";
var src2 = "enum Color { Red }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum Color { Red, Blue}]@0 -> [enum Color { Red }]@0",
"Delete [Blue]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue")));
}
[Fact]
public void EnumMemberDelete2()
{
var src1 = "enum Color { Red, Blue}";
var src2 = "enum Color { Red, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [Blue]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue")));
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")]
[Fact]
public void EnumTrailingCommaAdd()
{
var src1 = "enum Color { Red }";
var src2 = "enum Color { Red, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum Color { Red }]@0 -> [enum Color { Red, }]@0");
edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits);
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")]
[Fact]
public void EnumTrailingCommaAdd_WithInitializer()
{
var src1 = "enum Color { Red = 1 }";
var src2 = "enum Color { Red = 1, }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum Color { Red = 1 }]@0 -> [enum Color { Red = 1, }]@0");
edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits);
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")]
[Fact]
public void EnumTrailingCommaDelete()
{
var src1 = "enum Color { Red, }";
var src2 = "enum Color { Red }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red }]@0");
edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits);
}
[WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")]
[Fact]
public void EnumTrailingCommaDelete_WithInitializer()
{
var src1 = "enum Color { Red = 1, }";
var src2 = "enum Color { Red = 1 }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [enum Color { Red = 1, }]@0 -> [enum Color { Red = 1 }]@0");
edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits);
}
#endregion
#region Delegates
[Fact]
public void Delegates_NoModifiers_Insert()
{
var src1 = "";
var src2 = "delegate void D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_NoModifiers_IntoNamespace_Insert()
{
var src1 = "namespace N { }";
var src2 = "namespace N { delegate void D(); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_NoModifiers_IntoType_Insert()
{
var src1 = "class C { }";
var src2 = "class C { delegate void D(); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_Public_IntoType_Insert()
{
var src1 = "class C { }";
var src2 = "class C { public delegate void D(); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public delegate void D();]@10",
"Insert [()]@32");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_Generic_Insert()
{
var src1 = "class C { }";
var src2 = "class C { private delegate void D<T>(T a); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [private delegate void D<T>(T a);]@10",
"Insert [<T>]@33",
"Insert [(T a)]@36",
"Insert [T]@34",
"Insert [T a]@37");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_Delete()
{
var src1 = "class C { private delegate void D(); }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [private delegate void D();]@10",
"Delete [()]@33");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.delegate_, "D")));
}
[Fact]
public void Delegates_Rename()
{
var src1 = "public delegate void D();";
var src2 = "public delegate void Z();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate void D();]@0 -> [public delegate void Z();]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "public delegate void Z()", FeaturesResources.delegate_));
}
[Fact]
public void Delegates_Accessibility_Update()
{
var src1 = "public delegate void D();";
var src2 = "private delegate void D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate void D();]@0 -> [private delegate void D();]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "private delegate void D()", FeaturesResources.delegate_));
}
[Fact]
public void Delegates_ReturnType_Update()
{
var src1 = "public delegate int D();";
var src2 = "public delegate void D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D();]@0 -> [public delegate void D();]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "public delegate void D()", FeaturesResources.delegate_));
}
[Fact]
public void Delegates_ReturnType_AddAttribute()
{
var attribute = "public class A : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "[return: A]public delegate int D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D(int a);]@39 -> [[return: A]public delegate int D(int a);]@39");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Delegates_Parameter_Insert()
{
var src1 = "public delegate int D();";
var src2 = "public delegate int D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [int a]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "int a", FeaturesResources.parameter));
}
[Fact]
public void Delegates_Parameter_Insert_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D();";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D")));
}
[Fact]
public void Delegates_Parameter_Delete()
{
var src1 = "public delegate int D(int a);";
var src2 = "public delegate int D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [int a]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.parameter, "int a")));
}
[Fact]
public void Delegates_Parameter_Rename()
{
var src1 = "public delegate int D(int a);";
var src2 = "public delegate int D(int b);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@22 -> [int b]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "int b", FeaturesResources.parameter));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Delegates_Parameter_Update()
{
var src1 = "public delegate int D(int a);";
var src2 = "public delegate int D(byte a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@22 -> [byte a]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "byte a", FeaturesResources.parameter));
}
[Fact]
public void Delegates_Parameter_AddAttribute_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "public delegate int D([A]int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@70 -> [[A]int a]@70");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter));
}
[Fact]
public void Delegates_Parameter_AddAttribute()
{
var attribute = "public class A : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "public delegate int D([A]int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@61 -> [[A]int a]@61");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Delegates_TypeParameter_Insert()
{
var src1 = "public delegate int D();";
var src2 = "public delegate int D<T>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [<T>]@21",
"Insert [T]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "T", FeaturesResources.type_parameter));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")]
[WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")]
public void Delegates_TypeParameter_Insert_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D<out T>();";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D<in T, out S>(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D")));
}
[Fact]
public void Delegates_TypeParameter_Delete()
{
var src1 = "public delegate int D<T>();";
var src2 = "public delegate int D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [<T>]@21",
"Delete [T]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T")));
}
[Fact]
public void Delegates_TypeParameter_Rename()
{
var src1 = "public delegate int D<T>();";
var src2 = "public delegate int D<S>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@22 -> [S]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "S", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "S"));
}
[Fact]
public void Delegates_TypeParameter_Variance1()
{
var src1 = "public delegate int D<T>();";
var src2 = "public delegate int D<in T>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@22 -> [in T]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void Delegates_TypeParameter_Variance2()
{
var src1 = "public delegate int D<out T>();";
var src2 = "public delegate int D<T>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [out T]@22 -> [T]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void Delegates_TypeParameter_Variance3()
{
var src1 = "public delegate int D<out T>();";
var src2 = "public delegate int D<in T>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [out T]@22 -> [in T]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void Delegates_TypeParameter_AddAttribute()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D<T>();";
var src2 = attribute + "public delegate int D<[A]T>();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@70 -> [[A]T]@70");
edits.VerifyRudeDiagnostics(
EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void Delegates_Attribute_Add_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "[A]public delegate int D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public delegate int D(int a)", FeaturesResources.delegate_));
}
[Fact]
public void Delegates_Attribute_Add()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "[A]public delegate int D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Delegates_Attribute_Add_WithReturnTypeAttribute()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + "public delegate int D(int a);";
var src2 = attribute + "[return: A][A]public delegate int D(int a);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D(int a);]@48 -> [[return: A][A]public delegate int D(int a);]@48");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Delegates_ReadOnlyRef_Parameter_InsertWhole()
{
var src1 = "";
var src2 = "public delegate int D(in int b);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public delegate int D(in int b);]@0",
"Insert [(in int b)]@21",
"Insert [in int b]@22");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_ReadOnlyRef_Parameter_InsertParameter()
{
var src1 = "public delegate int D();";
var src2 = "public delegate int D(in int b);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [in int b]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter));
}
[Fact]
public void Delegates_ReadOnlyRef_Parameter_Update()
{
var src1 = "public delegate int D(int b);";
var src2 = "public delegate int D(in int b);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int b]@22 -> [in int b]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter));
}
[Fact]
public void Delegates_ReadOnlyRef_ReturnType_Insert()
{
var src1 = "";
var src2 = "public delegate ref readonly int D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public delegate ref readonly int D();]@0",
"Insert [()]@34");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Delegates_ReadOnlyRef_ReturnType_Update()
{
var src1 = "public delegate int D();";
var src2 = "public delegate ref readonly int D();";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate int D();]@0 -> [public delegate ref readonly int D();]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "public delegate ref readonly int D()", FeaturesResources.delegate_));
}
#endregion
#region Nested Types
[Fact]
public void NestedClass_ClassMove1()
{
var src1 = @"class C { class D { } }";
var src2 = @"class C { } class D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Move [class D { }]@10 -> @12");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_));
}
[Fact]
public void NestedClass_ClassMove2()
{
var src1 = @"class C { class D { } class E { } class F { } }";
var src2 = @"class C { class D { } class F { } } class E { } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Move [class E { }]@23 -> @37");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "class E", FeaturesResources.class_));
}
[Fact]
public void NestedClass_ClassInsertMove1()
{
var src1 = @"class C { class D { } }";
var src2 = @"class C { class E { class D { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [class E { class D { } }]@10",
"Move [class D { }]@10 -> @20");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_));
}
[Fact]
public void NestedClass_Insert1()
{
var src1 = @"class C { }";
var src2 = @"class C { class D { class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [class D { class E { } }]@10",
"Insert [class E { }]@20");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_Insert2()
{
var src1 = @"class C { }";
var src2 = @"class C { protected class D { public class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [protected class D { public class E { } }]@10",
"Insert [public class E { }]@30");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_Insert3()
{
var src1 = @"class C { }";
var src2 = @"class C { private class D { public class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [private class D { public class E { } }]@10",
"Insert [public class E { }]@28");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_Insert4()
{
var src1 = @"class C { }";
var src2 = @"class C { private class D { public D(int a, int b) { } public int P { get; set; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [private class D { public D(int a, int b) { } public int P { get; set; } }]@10",
"Insert [public D(int a, int b) { }]@28",
"Insert [public int P { get; set; }]@55",
"Insert [(int a, int b)]@36",
"Insert [{ get; set; }]@68",
"Insert [int a]@37",
"Insert [int b]@44",
"Insert [get;]@70",
"Insert [set;]@75");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_Insert_ReloadableIntoReloadable1()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void NestedClass_Insert_ReloadableIntoReloadable2()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void NestedClass_Insert_ReloadableIntoReloadable3()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { class D { [CreateNewOnMetadataUpdate]class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void NestedClass_Insert_ReloadableIntoReloadable4()
{
var src1 = ReloadableAttributeSrc + "class C { }";
var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D")));
}
[Fact]
public void NestedClass_Insert_Member_Reloadable()
{
var src1 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { } }";
var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { int x; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C.D")));
}
[Fact]
public void NestedClass_InsertMemberWithInitializer1()
{
var src1 = @"
class C
{
}";
var src2 = @"
class C
{
private class D
{
public int P = 1;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"), preserveLocalVariables: false)
});
}
[WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
[Fact]
public void NestedClass_Insert_PInvoke()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
}";
var src2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
abstract class D
{
public extern D();
public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; }
[DllImport(""msvcrt.dll"")]
public static extern int puts(string c);
[DllImport(""msvcrt.dll"")]
public static extern int operator +(D d, D g);
[DllImport(""msvcrt.dll"")]
public static extern explicit operator int (D d);
}
}
";
var edits = GetTopEdits(src1, src2);
// Adding P/Invoke is not supported by the CLR.
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertExtern, "public extern D()", FeaturesResources.constructor),
Diagnostic(RudeEditKind.InsertExtern, "public static extern int P", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertExtern, "public static extern int puts(string c)", FeaturesResources.method),
Diagnostic(RudeEditKind.InsertExtern, "public static extern int operator +(D d, D g)", FeaturesResources.operator_),
Diagnostic(RudeEditKind.InsertExtern, "public static extern explicit operator int (D d)", CSharpFeaturesResources.conversion_operator));
}
[WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
[Fact]
public void NestedClass_Insert_VirtualAbstract()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
}";
var src2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
abstract class D
{
public abstract int P { get; }
public abstract int this[int i] { get; }
public abstract int puts(string c);
public virtual event Action E { add { } remove { } }
public virtual int Q { get { return 1; } }
public virtual int this[string i] { get { return 1; } }
public virtual int M(string c) { return 1; }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_TypeReorder1()
{
var src1 = @"class C { struct E { } class F { } delegate void D(); interface I {} }";
var src2 = @"class C { class F { } interface I {} delegate void D(); struct E { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [struct E { }]@10 -> @56",
"Reorder [interface I {}]@54 -> @22");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedClass_MethodDeleteInsert()
{
var src1 = @"public class C { public void goo() {} }";
var src2 = @"public class C { private class D { public void goo() {} } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [private class D { public void goo() {} }]@17",
"Insert [public void goo() {}]@35",
"Insert [()]@50",
"Delete [public void goo() {}]@17",
"Delete [()]@32");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "public class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()")));
}
[Fact]
public void NestedClass_ClassDeleteInsert()
{
var src1 = @"public class C { public class X {} }";
var src2 = @"public class C { public class D { public class X {} } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public class D { public class X {} }]@17",
"Move [public class X {}]@17 -> @34");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "public class X", FeaturesResources.class_));
}
/// <summary>
/// A new generic type can be added whether it's nested and inherits generic parameters from the containing type, or top-level.
/// </summary>
[Fact]
public void NestedClassGeneric_Insert()
{
var src1 = @"
using System;
class C<T>
{
}
";
var src2 = @"
using System;
class C<T>
{
class D {}
struct S {}
enum N {}
interface I {}
delegate void D();
}
class D<T>
{
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void NestedEnum_InsertMember()
{
var src1 = "struct S { enum N { A = 1 } }";
var src2 = "struct S { enum N { A = 1, B = 2 } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [enum N { A = 1 }]@11 -> [enum N { A = 1, B = 2 }]@11",
"Insert [B = 2]@27");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value));
}
[Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")]
public void NestedEnumInPartialType_InsertDelete()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { enum N { A = 1 } }";
var srcA2 = "partial struct S { enum N { A = 1 } }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults()
});
}
[Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")]
public void NestedEnumInPartialType_InsertDeleteAndUpdateMember()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { enum N { A = 1 } }";
var srcA2 = "partial struct S { enum N { A = 2 } }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.InitializerUpdate, "A = 2", FeaturesResources.enum_value),
}),
DocumentResults()
});
}
[Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")]
public void NestedEnumInPartialType_InsertDeleteAndUpdateBase()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { enum N : uint { A = 1 } }";
var srcA2 = "partial struct S { enum N : int { A = 1 } }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum N", FeaturesResources.enum_),
}),
DocumentResults()
});
}
[Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")]
public void NestedEnumInPartialType_InsertDeleteAndInsertMember()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { enum N { A = 1 } }";
var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value) }),
DocumentResults()
});
}
[Fact]
public void NestedDelegateInPartialType_InsertDelete()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { delegate void D(); }";
var srcA2 = "partial struct S { delegate void D(); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
// delegate does not have any user-defined method body and this does not need a PDB update
semanticEdits: NoSemanticEdits),
DocumentResults()
});
}
[Fact]
public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { delegate void D(); }";
var srcA2 = "partial struct S { delegate void D(int x); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.ChangingParameterTypes, "delegate void D(int x)", FeaturesResources.delegate_)
}),
DocumentResults()
});
}
[Fact]
public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { delegate ref int D(); }";
var srcA2 = "partial struct S { delegate ref readonly int D(); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.TypeUpdate, "delegate ref readonly int D()", FeaturesResources.delegate_)
}),
DocumentResults()
});
}
[Fact]
public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { delegate void D(int x = 1); }";
var srcA2 = "partial struct S { delegate void D(int x = 2); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter)
}),
DocumentResults()
});
}
[Fact]
public void NestedPartialTypeInPartialType_InsertDeleteAndChange()
{
var srcA1 = "partial struct S { partial class C { void F1() {} } }";
var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }";
var srcC1 = "partial struct S { }";
var srcA2 = "partial struct S { partial class C { void F1() {} } }";
var srcB2 = "partial struct S { }";
var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F2(byte x)")) }),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("S").GetMember<INamedTypeSymbol>("C").GetMember("F2")) })
});
}
[Fact]
public void Type_Partial_AddMultiple()
{
var srcA1 = "";
var srcB1 = "";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C")
}),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C")
}),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_Partial_InsertDeleteAndChange_Attribute()
{
var srcA1 = "partial class C { }";
var srcB1 = "";
var srcC1 = "partial class C { }";
var srcA2 = "";
var srcB2 = "[A]partial class C { }";
var srcC2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C")
}),
DocumentResults(),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute_NotSupportedByRuntime()
{
var srcA1 = "partial class C<T> { }";
var srcB1 = "";
var srcC1 = "partial class C<T> { }";
var srcA2 = "";
var srcB2 = "partial class C<[A]T> { }";
var srcC2 = "partial class C<T> { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<[A]T>"),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T")
}),
DocumentResults(),
});
}
[Fact]
public void Type_Partial_InsertDeleteAndChange_Constraint()
{
var srcA1 = "partial class C<T> { }";
var srcB1 = "";
var srcC1 = "partial class C<T> { }";
var srcA2 = "";
var srcB2 = "partial class C<T> where T : new() { }";
var srcC2 = "partial class C<T> { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<T>"),
Diagnostic(RudeEditKind.ChangingConstraints, "where T : new()", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : new()")
}),
DocumentResults(),
});
}
[Fact]
public void Type_Partial_InsertDeleteRefactor()
{
var srcA1 = "partial class C : I { void F() { } }";
var srcB1 = "[A][B]partial class C : J { void G() { } }";
var srcC1 = "";
var srcD1 = "";
var srcA2 = "";
var srcB2 = "";
var srcC2 = "[A]partial class C : I, J { void F() { } }";
var srcD2 = "[B]partial class C { void G() { } }";
var srcE = "interface I {} interface J {}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G")) }),
DocumentResults(),
});
}
[Fact]
public void Type_Partial_Attribute_AddMultiple()
{
var attributes = @"
class A : System.Attribute {}
class B : System.Attribute {}
";
var srcA1 = "partial class C { }" + attributes;
var srcB1 = "partial class C { }";
var srcA2 = "[A]partial class C { }" + attributes;
var srcB2 = "[B]partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C")
}),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C")
}),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting()
{
var srcA1 = "partial class C { void F() { } }";
var srcB1 = "[A,B]partial class C { void G() { } }";
var srcC1 = "";
var srcD1 = "";
var srcA2 = "";
var srcB2 = "";
var srcC2 = "[A]partial class C { void F() { } }";
var srcD2 = "[B]partial class C { void G() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"))
}),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))
}),
});
}
[Fact]
public void Type_Partial_InsertDeleteChangeMember()
{
var srcA1 = "partial class C { void F(int y = 1) { } }";
var srcB1 = "partial class C { void G(int x = 1) { } }";
var srcC1 = "";
var srcA2 = "";
var srcB2 = "partial class C { void G(int x = 2) { } }";
var srcC2 = "partial class C { void F(int y = 2) { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }),
DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int y = 2", FeaturesResources.parameter) }),
});
}
[Fact]
public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual()
{
var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }";
var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }";
var srcC1 = "partial interface I { partial class C { } }";
var srcD1 = "partial interface I { partial class C { } }";
var srcE1 = "partial interface I { }";
var srcF1 = "partial interface I { }";
var srcA2 = "partial interface I { partial class C { } }";
var srcB2 = "";
var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl
var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl
var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl
var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2) },
new[]
{
// A
DocumentResults(),
// B
DocumentResults(),
// C
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F1")) }),
// D
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N1()", FeaturesResources.method) }),
// E
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }),
// F
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N2()", FeaturesResources.method) }),
});
}
#endregion
#region Namespaces
[Fact]
public void Namespace_Insert()
{
var src1 = @"";
var src2 = @"namespace C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [namespace C { }]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_));
}
[Fact]
public void Namespace_InsertNested()
{
var src1 = @"namespace C { }";
var src2 = @"namespace C { namespace D { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [namespace D { }]@14");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "namespace D", FeaturesResources.namespace_));
}
[Fact]
public void Namespace_DeleteNested()
{
var src1 = @"namespace C { namespace D { } }";
var src2 = @"namespace C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [namespace D { }]@14");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "namespace C", FeaturesResources.namespace_));
}
[Fact]
public void Namespace_Move()
{
var src1 = @"namespace C { namespace D { } }";
var src2 = @"namespace C { } namespace D { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Move [namespace D { }]@14 -> @16");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "namespace D", FeaturesResources.namespace_));
}
[Fact]
public void Namespace_Reorder1()
{
var src1 = @"namespace C { namespace D { } class T { } namespace E { } }";
var src2 = @"namespace C { namespace E { } class T { } namespace D { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [class T { }]@30 -> @30",
"Reorder [namespace E { }]@42 -> @14");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Namespace_Reorder2()
{
var src1 = @"namespace C { namespace D1 { } namespace D2 { } namespace D3 { } class T { } namespace E { } }";
var src2 = @"namespace C { namespace E { } class T { } namespace D1 { } namespace D2 { } namespace D3 { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [class T { }]@65 -> @65",
"Reorder [namespace E { }]@77 -> @14");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Namespace_FileScoped_Insert()
{
var src1 = @"";
var src2 = @"namespace C;";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [namespace C;]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_));
}
[Fact]
public void Namespace_FileScoped_Delete()
{
var src1 = @"namespace C;";
var src2 = @"";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [namespace C;]@0");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_));
}
#endregion
#region Members
[Fact]
public void PartialMember_DeleteInsert_SingleDocument()
{
var src1 = @"
using System;
partial class C
{
void M() {}
int P1 { get; set; }
int P2 { get => 1; set {} }
int this[int i] { get => 1; set {} }
int this[byte i] { get => 1; set {} }
event Action E { add {} remove {} }
event Action EF;
int F1;
int F2;
}
partial class C
{
}
";
var src2 = @"
using System;
partial class C
{
}
partial class C
{
void M() {}
int P1 { get; set; }
int P2 { get => 1; set {} }
int this[int i] { get => 1; set {} }
int this[byte i] { get => 1; set {} }
event Action E { add {} remove {} }
event Action EF;
int F1, F2;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [void M() {}]@68",
"Insert [int P1 { get; set; }]@85",
"Insert [int P2 { get => 1; set {} }]@111",
"Insert [int this[int i] { get => 1; set {} }]@144",
"Insert [int this[byte i] { get => 1; set {} }]@186",
"Insert [event Action E { add {} remove {} }]@229",
"Insert [event Action EF;]@270",
"Insert [int F1, F2;]@292",
"Insert [()]@74",
"Insert [{ get; set; }]@92",
"Insert [{ get => 1; set {} }]@118",
"Insert [[int i]]@152",
"Insert [{ get => 1; set {} }]@160",
"Insert [[byte i]]@194",
"Insert [{ get => 1; set {} }]@203",
"Insert [{ add {} remove {} }]@244",
"Insert [Action EF]@276",
"Insert [int F1, F2]@292",
"Insert [get;]@94",
"Insert [set;]@99",
"Insert [get => 1;]@120",
"Insert [set {}]@130",
"Insert [int i]@153",
"Insert [get => 1;]@162",
"Insert [set {}]@172",
"Insert [byte i]@195",
"Insert [get => 1;]@205",
"Insert [set {}]@215",
"Insert [add {}]@246",
"Insert [remove {}]@253",
"Insert [EF]@283",
"Insert [F1]@296",
"Insert [F2]@300",
"Delete [void M() {}]@43",
"Delete [()]@49",
"Delete [int P1 { get; set; }]@60",
"Delete [{ get; set; }]@67",
"Delete [get;]@69",
"Delete [set;]@74",
"Delete [int P2 { get => 1; set {} }]@86",
"Delete [{ get => 1; set {} }]@93",
"Delete [get => 1;]@95",
"Delete [set {}]@105",
"Delete [int this[int i] { get => 1; set {} }]@119",
"Delete [[int i]]@127",
"Delete [int i]@128",
"Delete [{ get => 1; set {} }]@135",
"Delete [get => 1;]@137",
"Delete [set {}]@147",
"Delete [int this[byte i] { get => 1; set {} }]@161",
"Delete [[byte i]]@169",
"Delete [byte i]@170",
"Delete [{ get => 1; set {} }]@178",
"Delete [get => 1;]@180",
"Delete [set {}]@190",
"Delete [event Action E { add {} remove {} }]@204",
"Delete [{ add {} remove {} }]@219",
"Delete [add {}]@221",
"Delete [remove {}]@228",
"Delete [event Action EF;]@245",
"Delete [Action EF]@251",
"Delete [EF]@258",
"Delete [int F1;]@267",
"Delete [int F1]@267",
"Delete [F1]@271",
"Delete [int F2;]@280",
"Delete [int F2]@280",
"Delete [F2]@284");
EditAndContinueValidation.VerifySemantics(
new[] { edits },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").SetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").SetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").SetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod, preserveLocalVariables: false),
})
});
}
[Fact]
public void PartialMember_InsertDelete_MultipleDocuments()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { void F() {} }";
var srcA2 = "partial class C { void F() {} }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"), preserveLocalVariables: false)
}),
DocumentResults()
});
}
[Fact]
public void PartialMember_DeleteInsert_MultipleDocuments()
{
var srcA1 = "partial class C { void F() {} }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { void F() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"), preserveLocalVariables: false)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_GenericMethod()
{
var srcA1 = "partial class C { void F<T>() {} }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { void F<T>() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<T>()"),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T")
})
});
}
[Fact]
public void PartialMember_DeleteInsert_GenericType()
{
var srcA1 = "partial class C<T> { void F() {} }";
var srcB1 = "partial class C<T> { }";
var srcA2 = "partial class C<T> { }";
var srcB2 = "partial class C<T> { void F() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()")
})
});
}
[Fact]
public void PartialMember_DeleteInsert_Destructor()
{
var srcA1 = "partial class C { ~C() {} }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { ~C() {} }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("Finalize"), preserveLocalVariables: false),
})
});
}
[Fact]
public void PartialNestedType_InsertDeleteAndChange()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { class D { void M() {} } interface I { } }";
var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class D", FeaturesResources.class_),
}),
DocumentResults()
});
}
[Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")]
public void PartialMember_RenameInsertDelete()
{
// The syntactic analysis for A and B produce rename edits since it doesn't see that the member was in fact moved.
// TODO: Currently, we don't even pass rename edits to semantic analysis where we could handle them as updates.
var srcA1 = "partial class C { void F1() {} }";
var srcB1 = "partial class C { void F2() {} }";
var srcA2 = "partial class C { void F2() {} }";
var srcB2 = "partial class C { void F1() {} }";
// current outcome:
GetTopEdits(srcA1, srcA2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F2()", FeaturesResources.method));
GetTopEdits(srcB1, srcB2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F1()", FeaturesResources.method));
// correct outcome:
//EditAndContinueValidation.VerifySemantics(
// new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
// new[]
// {
// DocumentResults(semanticEdits: new[]
// {
// SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")),
// }),
// DocumentResults(
// semanticEdits: new[]
// {
// SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F1")),
// })
// });
}
[Fact]
public void PartialMember_DeleteInsert_UpdateMethodBodyError()
{
var srcA1 = @"
using System.Collections.Generic;
partial class C
{
IEnumerable<int> F() { yield return 1; }
}
";
var srcB1 = @"
using System.Collections.Generic;
partial class C
{
}
";
var srcA2 = @"
using System.Collections.Generic;
partial class C
{
}
";
var srcB2 = @"
using System.Collections.Generic;
partial class C
{
IEnumerable<int> F() { yield return 1; yield return 2; }
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(diagnostics: new[]
{
Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_UpdatePropertyAccessors()
{
var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_UpdateAutoProperty()
{
var srcA1 = "partial class C { int P => 1; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int P => 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_AddFieldInitializer()
{
var srcA1 = "partial class C { int f; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int f = 1; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_RemoveFieldInitializer()
{
var srcA1 = "partial class C { int f = 1; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int f; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_ConstructorWithInitializers()
{
var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { int f = 1; }";
var srcB2 = "partial class C { C(int x) { f = x + 1; } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
})
});
}
[Fact]
public void PartialMember_DeleteInsert_MethodAddParameter()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { void F() {} }";
var srcA2 = "partial struct S { void F(int x) {} }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F"))
}),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()"))
})
});
}
[Fact]
public void PartialMember_DeleteInsert_UpdateMethodParameterType()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { void F(int x); }";
var srcA2 = "partial struct S { void F(byte x); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F"))
}),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F(int x)"))
})
});
}
[Fact]
public void PartialMember_DeleteInsert_MethodAddTypeParameter()
{
var srcA1 = "partial struct S { }";
var srcB1 = "partial struct S { void F(); }";
var srcA2 = "partial struct S { void F<T>(); }";
var srcB2 = "partial struct S { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.InsertGenericMethod, "void F<T>()", FeaturesResources.method)
}),
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()"))
})
});
}
#endregion
#region Methods
[Theory]
[InlineData("static")]
[InlineData("virtual")]
[InlineData("abstract")]
[InlineData("override")]
[InlineData("sealed override", "override")]
public void Method_Modifiers_Update(string oldModifiers, string newModifiers = "")
{
if (oldModifiers != "")
{
oldModifiers += " ";
}
if (newModifiers != "")
{
newModifiers += " ";
}
var src1 = "class C { " + oldModifiers + "int F() => 0; }";
var src2 = "class C { " + newModifiers + "int F() => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [" + oldModifiers + "int F() => 0;]@10 -> [" + newModifiers + "int F() => 0;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F()", FeaturesResources.method));
}
[Fact]
public void Method_NewModifier_Add()
{
var src1 = "class C { int F() => 0; }";
var src2 = "class C { new int F() => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [int F() => 0;]@10 -> [new int F() => 0;]@10");
// Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving.
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")));
}
[Fact]
public void Method_NewModifier_Remove()
{
var src1 = "class C { new int F() => 0; }";
var src2 = "class C { int F() => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [new int F() => 0;]@10 -> [int F() => 0;]@10");
// Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving.
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")));
}
[Fact]
public void Method_ReadOnlyModifier_Add_InMutableStruct()
{
var src1 = @"
struct S
{
public int M() => 1;
}";
var src2 = @"
struct S
{
public readonly int M() => 1;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly int M()", FeaturesResources.method));
}
[Fact]
public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1()
{
var src1 = @"
readonly struct S
{
public int M()
=> 1;
}";
var src2 = @"
readonly struct S
{
public readonly int M()
=> 1;
}";
var edits = GetTopEdits(src1, src2);
// Currently, an edit is produced eventhough the body nor IsReadOnly attribute have changed. Consider improving.
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IMethodSymbol>("M")));
}
[Fact]
public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2()
{
var src1 = @"
readonly struct S
{
public int M() => 1;
}";
var src2 = @"
struct S
{
public readonly int M() => 1;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct"));
}
[Fact]
public void Method_AsyncModifier_Remove()
{
var src1 = @"
class Test
{
public async Task<int> WaitAsync()
{
return 1;
}
}";
var src2 = @"
class Test
{
public Task<int> WaitAsync()
{
return Task.FromResult(1);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task<int> WaitAsync()", FeaturesResources.method));
}
[Fact]
public void Method_AsyncModifier_Add()
{
var src1 = @"
class Test
{
public Task<int> WaitAsync()
{
return 1;
}
}";
var src2 = @"
class Test
{
public async Task<int> WaitAsync()
{
await Task.Delay(1000);
return 1;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
VerifyPreserveLocalVariables(edits, preserveLocalVariables: false);
}
[Fact]
public void Method_AsyncModifier_Add_NotSupported()
{
var src1 = @"
class Test
{
public Task<int> WaitAsync()
{
return 1;
}
}";
var src2 = @"
class Test
{
public async Task<int> WaitAsync()
{
await Task.Delay(1000);
return 1;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.MakeMethodAsync, "public async Task<int> WaitAsync()"));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("object", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Method_ReturnType_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C { " + oldType + " M() => default; }";
var src2 = "class C { " + newType + " M() => default; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Method_ReturnType_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C { " + oldType + " M() => default; }";
var src2 = "class C { " + newType + " M() => default; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, newType + " M()", FeaturesResources.method));
}
[Fact]
public void Method_Update()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
System.Console.WriteLine(a + b);
}
}
";
var src2 = @"
class C
{
static void Main(string[] args)
{
int b = 2;
int a = 1;
System.Console.WriteLine(a + b);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Update [static void Main(string[] args)
{
int a = 1;
int b = 2;
System.Console.WriteLine(a + b);
}]@18 -> [static void Main(string[] args)
{
int b = 2;
int a = 1;
System.Console.WriteLine(a + b);
}]@18");
edits.VerifyRudeDiagnostics();
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) });
}
[Fact]
public void MethodWithExpressionBody_Update()
{
var src1 = @"
class C
{
static int Main(string[] args) => F(1);
static int F(int a) => 1;
}
";
var src2 = @"
class C
{
static int Main(string[] args) => F(2);
static int F(int a) => 1;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Update [static int Main(string[] args) => F(1);]@18 -> [static int Main(string[] args) => F(2);]@18");
edits.VerifyRudeDiagnostics();
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) });
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void MethodWithExpressionBody_Update_LiftedParameter()
{
var src1 = @"
using System;
class C
{
int M(int a) => new Func<int>(() => a + 1)();
}
";
var src2 = @"
using System;
class C
{
int M(int a) => new Func<int>(() => 2)(); // not capturing a anymore
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int M(int a) => new Func<int>(() => a + 1)();]@35 -> [int M(int a) => new Func<int>(() => 2)();]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a"));
}
[Fact]
public void MethodWithExpressionBody_ToBlockBody()
{
var src1 = "class C { static int F(int a) => 1; }";
var src2 = "class C { static int F(int a) { return 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [static int F(int a) => 1;]@10 -> [static int F(int a) { return 2; }]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false)
});
}
[Fact]
public void MethodWithBlockBody_ToExpressionBody()
{
var src1 = "class C { static int F(int a) { return 2; } }";
var src2 = "class C { static int F(int a) => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [static int F(int a) { return 2; }]@10 -> [static int F(int a) => 1;]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false)
});
}
[Fact]
public void MethodWithLambda_Update()
{
var src1 = @"
using System;
class C
{
static void F()
{
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
}
}
";
var src2 = @"
using System;
class C
{
static void F()
{
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
Console.WriteLine(1);
}
}";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap[0]) });
}
[Fact]
public void MethodUpdate_LocalVariableDeclaration()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
int x = 1;
Console.WriteLine(x);
}
}
";
var src2 = @"
class C
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(x);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Update [static void Main(string[] args)
{
int x = 1;
Console.WriteLine(x);
}]@18 -> [static void Main(string[] args)
{
int x = 2;
Console.WriteLine(x);
}]@18");
}
[Fact]
public void Method_Delete()
{
var src1 = @"
class C
{
void goo() { }
}
";
var src2 = @"
class C
{
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [void goo() { }]@18",
"Delete [()]@26");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()")));
}
[Fact]
public void MethodWithExpressionBody_Delete()
{
var src1 = @"
class C
{
int goo() => 1;
}
";
var src2 = @"
class C
{
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [int goo() => 1;]@18",
"Delete [()]@25");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()")));
}
[WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")]
[Fact]
public void MethodDelete_WithParameterAndAttribute()
{
var src1 = @"
class C
{
[Obsolete]
void goo(int a) { }
}
";
var src2 = @"
class C
{
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Delete [[Obsolete]
void goo(int a) { }]@18",
"Delete [(int a)]@42",
"Delete [int a]@43");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo(int a)")));
}
[WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")]
[Fact]
public void MethodDelete_PInvoke()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int puts(string c);
}
";
var src2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Delete [[DllImport(""msvcrt.dll"")]
public static extern int puts(string c);]@74",
"Delete [(string c)]@134",
"Delete [string c]@135");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)")));
}
[Fact]
public void MethodInsert_NotSupportedByRuntime()
{
var src1 = "class C { }";
var src2 = "class C { void goo() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "void goo()", FeaturesResources.method));
}
[Fact]
public void PrivateMethodInsert()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
Console.ReadLine();
}
}";
var src2 = @"
class C
{
void goo() { }
static void Main(string[] args)
{
Console.ReadLine();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [void goo() { }]@18",
"Insert [()]@26");
edits.VerifyRudeDiagnostics();
}
[WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")]
[Fact]
public void PrivateMethodInsert_WithParameters()
{
var src1 = @"
using System;
class C
{
static void Main(string[] args)
{
Console.ReadLine();
}
}";
var src2 = @"
using System;
class C
{
void goo(int a) { }
static void Main(string[] args)
{
Console.ReadLine();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [void goo(int a) { }]@35",
"Insert [(int a)]@43",
"Insert [int a]@44");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.goo")) });
}
[WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")]
[Fact]
public void PrivateMethodInsert_WithAttribute()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
Console.ReadLine();
}
}";
var src2 = @"
class C
{
[System.Obsolete]
void goo(int a) { }
static void Main(string[] args)
{
Console.ReadLine();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Insert [[System.Obsolete]
void goo(int a) { }]@18",
"Insert [(int a)]@49",
"Insert [int a]@50");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodInsert_Virtual()
{
var src1 = @"
class C
{
}";
var src2 = @"
class C
{
public virtual void F() {}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertVirtual, "public virtual void F()", FeaturesResources.method));
}
[Fact]
public void MethodInsert_Abstract()
{
var src1 = @"
abstract class C
{
}";
var src2 = @"
abstract class C
{
public abstract void F();
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertVirtual, "public abstract void F()", FeaturesResources.method));
}
[Fact]
public void MethodInsert_Override()
{
var src1 = @"
class C
{
}";
var src2 = @"
class C
{
public override void F() { }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertVirtual, "public override void F()", FeaturesResources.method));
}
[WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
[Fact]
public void ExternMethodInsert()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
}";
var src2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
private static extern int puts(string c);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
@"Insert [[DllImport(""msvcrt.dll"")]
private static extern int puts(string c);]@74",
"Insert [(string c)]@135",
"Insert [string c]@136");
// CLR doesn't support methods without a body
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertExtern, "private static extern int puts(string c)", FeaturesResources.method));
}
[Fact]
[WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
public void ExternMethodDeleteInsert()
{
var srcA1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
private static extern int puts(string c);
}";
var srcA2 = @"
using System;
using System.Runtime.InteropServices;
";
var srcB1 = @"
using System;
using System.Runtime.InteropServices;
";
var srcB2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
private static extern int puts(string c);
}
";
// TODO: The method does not need to be updated since there are no sequence points generated for it.
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")),
})
});
}
[Fact]
[WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
public void ExternMethod_Attribute_DeleteInsert()
{
var srcA1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
private static extern int puts(string c);
}";
var srcA2 = @"
using System;
using System.Runtime.InteropServices;
";
var srcB1 = @"
using System;
using System.Runtime.InteropServices;
";
var srcB2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
[Obsolete]
private static extern int puts(string c);
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")),
})
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void MethodReorder1()
{
var src1 = "class C { void f(int a, int b) { a = b; } void g() { } }";
var src2 = "class C { void g() { } void f(int a, int b) { a = b; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Reorder [void g() { }]@42 -> @10");
}
[Fact]
public void MethodInsertDelete1()
{
var src1 = "class C { class D { } void f(int a, int b) { a = b; } }";
var src2 = "class C { class D { void f(int a, int b) { a = b; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [void f(int a, int b) { a = b; }]@20",
"Insert [(int a, int b)]@26",
"Insert [int a]@27",
"Insert [int b]@34",
"Delete [void f(int a, int b) { a = b; }]@22",
"Delete [(int a, int b)]@28",
"Delete [int a]@29",
"Delete [int b]@36");
}
[Fact]
public void MethodUpdate_AddParameter()
{
var src1 = @"
class C
{
static void Main()
{
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [string[] args]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "string[] args", FeaturesResources.parameter));
}
[Fact]
public void MethodUpdate_UpdateParameter()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
}
}";
var src2 = @"
class C
{
static void Main(string[] b)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [string[] args]@35 -> [string[] b]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void MethodUpdate_UpdateParameterAndBody()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
}
}";
var src2 = @"
class C
{
static void Main(string[] b)
{
System.Console.Write(1);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Method_Name_Update()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
}
}";
var src2 = @"
class C
{
static void EntryPoint(string[] args)
{
}
}";
var edits = GetTopEdits(src1, src2);
var expectedEdit = @"Update [static void Main(string[] args)
{
}]@18 -> [static void EntryPoint(string[] args)
{
}]@18";
edits.VerifyEdits(expectedEdit);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "static void EntryPoint(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_AsyncMethod0()
{
var src1 = @"
class Test
{
public async Task<int> WaitAsync()
{
await Task.Delay(1000);
return 1;
}
}";
var src2 = @"
class Test
{
public async Task<int> WaitAsync()
{
await Task.Delay(500);
return 1;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
VerifyPreserveLocalVariables(edits, preserveLocalVariables: true);
}
[Fact]
public void MethodUpdate_AsyncMethod1()
{
var src1 = @"
class Test
{
static void Main(string[] args)
{
Test f = new Test();
string result = f.WaitAsync().Result;
}
public async Task<string> WaitAsync()
{
await Task.Delay(1000);
return ""Done"";
}
}";
var src2 = @"
class Test
{
static void Main(string[] args)
{
Test f = new Test();
string result = f.WaitAsync().Result;
}
public async Task<string> WaitAsync()
{
await Task.Delay(1000);
return ""Not Done"";
}
}";
var edits = GetTopEdits(src1, src2);
var expectedEdit = @"Update [public async Task<string> WaitAsync()
{
await Task.Delay(1000);
return ""Done"";
}]@151 -> [public async Task<string> WaitAsync()
{
await Task.Delay(1000);
return ""Not Done"";
}]@151";
edits.VerifyEdits(expectedEdit);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_AddReturnTypeAttribute()
{
var src1 = @"
using System;
class Test
{
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[return: Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(@"Update [static void Main(string[] args)
{
System.Console.Write(5);
}]@38 -> [[return: Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}]@38");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_AddAttribute()
{
var src1 = @"
using System;
class Test
{
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(@"Update [static void Main(string[] args)
{
System.Console.Write(5);
}]@38 -> [[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}]@38");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_AddAttribute_SupportedByRuntime()
{
var src1 = @"
using System;
class Test
{
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(@"Update [static void Main(string[] args)
{
System.Console.Write(5);
}]@38 -> [[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}]@38");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Test.Main")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void MethodUpdate_Attribute_ArrayParameter()
{
var src1 = @"
class AAttribute : System.Attribute
{
public AAttribute(int[] nums) { }
}
class C
{
[A(new int[] { 1, 2, 3})]
void M()
{
}
}";
var src2 = @"
class AAttribute : System.Attribute
{
public AAttribute(int[] nums) { }
}
class C
{
[A(new int[] { 4, 5, 6})]
void M()
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void MethodUpdate_Attribute_ArrayParameter_NoChange()
{
var src1 = @"
class AAttribute : System.Attribute
{
public AAttribute(int[] nums) { }
}
class C
{
[A(new int[] { 1, 2, 3})]
void M()
{
var x = 1;
}
}";
var src2 = @"
class AAttribute : System.Attribute
{
public AAttribute(int[] nums) { }
}
class C
{
[A(new int[] { 1, 2, 3})]
void M()
{
var x = 2;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) });
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_AddAttribute2()
{
var src1 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete, STAThread]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_AddAttribute3()
{
var src1 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete]
[STAThread]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_AddAttribute4()
{
var src1 = @"
using System;
class Test
{
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete, STAThread]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_UpdateAttribute()
{
var src1 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete("""")]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")]
[Fact]
public void MethodUpdate_DeleteAttribute()
{
var src1 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_DeleteAttribute2()
{
var src1 = @"
using System;
class Test
{
[Obsolete, STAThread]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_DeleteAttribute3()
{
var src1 = @"
using System;
class Test
{
[Obsolete]
[STAThread]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var src2 = @"
using System;
class Test
{
[Obsolete]
static void Main(string[] args)
{
System.Console.Write(5);
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_ExplicitlyImplemented1()
{
var src1 = @"
class C : I, J
{
void I.Goo() { Console.WriteLine(2); }
void J.Goo() { Console.WriteLine(1); }
}";
var src2 = @"
class C : I, J
{
void I.Goo() { Console.WriteLine(1); }
void J.Goo() { Console.WriteLine(2); }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void I.Goo() { Console.WriteLine(2); }]@25 -> [void I.Goo() { Console.WriteLine(1); }]@25",
"Update [void J.Goo() { Console.WriteLine(1); }]@69 -> [void J.Goo() { Console.WriteLine(2); }]@69");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_ExplicitlyImplemented2()
{
var src1 = @"
class C : I, J
{
void I.Goo() { Console.WriteLine(1); }
void J.Goo() { Console.WriteLine(2); }
}";
var src2 = @"
class C : I, J
{
void Goo() { Console.WriteLine(1); }
void J.Goo() { Console.WriteLine(2); }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void I.Goo() { Console.WriteLine(1); }]@25 -> [void Goo() { Console.WriteLine(1); }]@25");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "void Goo()", FeaturesResources.method));
}
[WorkItem(754255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754255")]
[Fact]
public void MethodUpdate_UpdateStackAlloc()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
int i = 10;
unsafe
{
int* px2 = &i;
}
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
int i = 10;
unsafe
{
char* buffer = stackalloc char[16];
int* px2 = &i;
}
}
}";
var expectedEdit = @"Update [static void Main(string[] args)
{
int i = 10;
unsafe
{
int* px2 = &i;
}
}]@18 -> [static void Main(string[] args)
{
int i = 10;
unsafe
{
char* buffer = stackalloc char[16];
int* px2 = &i;
}
}]@18";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(expectedEdit);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method));
}
[Theory]
[InlineData("stackalloc int[3]")]
[InlineData("stackalloc int[3] { 1, 2, 3 }")]
[InlineData("stackalloc int[] { 1, 2, 3 }")]
[InlineData("stackalloc[] { 1, 2, 3 }")]
public void MethodUpdate_UpdateStackAlloc2(string stackallocDecl)
{
var src1 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 1; } }";
var src2 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method));
}
[Fact]
public void MethodUpdate_UpdateStackAllocInLambda1()
{
var src1 = "unsafe class C { void M() { F(1, () => { int* a = stackalloc int[10]; }); } }";
var src2 = "unsafe class C { void M() { F(2, () => { int* a = stackalloc int[10]; }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateStackAllocInLambda2()
{
var src1 = "unsafe class C { void M() { F(1, x => { int* a = stackalloc int[10]; }); } }";
var src2 = "unsafe class C { void M() { F(2, x => { int* a = stackalloc int[10]; }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateStackAllocInAnonymousMethod()
{
var src1 = "unsafe class C { void M() { F(1, delegate(int x) { int* a = stackalloc int[10]; }); } }";
var src2 = "unsafe class C { void M() { F(2, delegate(int x) { int* a = stackalloc int[10]; }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateStackAllocInLocalFunction()
{
var src1 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(1); } }";
var src2 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(2); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_SwitchExpressionInLambda1()
{
var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }";
var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_SwitchExpressionInLambda2()
{
var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }";
var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_SwitchExpressionInAnonymousMethod()
{
var src1 = "class C { void M() { F(1, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }";
var src2 = "class C { void M() { F(2, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_SwitchExpressionInLocalFunction()
{
var src1 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(1); } }";
var src2 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(2); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_SwitchExpressionInQuery()
{
var src1 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 1; } }";
var src2 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateAnonymousMethod()
{
var src1 = "class C { void M() { F(1, delegate(int a) { return a; }); } }";
var src2 = "class C { void M() { F(2, delegate(int a) { return a; }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodWithExpressionBody_Update_UpdateAnonymousMethod()
{
var src1 = "class C { void M() => F(1, delegate(int a) { return a; }); }";
var src2 = "class C { void M() => F(2, delegate(int a) { return a; }); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_Query()
{
var src1 = "class C { void M() { F(1, from goo in bar select baz); } }";
var src2 = "class C { void M() { F(2, from goo in bar select baz); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodWithExpressionBody_Update_Query()
{
var src1 = "class C { void M() => F(1, from goo in bar select baz); }";
var src2 = "class C { void M() => F(2, from goo in bar select baz); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_AnonymousType()
{
var src1 = "class C { void M() { F(1, new { A = 1, B = 2 }); } }";
var src2 = "class C { void M() { F(2, new { A = 1, B = 2 }); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodWithExpressionBody_Update_AnonymousType()
{
var src1 = "class C { void M() => F(new { A = 1, B = 2 }); }";
var src2 = "class C { void M() => F(new { A = 10, B = 20 }); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_Iterator_YieldReturn()
{
var src1 = "class C { IEnumerable<int> M() { yield return 1; } }";
var src2 = "class C { IEnumerable<int> M() { yield return 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
VerifyPreserveLocalVariables(edits, preserveLocalVariables: true);
}
[Fact]
public void MethodUpdate_AddYieldReturn()
{
var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }";
var src2 = "class C { IEnumerable<int> M() { yield return 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
VerifyPreserveLocalVariables(edits, preserveLocalVariables: false);
}
[Fact]
public void MethodUpdate_AddYieldReturn_NotSupported()
{
var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }";
var src2 = "class C { IEnumerable<int> M() { yield return 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.MakeMethodIterator, "IEnumerable<int> M()"));
}
[Fact]
public void MethodUpdate_Iterator_YieldBreak()
{
var src1 = "class C { IEnumerable<int> M() { F(); yield break; } }";
var src2 = "class C { IEnumerable<int> M() { G(); yield break; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
VerifyPreserveLocalVariables(edits, preserveLocalVariables: true);
}
[WorkItem(1087305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")]
[Fact]
public void MethodUpdate_LabeledStatement()
{
var src1 = @"
class C
{
static void Main(string[] args)
{
goto Label1;
Label1:
{
Console.WriteLine(1);
}
}
}";
var src2 = @"
class C
{
static void Main(string[] args)
{
goto Label1;
Label1:
{
Console.WriteLine(2);
}
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_LocalFunctionsParameterRefnessInBody()
{
var src1 = @"class C { public void M(int a) { void f(ref int b) => b = 1; } }";
var src2 = @"class C { public void M(int a) { void f(out int b) => b = 1; } } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public void M(int a) { void f(ref int b) => b = 1; }]@10 -> [public void M(int a) { void f(out int b) => b = 1; }]@10");
}
[Fact]
public void MethodUpdate_LambdaParameterRefnessInBody()
{
var src1 = @"class C { public void M(int a) { f((ref int b) => b = 1); } }";
var src2 = @"class C { public void M(int a) { f((out int b) => b = 1); } } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public void M(int a) { f((ref int b) => b = 1); }]@10 -> [public void M(int a) { f((out int b) => b = 1); }]@10");
}
[Fact]
public void Method_ReadOnlyRef_Parameter_InsertWhole()
{
var src1 = "class Test { }";
var src2 = "class Test { int M(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [int M(in int b) => throw null;]@13",
"Insert [(in int b)]@18",
"Insert [in int b]@19");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Method_ReadOnlyRef_Parameter_InsertParameter()
{
var src1 = "class Test { int M() => throw null; }";
var src2 = "class Test { int M(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [in int b]@19");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter));
}
[Fact]
public void Method_ReadOnlyRef_Parameter_Update()
{
var src1 = "class Test { int M(int b) => throw null; }";
var src2 = "class Test { int M(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int b]@19 -> [in int b]@19");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter));
}
[Fact]
public void Method_ReadOnlyRef_ReturnType_Insert()
{
var src1 = "class Test { }";
var src2 = "class Test { ref readonly int M() => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [ref readonly int M() => throw null;]@13",
"Insert [()]@31");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Method_ReadOnlyRef_ReturnType_Update()
{
var src1 = "class Test { int M() => throw null; }";
var src2 = "class Test { ref readonly int M() => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int M() => throw null;]@13 -> [ref readonly int M() => throw null;]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int M()", FeaturesResources.method));
}
[Fact]
public void Method_ImplementingInterface_Add()
{
var src1 = @"
using System;
public interface ISample
{
string Get();
}
public interface IConflict
{
string Get();
}
public class BaseClass : ISample
{
public virtual string Get() => string.Empty;
}
public class SubClass : BaseClass, IConflict
{
public override string Get() => string.Empty;
}
";
var src2 = @"
using System;
public interface ISample
{
string Get();
}
public interface IConflict
{
string Get();
}
public class BaseClass : ISample
{
public virtual string Get() => string.Empty;
}
public class SubClass : BaseClass, IConflict
{
public override string Get() => string.Empty;
string IConflict.Get() => String.Empty;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [string IConflict.Get() => String.Empty;]@325",
"Insert [()]@345");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, "string IConflict.Get()", FeaturesResources.method));
}
[Fact]
public void Method_Partial_DeleteInsert_DefinitionPart()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcC1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { partial void F() { } }";
var srcC2 = "partial class C { partial void F(); }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults(),
});
}
[Fact]
public void Method_Partial_DeleteInsert_ImplementationPart()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcC1 = "partial class C { }";
var srcA2 = "partial class C { partial void F(); }";
var srcB2 = "partial class C { }";
var srcC2 = "partial class C { partial void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }),
});
}
[Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")]
public void Method_Partial_Swap_ImplementationAndDefinitionParts()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcA2 = "partial class C { partial void F() { } }";
var srcB2 = "partial class C { partial void F(); }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }),
DocumentResults(),
});
}
[Fact]
public void Method_Partial_DeleteImplementation()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcA2 = "partial class C { partial void F(); }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) })
});
}
[Fact]
public void Method_Partial_DeleteBoth()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) })
});
}
[Fact]
public void Method_Partial_DeleteInsertBoth()
{
var srcA1 = "partial class C { partial void F(); }";
var srcB1 = "partial class C { partial void F() { } }";
var srcC1 = "partial class C { }";
var srcD1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { }";
var srcC2 = "partial class C { partial void F(); }";
var srcD2 = "partial class C { partial void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) },
new[]
{
DocumentResults(),
DocumentResults(),
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) })
});
}
[Fact]
public void Method_Partial_Insert()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { partial void F(); }";
var srcB2 = "partial class C { partial void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }),
});
}
[Fact]
public void Method_Partial_Insert_Reloadable()
{
var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }";
var srcB1 = "partial class C { }";
var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }";
var srcB2 = "partial class C { partial void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }),
});
}
#endregion
#region Operators
[Theory]
[InlineData("implicit", "explicit")]
[InlineData("explicit", "implicit")]
public void Operator_Modifiers_Update(string oldModifiers, string newModifiers)
{
var src1 = "class C { public static " + oldModifiers + " operator int (C c) => 0; }";
var src2 = "class C { public static " + newModifiers + " operator int (C c) => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [public static " + oldModifiers + " operator int (C c) => 0;]@10 -> [public static " + newModifiers + " operator int (C c) => 0;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public static " + newModifiers + " operator int (C c)", CSharpFeaturesResources.conversion_operator));
}
[Fact]
public void Operator_Modifiers_Update_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static implicit operator int (C c) => 0; }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static explicit operator int (C c) => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Operator_Conversion_ExternModifiers_Add()
{
var src1 = "class C { public static implicit operator bool (C c) => default; }";
var src2 = "class C { extern public static implicit operator bool (C c); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "extern public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator));
}
[Fact]
public void Operator_Conversion_ExternModifiers_Remove()
{
var src1 = "class C { extern public static implicit operator bool (C c); }";
var src2 = "class C { public static implicit operator bool (C c) => default; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator));
}
[Fact]
public void OperatorInsert()
{
var src1 = @"
class C
{
}
";
var src2 = @"
class C
{
public static implicit operator bool (C c)
{
return false;
}
public static C operator +(C c, C d)
{
return c;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertOperator, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator),
Diagnostic(RudeEditKind.InsertOperator, "public static C operator +(C c, C d)", FeaturesResources.operator_));
}
[Fact]
public void OperatorDelete()
{
var src1 = @"
class C
{
public static implicit operator bool (C c)
{
return false;
}
public static C operator +(C c, C d)
{
return c;
}
}
";
var src2 = @"
class C
{
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(CSharpFeaturesResources.conversion_operator, "implicit operator bool(C c)")),
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.operator_, "operator +(C c, C d)")));
}
[Fact]
public void OperatorInsertDelete()
{
var srcA1 = @"
partial class C
{
public static implicit operator bool (C c) => false;
}
";
var srcB1 = @"
partial class C
{
public static C operator +(C c, C d) => c;
}
";
var srcA2 = srcB1;
var srcB2 = srcA1;
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Addition"))
}),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Implicit"))
}),
});
}
[Fact]
public void OperatorUpdate()
{
var src1 = @"
class C
{
public static implicit operator bool (C c)
{
return false;
}
public static C operator +(C c, C d)
{
return c;
}
}
";
var src2 = @"
class C
{
public static implicit operator bool (C c)
{
return true;
}
public static C operator +(C c, C d)
{
return d;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")),
});
}
[Fact]
public void OperatorWithExpressionBody_Update()
{
var src1 = @"
class C
{
public static implicit operator bool (C c) => false;
public static C operator +(C c, C d) => c;
}
";
var src2 = @"
class C
{
public static implicit operator bool (C c) => true;
public static C operator +(C c, C d) => d;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")),
});
}
[Fact]
public void OperatorWithExpressionBody_ToBlockBody()
{
var src1 = "class C { public static C operator +(C c, C d) => d; }";
var src2 = "class C { public static C operator +(C c, C d) { return c; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [public static C operator +(C c, C d) => d;]@10 -> [public static C operator +(C c, C d) { return c; }]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition"))
});
}
[Fact]
public void OperatorWithBlockBody_ToExpressionBody()
{
var src1 = "class C { public static C operator +(C c, C d) { return c; } }";
var src2 = "class C { public static C operator +(C c, C d) => d; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [public static C operator +(C c, C d) { return c; }]@10 -> [public static C operator +(C c, C d) => d;]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition"))
});
}
[Fact]
public void OperatorReorder1()
{
var src1 = @"
class C
{
public static implicit operator bool (C c) { return false; }
public static implicit operator int (C c) { return 1; }
}
";
var src2 = @"
class C
{
public static implicit operator int (C c) { return 1; }
public static implicit operator bool (C c) { return false; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [public static implicit operator int (C c) { return 1; }]@84 -> @18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void OperatorReorder2()
{
var src1 = @"
class C
{
public static C operator +(C c, C d) { return c; }
public static C operator -(C c, C d) { return d; }
}
";
var src2 = @"
class C
{
public static C operator -(C c, C d) { return d; }
public static C operator +(C c, C d) { return c; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [public static C operator -(C c, C d) { return d; }]@74 -> @18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Operator_ReadOnlyRef_Parameter_InsertWhole()
{
var src1 = "class Test { }";
var src2 = "class Test { public static bool operator !(in Test b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public static bool operator !(in Test b) => throw null;]@13",
"Insert [(in Test b)]@42",
"Insert [in Test b]@43");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertOperator, "public static bool operator !(in Test b)", FeaturesResources.operator_));
}
[Fact]
public void Operator_ReadOnlyRef_Parameter_Update()
{
var src1 = "class Test { public static bool operator !(Test b) => throw null; }";
var src2 = "class Test { public static bool operator !(in Test b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Test b]@43 -> [in Test b]@43");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "in Test b", FeaturesResources.parameter));
}
#endregion
#region Constructor, Destructor
[Fact]
public void Constructor_Parameter_AddAttribute()
{
var src1 = @"
class C
{
private int x = 1;
public C(int a)
{
}
}";
var src2 = @"
class C
{
private int x = 2;
public C([System.Obsolete]int a)
{
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [x = 1]@30 -> [x = 2]@30",
"Update [int a]@53 -> [[System.Obsolete]int a]@53");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C..ctor"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
[WorkItem(2068, "https://github.com/dotnet/roslyn/issues/2068")]
public void Constructor_ExternModifier_Add()
{
var src1 = "class C { }";
var src2 = "class C { public extern C(); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [public extern C();]@10",
"Insert [()]@25");
// This can be allowed as the compiler generates an empty constructor, but it's not worth the complexity.
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public extern C()", FeaturesResources.constructor));
}
[Fact]
public void ConstructorInitializer_Update1()
{
var src1 = @"
class C
{
public C(int a) : base(a) { }
}";
var src2 = @"
class C
{
public C(int a) : base(a + 1) { }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public C(int a) : base(a) { }]@18 -> [public C(int a) : base(a + 1) { }]@18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void ConstructorInitializer_Update2()
{
var src1 = @"
class C<T>
{
public C(int a) : base(a) { }
}";
var src2 = @"
class C<T>
{
public C(int a) { }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public C(int a) : base(a) { }]@21 -> [public C(int a) { }]@21");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)"));
}
[Fact]
public void ConstructorInitializer_Update3()
{
var src1 = @"
class C
{
public C(int a) { }
}";
var src2 = @"
class C
{
public C(int a) : base(a) { }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public C(int a) { }]@18 -> [public C(int a) : base(a) { }]@18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void ConstructorInitializer_Update4()
{
var src1 = @"
class C<T>
{
public C(int a) : base(a) { }
}";
var src2 = @"
class C<T>
{
public C(int a) : base(a + 1) { }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public C(int a) : base(a) { }]@21 -> [public C(int a) : base(a + 1) { }]@21");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)"));
}
[WorkItem(743552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743552")]
[Fact]
public void ConstructorUpdate_AddParameter()
{
var src1 = @"
class C
{
public C(int a) { }
}";
var src2 = @"
class C
{
public C(int a, int b) { }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int a)]@26 -> [(int a, int b)]@26",
"Insert [int b]@34");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "int b", FeaturesResources.parameter));
}
[Fact]
public void DestructorDelete()
{
var src1 = @"class B { ~B() { } }";
var src2 = @"class B { }";
var expectedEdit1 = @"Delete [~B() { }]@10";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(expectedEdit1);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()")));
}
[Fact]
public void DestructorDelete_InsertConstructor()
{
var src1 = @"class B { ~B() { } }";
var src2 = @"class B { B() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [B() { }]@10",
"Insert [()]@11",
"Delete [~B() { }]@10");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "B()", FeaturesResources.constructor),
Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()")));
}
[Fact]
[WorkItem(789577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789577")]
public void ConstructorUpdate_AnonymousTypeInFieldInitializer()
{
var src1 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 1; } }";
var src2 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Constructor_Static_Delete()
{
var src1 = "class C { static C() { } }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.static_constructor, "C()")));
}
[Fact]
public void Constructor_Static_Delete_Reloadable()
{
var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { static C() { } }";
var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")));
}
[Fact]
public void Constructor_Static_Insert()
{
var src1 = "class C { }";
var src2 = "class C { static C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) });
}
[Fact]
public void InstanceCtorDelete_Public()
{
var src1 = "class C { public C() { } }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("")]
[InlineData("private")]
[InlineData("protected")]
[InlineData("internal")]
[InlineData("private protected")]
[InlineData("protected internal")]
public void InstanceCtorDelete_NonPublic(string accessibility)
{
var src1 = "class C { [System.Obsolete] " + accessibility + " C() { } }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")),
Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")));
}
[Fact]
public void InstanceCtorDelete_Public_PartialWithInitializerUpdate()
{
var srcA1 = "partial class C { public C() { } }";
var srcB1 = "partial class C { int x = 1; }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int x = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) })
});
}
[Fact]
public void InstanceCtorInsert_Public_Implicit()
{
var src1 = "class C { }";
var src2 = "class C { public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void InstanceCtorInsert_Partial_Public_Implicit()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { public C() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// no change in document A
DocumentResults(),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }),
});
}
[Fact]
public void InstanceCtorInsert_Public_NoImplicit()
{
var src1 = "class C { public C(int a) { } }";
var src2 = "class C { public C(int a) { } public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty))
});
}
[Fact]
public void InstanceCtorInsert_Partial_Public_NoImplicit()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { public C(int a) { } }";
var srcA2 = "partial class C { public C() { } }";
var srcB2 = "partial class C { public C(int a) { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty))
}),
// no change in document B
DocumentResults(),
});
}
[Fact]
public void InstanceCtorInsert_Private_Implicit1()
{
var src1 = "class C { }";
var src2 = "class C { private C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "private C()", FeaturesResources.constructor));
}
[Fact]
public void InstanceCtorInsert_Private_Implicit2()
{
var src1 = "class C { }";
var src2 = "class C { C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "C()", FeaturesResources.constructor));
}
[Fact]
public void InstanceCtorInsert_Protected_PublicImplicit()
{
var src1 = "class C { }";
var src2 = "class C { protected C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "protected C()", FeaturesResources.constructor));
}
[Fact]
public void InstanceCtorInsert_Internal_PublicImplicit()
{
var src1 = "class C { }";
var src2 = "class C { internal C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor));
}
[Fact]
public void InstanceCtorInsert_Internal_ProtectedImplicit()
{
var src1 = "abstract class C { }";
var src2 = "abstract class C { internal C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor));
}
[Fact]
public void InstanceCtorUpdate_ProtectedImplicit()
{
var src1 = "abstract class C { }";
var src2 = "abstract class C { protected C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void InstanceCtorInsert_Private_NoImplicit()
{
var src1 = "class C { public C(int a) { } }";
var src2 = "class C { public C(int a) { } private C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C")
.InstanceConstructors.Single(ctor => ctor.DeclaredAccessibility == Accessibility.Private))
});
}
[Fact]
public void InstanceCtorInsert_Internal_NoImplicit()
{
var src1 = "class C { public C(int a) { } }";
var src2 = "class C { public C(int a) { } internal C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void InstanceCtorInsert_Protected_NoImplicit()
{
var src1 = "class C { public C(int a) { } }";
var src2 = "class C { public C(int a) { } protected C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void InstanceCtorInsert_InternalProtected_NoImplicit()
{
var src1 = "class C { public C(int a) { } }";
var src2 = "class C { public C(int a) { } internal protected C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void StaticCtor_Partial_DeleteInsert()
{
var srcA1 = "partial class C { static C() { } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { static C() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void InstanceCtor_Partial_DeletePrivateInsertPrivate()
{
var srcA1 = "partial class C { C() { } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { C() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void InstanceCtor_Partial_DeletePublicInsertPublic()
{
var srcA1 = "partial class C { public C() { } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { public C() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void InstanceCtor_Partial_DeletePrivateInsertPublic()
{
var srcA1 = "partial class C { C() { } }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { public C() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility
DocumentResults(
semanticEdits: NoSemanticEdits),
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }),
});
}
[Fact]
public void StaticCtor_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { static C() { } }";
var srcA2 = "partial class C { static C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_InsertPublicDeletePublic()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { public C() { } }";
var srcA2 = "partial class C { public C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_InsertPrivateDeletePrivate()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { private C() { } }";
var srcA2 = "partial class C { private C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_DeleteInternalInsertInternal()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { internal C() { } }";
var srcA2 = "partial class C { internal C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_InsertInternalDeleteInternal_WithBody()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { internal C() { } }";
var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
// delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_InsertPublicDeletePrivate()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { private C() { } }";
var srcA2 = "partial class C { public C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }),
// delete of the constructor in partial part will be reported as rude in the the other document where it was inserted with changed accessibility
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_InsertInternalDeletePrivate()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { private C() { } }";
var srcA2 = "partial class C { internal C() { } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor) }),
DocumentResults(),
});
}
[Fact]
public void InstanceCtor_Partial_Update_LambdaInInitializer1()
{
var src1 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
public C()
{
F(<N:0.2>c => c + 1</N:0.2>);
}
}
";
var src2 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
public C()
{
F(<N:0.2>c => c + 2</N:0.2>);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void InstanceCtor_Partial_Update_LambdaInInitializer_Trivia1()
{
var src1 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
public C() { F(<N:0.2>c => c + 1</N:0.2>); }
}
";
var src2 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
/*new trivia*/public C() { F(<N:0.2>c => c + 1</N:0.2>); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void InstanceCtor_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1()
{
var src1 = @"
using System;
public interface I { int B { get; } }
public interface J { int B { get; } }
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C : I, J
{
int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>);
int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>);
public C()
{
F(<N:0.3>c => c + 1</N:0.3>);
}
}
";
var src2 = @"
using System;
public interface I { int B { get; } }
public interface J { int B { get; } }
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C : I, J
{
int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>);
int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>);
public C()
{
F(<N:0.3>c => c + 2</N:0.3>);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void InstanceCtor_Partial_Insert_Parameterless_LambdaInInitializer1()
{
var src1 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
}
";
var src2 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
public C() // new ctor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()"));
// TODO:
//var syntaxMap = GetSyntaxMap(src1, src2);
//edits.VerifySemantics(
// ActiveStatementsDescription.Empty,
// new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void InstanceCtor_Partial_Insert_WithParameters_LambdaInInitializer1()
{
var src1 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
}
";
var src2 = @"
using System;
partial class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int B { get; } = F(<N:0.1>b => b + 1</N:0.1>);
public C(int x) // new ctor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
_ = GetSyntaxMap(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)"));
// TODO: bug https://github.com/dotnet/roslyn/issues/2504
//edits.VerifySemantics(
// ActiveStatementsDescription.Empty,
// new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void InstanceCtor_Partial_Explicit_Update()
{
var srcA1 = @"
using System;
partial class C
{
C(int arg) => Console.WriteLine(0);
C(bool arg) => Console.WriteLine(1);
}
";
var srcB1 = @"
using System;
partial class C
{
int a <N:0.0>= 1</N:0.0>;
C(uint arg) => Console.WriteLine(2);
}
";
var srcA2 = @"
using System;
partial class C
{
C(int arg) => Console.WriteLine(0);
C(bool arg) => Console.WriteLine(1);
}
";
var srcB2 = @"
using System;
partial class C
{
int a <N:0.0>= 2</N:0.0>; // updated field initializer
C(uint arg) => Console.WriteLine(2);
C(byte arg) => Console.WriteLine(3); // new ctor
}
";
var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0];
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// No changes in document A
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Int32"), partialType: "C", syntaxMap: syntaxMapB),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Boolean"), partialType: "C", syntaxMap: syntaxMapB),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "UInt32"), partialType: "C", syntaxMap: syntaxMapB),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Byte"), syntaxMap: null),
})
});
}
[Fact]
public void InstanceCtor_Partial_Explicit_Update_SemanticError()
{
var srcA1 = @"
using System;
partial class C
{
C(int arg) => Console.WriteLine(0);
C(int arg) => Console.WriteLine(1);
}
";
var srcB1 = @"
using System;
partial class C
{
int a = 1;
}
";
var srcA2 = @"
using System;
partial class C
{
C(int arg) => Console.WriteLine(0);
C(int arg) => Console.WriteLine(1);
}
";
var srcB2 = @"
using System;
partial class C
{
int a = 2;
C(int arg) => Console.WriteLine(2);
}
";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
// No changes in document A
DocumentResults(),
// The actual edits do not matter since there are semantic errors in the compilation.
// We just should not crash.
DocumentResults(diagnostics: Array.Empty<RudeEditDiagnosticDescription>())
});
}
[Fact]
public void InstanceCtor_Partial_Implicit_Update()
{
var srcA1 = "partial class C { int F = 1; }";
var srcB1 = "partial class C { int G = 1; }";
var srcA2 = "partial class C { int F = 2; }";
var srcB2 = "partial class C { int G = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void ParameterlessConstructor_SemanticError_Delete1()
{
var src1 = @"
class C
{
D() {}
}
";
var src2 = @"
class C
{
}
";
var edits = GetTopEdits(src1, src2);
// The compiler interprets D() as a constructor declaration.
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")));
}
[Fact]
public void Constructor_SemanticError_Partial()
{
var src1 = @"
partial class C
{
partial void C(int x);
}
partial class C
{
partial void C(int x)
{
System.Console.WriteLine(1);
}
}
";
var src2 = @"
partial class C
{
partial void C(int x);
}
partial class C
{
partial void C(int x)
{
System.Console.WriteLine(2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("C").PartialImplementationPart)
});
}
[Fact]
public void PartialDeclaration_Delete()
{
var srcA1 = "partial class C { public C() { } void F() { } }";
var srcB1 = "partial class C { int x = 1; }";
var srcA2 = "";
var srcB2 = "partial class C { int x = 2; void F() { } }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void PartialDeclaration_Insert()
{
var srcA1 = "";
var srcB1 = "partial class C { int x = 1; void F() { } }";
var srcA2 = "partial class C { public C() { } void F() { } }";
var srcB2 = "partial class C { int x = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }),
});
}
[Fact]
public void PartialDeclaration_Insert_Reloadable()
{
var srcA1 = "";
var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }";
var srcA2 = "partial class C { public C() { } void F() { } }";
var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")
}),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")
}),
});
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void Constructor_DeleteParameterless(string typeKind)
{
var src1 = @"
" + typeKind + @" C
{
private int a = 10;
private int b;
public C() { b = 3; }
}
";
var src2 = @"
" + typeKind + @" C
{
private int a = 10;
private int b;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [public C() { b = 3; }]@66", "Delete [()]@74");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void Constructor_InsertParameterless(string typeKind)
{
var src1 = @"
" + typeKind + @" C
{
private int a = 10;
private int b;
}
";
var src2 = @"
" + typeKind + @" C
{
private int a = 10;
private int b;
public C() { b = 3; }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [public C() { b = 3; }]@66", "Insert [()]@74");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Constructor_BlockBodyToExpressionBody()
{
var src1 = @"
public class C
{
private int _value;
public C(int value) { _value = value; }
}
";
var src2 = @"
public class C
{
private int _value;
public C(int value) => _value = value;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void ConstructorWithInitializer_BlockBodyToExpressionBody()
{
var src1 = @"
public class B { B(int value) {} }
public class C : B
{
private int _value;
public C(int value) : base(value) { _value = value; }
}
";
var src2 = @"
public class B { B(int value) {} }
public class C : B
{
private int _value;
public C(int value) : base(value) => _value = value;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Constructor_ExpressionBodyToBlockBody()
{
var src1 = @"
public class C
{
private int _value;
public C(int value) => _value = value;
}
";
var src2 = @"
public class C
{
private int _value;
public C(int value) { _value = value; }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void ConstructorWithInitializer_ExpressionBodyToBlockBody()
{
var src1 = @"
public class B { B(int value) {} }
public class C : B
{
private int _value;
public C(int value) : base(value) => _value = value;
}
";
var src2 = @"
public class B { B(int value) {} }
public class C : B
{
private int _value;
public C(int value) : base(value) { _value = value; }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Destructor_BlockBodyToExpressionBody()
{
var src1 = @"
public class C
{
~C() { Console.WriteLine(0); }
}
";
var src2 = @"
public class C
{
~C() => Console.WriteLine(0);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Destructor_ExpressionBodyToBlockBody()
{
var src1 = @"
public class C
{
~C() => Console.WriteLine(0);
}
";
var src2 = @"
public class C
{
~C() { Console.WriteLine(0); }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false)
});
}
[Fact]
public void Constructor_ReadOnlyRef_Parameter_InsertWhole()
{
var src1 = "class Test { }";
var src2 = "class Test { Test(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [Test(in int b) => throw null;]@13",
"Insert [(in int b)]@17",
"Insert [in int b]@18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Constructor_ReadOnlyRef_Parameter_InsertParameter()
{
var src1 = "class Test { Test() => throw null; }";
var src2 = "class Test { Test(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [in int b]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter));
}
[Fact]
public void Constructor_ReadOnlyRef_Parameter_Update()
{
var src1 = "class Test { Test(int b) => throw null; }";
var src2 = "class Test { Test(in int b) => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int b]@18 -> [in int b]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter));
}
#endregion
#region Fields and Properties with Initializers
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void FieldInitializer_Update1(string typeKind)
{
var src1 = typeKind + " C { int a = 0; }";
var src2 = typeKind + " C { int a = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 0]@15 -> [a = 1]@15");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void PropertyInitializer_Update1(string typeKind)
{
var src1 = typeKind + " C { int a { get; } = 0; }";
var src2 = typeKind + " C { int a { get; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a { get; } = 0;]@11 -> [int a { get; } = 1;]@11");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializer_Update2()
{
var src1 = "class C { int a = 0; }";
var src2 = "class C { int a; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 0]@14 -> [a]@14");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyInitializer_Update2()
{
var src1 = "class C { int a { get; } = 0; }";
var src2 = "class C { int a { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a { get; } = 0;]@10 -> [int a { get { return 1; } }]@10",
"Update [get;]@18 -> [get { return 1; }]@18");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true));
}
[Fact]
public void PropertyInitializer_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int a { get; } = 0; }";
var srcA2 = "partial class C { int a { get { return 1; } } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
DocumentResults()
});
}
[Fact]
public void FieldInitializer_Update3()
{
var src1 = "class C { int a; }";
var src2 = "class C { int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@14 -> [a = 0]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void PropertyInitializer_Update3()
{
var src1 = "class C { int a { get { return 1; } } }";
var src2 = "class C { int a { get; } = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a { get { return 1; } }]@10 -> [int a { get; } = 0;]@10",
"Update [get { return 1; }]@18 -> [get;]@18");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void FieldInitializerUpdate_StaticCtorUpdate1()
{
var src1 = "class C { static int a; static C() { } }";
var src2 = "class C { static int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@21 -> [a = 0]@21",
"Delete [static C() { }]@24",
"Delete [()]@32");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void PropertyInitializerUpdate_StaticCtorUpdate1()
{
var src1 = "class C { static int a { get; } = 1; static C() { } }";
var src2 = "class C { static int a { get; } = 2;}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void FieldInitializerUpdate_InstanceCtorUpdate_Private(string typeKind)
{
var src1 = typeKind + " C { int a; [System.Obsolete]C() { } }";
var src2 = typeKind + " C { int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")),
Diagnostic(RudeEditKind.ChangingAccessibility, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")));
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void PropertyInitializerUpdate_InstanceCtorUpdate_Private(string typeKind)
{
var src1 = typeKind + " C { int a { get; } = 1; C() { } }";
var src2 = typeKind + " C { int a { get; } = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingAccessibility, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")));
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void FieldInitializerUpdate_InstanceCtorUpdate_Public(string typeKind)
{
var src1 = typeKind + " C { int a; public C() { } }";
var src2 = typeKind + " C { int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void PropertyInitializerUpdate_InstanceCtorUpdate_Public(string typeKind)
{
var src1 = typeKind + " C { int a { get; } = 1; public C() { } }";
var src2 = typeKind + " C { int a { get; } = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializerUpdate_StaticCtorUpdate2()
{
var src1 = "class C { static int a; static C() { } }";
var src2 = "class C { static int a = 0; static C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@21 -> [a = 0]@21");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void PropertyInitializerUpdate_StaticCtorUpdate2()
{
var src1 = "class C { static int a { get; } = 1; static C() { } }";
var src2 = "class C { static int a { get; } = 2; static C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void FieldInitializerUpdate_InstanceCtorUpdate2(string typeKind)
{
var src1 = typeKind + " C { int a; public C() { } }";
var src2 = typeKind + " C { int a = 0; public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@15 -> [a = 0]@15");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void PropertyInitializerUpdate_InstanceCtorUpdate2(string typeKind)
{
var src1 = typeKind + " C { int a { get; } = 1; public C() { } }";
var src2 = typeKind + " C { int a { get; } = 2; public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializerUpdate_InstanceCtorUpdate3()
{
var src1 = "class C { int a; }";
var src2 = "class C { int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@14 -> [a = 0]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void PropertyInitializerUpdate_InstanceCtorUpdate3()
{
var src1 = "class C { int a { get; } = 1; }";
var src2 = "class C { int a { get; } = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializerUpdate_InstanceCtorUpdate4()
{
var src1 = "class C { int a = 0; }";
var src2 = "class C { int a; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 0]@14 -> [a]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializerUpdate_InstanceCtorUpdate5()
{
var src1 = "class C { int a; private C(int a) { } private C(bool a) { } }";
var src2 = "class C { int a = 0; private C(int a) { } private C(bool a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@14 -> [a = 0]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true),
});
}
[Fact]
public void FieldInitializerUpdate_Struct_InstanceCtorUpdate5()
{
var src1 = "struct C { int a; private C(int a) { } private C(bool a) { } }";
var src2 = "struct C { int a = 0; private C(int a) { } private C(bool a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@15 -> [a = 0]@15");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C()"), preserveLocalVariables: true),
});
}
[Fact]
public void PropertyInitializerUpdate_InstanceCtorUpdate5()
{
var src1 = "class C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }";
var src2 = "class C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true),
});
}
[Fact]
public void PropertyInitializerUpdate_Struct_InstanceCtorUpdate5()
{
var src1 = "struct C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }";
var src2 = "struct C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C()"), preserveLocalVariables: true),
});
}
[Fact]
public void FieldInitializerUpdate_InstanceCtorUpdate6()
{
var src1 = "class C { int a; private C(int a) : this(true) { } private C(bool a) { } }";
var src2 = "class C { int a = 0; private C(int a) : this(true) { } private C(bool a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@14 -> [a = 0]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true)
});
}
[Fact]
public void FieldInitializerUpdate_StaticCtorInsertImplicit()
{
var src1 = "class C { static int a; }";
var src2 = "class C { static int a = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@21 -> [a = 0]@21");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) });
}
[Fact]
public void FieldInitializerUpdate_StaticCtorInsertExplicit()
{
var src1 = "class C { static int a; }";
var src2 = "class C { static int a = 0; static C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [static C() { }]@28",
"Insert [()]@36",
"Update [a]@21 -> [a = 0]@21");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void FieldInitializerUpdate_InstanceCtorInsertExplicit(string typeKind)
{
var src1 = typeKind + " C { int a; }";
var src2 = typeKind + " C { int a = 0; public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Theory]
[InlineData("class ")]
[InlineData("struct")]
public void PropertyInitializerUpdate_InstanceCtorInsertExplicit(string typeKind)
{
var src1 = typeKind + " C { int a { get; } = 1; }";
var src2 = typeKind + " C { int a { get; } = 2; public C() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) });
}
[Fact]
public void FieldInitializerUpdate_GenericType()
{
var src1 = "class C<T> { int a = 1; }";
var src2 = "class C<T> { int a = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@17 -> [a = 2]@17");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericTypeUpdate, "a = 2"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"));
}
[Fact]
public void PropertyInitializerUpdate_GenericType()
{
var src1 = "class C<T> { int a { get; } = 1; }";
var src2 = "class C<T> { int a { get; } = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericTypeUpdate, "int a"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"));
}
[Fact]
public void FieldInitializerUpdate_StackAllocInConstructor()
{
var src1 = "unsafe class C { int a = 1; public C() { int* a = stackalloc int[10]; } }";
var src2 = "unsafe class C { int a = 2; public C() { int* a = stackalloc int[10]; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@21 -> [a = 2]@21");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor));
}
[Fact]
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")]
public void FieldInitializerUpdate_SwitchExpressionInConstructor()
{
var src1 = "class C { int a = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }";
var src2 = "class C { int a = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_StackAllocInConstructor1()
{
var src1 = "unsafe class C { int a { get; } = 1; public C() { int* a = stackalloc int[10]; } }";
var src2 = "unsafe class C { int a { get; } = 2; public C() { int* a = stackalloc int[10]; } }";
var edits = GetTopEdits(src1, src2);
// TODO (tomat): diagnostic should point to the property initializer
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor));
}
[Fact]
public void PropertyInitializerUpdate_StackAllocInConstructor2()
{
var src1 = "unsafe class C { int a { get; } = 1; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }";
var src2 = "unsafe class C { int a { get; } = 2; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_StackAllocInConstructor3()
{
var src1 = "unsafe class C { int a { get; } = 1; public C() { } public C(int b) { int* a = stackalloc int[10]; } }";
var src2 = "unsafe class C { int a { get; } = 2; public C() { } public C(int b) { int* a = stackalloc int[10]; } }";
var edits = GetTopEdits(src1, src2);
// TODO (tomat): diagnostic should point to the property initializer
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor));
}
[Fact]
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")]
public void PropertyInitializerUpdate_SwitchExpressionInConstructor1()
{
var src1 = "class C { int a { get; } = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }";
var src2 = "class C { int a { get; } = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")]
public void PropertyInitializerUpdate_SwitchExpressionInConstructor2()
{
var src1 = "class C { int a { get; } = 1; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }";
var src2 = "class C { int a { get; } = 2; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")]
public void PropertyInitializerUpdate_SwitchExpressionInConstructor3()
{
var src1 = "class C { int a { get; } = 1; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }";
var src2 = "class C { int a { get; } = 2; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_LambdaInConstructor()
{
var src1 = "class C { int a = 1; public C() { F(() => {}); } static void F(System.Action a) {} }";
var src2 = "class C { int a = 2; public C() { F(() => {}); } static void F(System.Action a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@14 -> [a = 2]@14");
edits.VerifySemanticDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_LambdaInConstructor()
{
var src1 = "class C { int a { get; } = 1; public C() { F(() => {}); } static void F(System.Action a) {} }";
var src2 = "class C { int a { get; } = 2; public C() { F(() => {}); } static void F(System.Action a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_QueryInConstructor()
{
var src1 = "using System.Linq; class C { int a = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }";
var src2 = "using System.Linq; class C { int a = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@33 -> [a = 2]@33");
edits.VerifySemanticDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_QueryInConstructor()
{
var src1 = "using System.Linq; class C { int a { get; } = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }";
var src2 = "using System.Linq; class C { int a { get; } = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_AnonymousTypeInConstructor()
{
var src1 = "class C { int a = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }";
var src2 = "class C { int a = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_AnonymousTypeInConstructor()
{
var src1 = "class C { int a { get; } = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }";
var src2 = "class C { int a { get; } = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_PartialTypeWithSingleDeclaration()
{
var src1 = "partial class C { int a = 1; }";
var src2 = "partial class C { int a = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@22 -> [a = 2]@22");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void PropertyInitializerUpdate_PartialTypeWithSingleDeclaration()
{
var src1 = "partial class C { int a { get; } = 1; }";
var src2 = "partial class C { int a { get; } = 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void FieldInitializerUpdate_PartialTypeWithMultipleDeclarations()
{
var src1 = "partial class C { int a = 1; } partial class C { }";
var src2 = "partial class C { int a = 2; } partial class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 1]@22 -> [a = 2]@22");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void PropertyInitializerUpdate_PartialTypeWithMultipleDeclarations()
{
var src1 = "partial class C { int a { get; } = 1; } partial class C { }";
var src2 = "partial class C { int a { get; } = 2; } partial class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void FieldInitializerUpdate_ParenthesizedLambda()
{
var src1 = "class C { int a = F(1, (x, y) => x + y); }";
var src2 = "class C { int a = F(2, (x, y) => x + y); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_ParenthesizedLambda()
{
var src1 = "class C { int a { get; } = F(1, (x, y) => x + y); }";
var src2 = "class C { int a { get; } = F(2, (x, y) => x + y); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_SimpleLambda()
{
var src1 = "class C { int a = F(1, x => x); }";
var src2 = "class C { int a = F(2, x => x); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_SimpleLambda()
{
var src1 = "class C { int a { get; } = F(1, x => x); }";
var src2 = "class C { int a { get; } = F(2, x => x); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_Query()
{
var src1 = "class C { int a = F(1, from goo in bar select baz); }";
var src2 = "class C { int a = F(2, from goo in bar select baz); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_Query()
{
var src1 = "class C { int a { get; } = F(1, from goo in bar select baz); }";
var src2 = "class C { int a { get; } = F(2, from goo in bar select baz); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_AnonymousType()
{
var src1 = "class C { int a = F(1, new { A = 1, B = 2 }); }";
var src2 = "class C { int a = F(2, new { A = 1, B = 2 }); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyInitializerUpdate_AnonymousType()
{
var src1 = "class C { int a { get; } = F(1, new { A = 1, B = 2 }); }";
var src2 = "class C { int a { get; } = F(2, new { A = 1, B = 2 }); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 2</N:0.1>);
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithoutLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = 1;
int B = F(<N:0.0>b => b + 1</N:0.0>);
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = 2;
int B = F(<N:0.0>b => b + 1</N:0.0>);
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C() {}
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 2</N:0.1>);
public C() {}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithoutLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = 1;
int B = F(<N:0.0>b => b + 1</N:0.0>);
public C() {}
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = 2;
int B = F(<N:0.0>b => b + 1</N:0.0>);
public C() {}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) });
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) {}
public C(bool b) {}
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 2</N:0.1>);
public C(int a) {}
public C(bool b) {}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 2</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(d => d + 1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 2</N:0.2>); }
public C(bool b) { F(d => d + 1); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(d => d + 1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); }
public C(bool b) { F(d => d + 1); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(c => c + 1); }
public C(bool b) { Console.WriteLine(1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(int a) { F(c => c + 1); }
public C(bool b) { Console.WriteLine(2); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_EditConstructorNotIncludingInitializers()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(a => a + 1);
int B = F(b => b + 1);
public C(int a) { F(c => c + 1); }
public C(bool b) : this(1) { Console.WriteLine(1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(a => a + 1);
int B = F(b => b + 1);
public C(int a) { F(c => c + 1); }
public C(bool b) : this(1) { Console.WriteLine(2); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"))
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_RemoveCtorInitializer1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); }
public C(bool b) : this(1) { Console.WriteLine(1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); }
public C(bool b) { Console.WriteLine(1); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_AddCtorInitializer1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(a => a + 1);
int B = F(b => b + 1);
public C(int a) { F(c => c + 1); }
public C(bool b) { Console.WriteLine(1); }
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(a => a + 1);
int B = F(b => b + 1);
public C(int a) { F(c => c + 1); }
public C(bool b) : this(1) { Console.WriteLine(1); }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"))
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_UpdateBaseCtorInitializerWithLambdas1()
{
var src1 = @"
using System;
class B
{
public B(int a) { }
}
class C : B
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(bool b)
: base(F(<N:0.2>c => c + 1</N:0.2>))
{
F(<N:0.3>d => d + 1</N:0.3>);
}
}
";
var src2 = @"
using System;
class B
{
public B(int a) { }
}
class C : B
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(<N:0.1>b => b + 1</N:0.1>);
public C(bool b)
: base(F(<N:0.2>c => c + 2</N:0.2>))
{
F(<N:0.3>d => d + 1</N:0.3>);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0])
});
}
[Fact]
public void FieldInitializerUpdate_Lambdas_PartialDeclarationDelete_SingleDocument()
{
var src1 = @"
partial class C
{
int x = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int y = F(<N:0.1>a => a + 10</N:0.1>);
}
partial class C
{
public C() { }
static int F(Func<int, int> x) => 1;
}
";
var src2 = @"
partial class C
{
int x = F(<N:0.0>a => a + 1</N:0.0>);
}
partial class C
{
int y = F(<N:0.1>a => a + 10</N:0.1>);
static int F(Func<int, int> x) => 1;
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), syntaxMap[0]),
});
}
[Fact]
public void FieldInitializerUpdate_ActiveStatements1()
{
var src1 = @"
using System;
class C
{
<AS:0>int A = <N:0.0>1</N:0.0>;</AS:0>
int B = 1;
public C(int a) { Console.WriteLine(1); }
public C(bool b) { Console.WriteLine(1); }
}
";
var src2 = @"
using System;
class C
{
<AS:0>int A = <N:0.0>1</N:0.0>;</AS:0>
int B = 2;
public C(int a) { Console.WriteLine(1); }
public C(bool b) { Console.WriteLine(1); }
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
var activeStatements = GetActiveStatements(src1, src2);
edits.VerifySemantics(
activeStatements,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]),
});
}
[Fact]
public void PropertyWithInitializer_SemanticError_Partial()
{
var src1 = @"
partial class C
{
partial int P => 1;
}
partial class C
{
partial int P => 1;
}
";
var src2 = @"
partial class C
{
partial int P => 1;
}
partial class C
{
partial int P => 2;
public C() { }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => ((IPropertySymbol)c.GetMember<INamedTypeSymbol>("C").GetMembers("P").First()).GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void Field_Partial_DeleteInsert_InitializerRemoval()
{
var srcA1 = "partial class C { int F = 1; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int F; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
[Fact]
public void Field_Partial_DeleteInsert_InitializerUpdate()
{
var srcA1 = "partial class C { int F = 1; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { int F = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
});
}
#endregion
#region Fields
[Fact]
public void Field_Rename()
{
var src1 = "class C { int a = 0; }";
var src2 = "class C { int b = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a = 0]@14 -> [b = 0]@14");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "b = 0", FeaturesResources.field));
}
[Fact]
public void Field_Kind_Update()
{
var src1 = "class C { Action a; }";
var src2 = "class C { event Action a; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Action a;]@10 -> [event Action a;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.FieldKindUpdate, "event Action a", FeaturesResources.event_));
}
[Theory]
[InlineData("static")]
[InlineData("volatile")]
[InlineData("const")]
public void Field_Modifiers_Update(string oldModifiers, string newModifiers = "")
{
if (oldModifiers != "")
{
oldModifiers += " ";
}
if (newModifiers != "")
{
newModifiers += " ";
}
var src1 = "class C { " + oldModifiers + "int F = 0; }";
var src2 = "class C { " + newModifiers + "int F = 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [" + oldModifiers + "int F = 0;]@10 -> [" + newModifiers + "int F = 0;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F = 0", FeaturesResources.field));
}
[Fact]
public void Field_Modifier_Add_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int F; }";
var srcA2 = "partial class C { static int F; }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.ModifiersUpdate, "F", FeaturesResources.field)
}),
DocumentResults(),
});
}
[Fact]
public void Field_Attribute_Add_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int F; }";
var srcA2 = "partial class C { [System.Obsolete]int F; }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"))
}),
DocumentResults(),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Field_FixedSize_Update()
{
var src1 = "struct S { public unsafe fixed byte a[1], b[2]; }";
var src2 = "struct S { public unsafe fixed byte a[2], b[3]; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a[1]]@36 -> [a[2]]@36",
"Update [b[2]]@42 -> [b[3]]@42");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "a[2]", FeaturesResources.field),
Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "b[3]", FeaturesResources.field));
}
[WorkItem(1120407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120407")]
[Fact]
public void Field_Const_Update()
{
var src1 = "class C { const int x = 0; }";
var src2 = "class C { const int x = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [x = 0]@20 -> [x = 1]@20");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, "x = 1", FeaturesResources.const_field));
}
[Fact]
public void Field_Event_VariableDeclarator_Update()
{
var src1 = "class C { event Action a; }";
var src2 = "class C { event Action a = () => { }; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@23 -> [a = () => { }]@23");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Field_Reorder()
{
var src1 = "class C { int a = 0; int b = 1; int c = 2; }";
var src2 = "class C { int c = 2; int a = 0; int b = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int c = 2;]@32 -> @10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "int c = 2", FeaturesResources.field));
}
[Fact]
public void Field_Insert()
{
var src1 = "class C { }";
var src2 = "class C { int a = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [int a = 1;]@10",
"Insert [int a = 1]@10",
"Insert [a = 1]@14");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.a")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true)
});
}
[Fact]
public void Field_Insert_IntoStruct()
{
var src1 = @"
struct S
{
public int a;
public S(int z) { this = default(S); a = z; }
}
";
var src2 = @"
struct S
{
public int a;
private int b;
private static int c;
private static int f = 1;
private event System.Action d;
public S(int z) { this = default(S); a = z; }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoStruct, "b", FeaturesResources.field, CSharpFeaturesResources.struct_),
Diagnostic(RudeEditKind.InsertIntoStruct, "c", FeaturesResources.field, CSharpFeaturesResources.struct_),
Diagnostic(RudeEditKind.InsertIntoStruct, "f = 1", FeaturesResources.field, CSharpFeaturesResources.struct_),
Diagnostic(RudeEditKind.InsertIntoStruct, "d", CSharpFeaturesResources.event_field, CSharpFeaturesResources.struct_));
}
[Fact]
public void Field_Insert_IntoLayoutClass_Auto()
{
var src1 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Auto)]
class C
{
private int a;
}
";
var src2 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Auto)]
class C
{
private int a;
private int b;
private int c;
private static int d;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.b")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.c")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.d")),
});
}
[Fact]
public void Field_Insert_IntoLayoutClass_Explicit()
{
var src1 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Explicit)]
class C
{
[FieldOffset(0)]
private int a;
}
";
var src2 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Explicit)]
class C
{
[FieldOffset(0)]
private int a;
[FieldOffset(0)]
private int b;
[FieldOffset(4)]
private int c;
private static int d;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_));
}
[Fact]
public void Field_Insert_IntoLayoutClass_Sequential()
{
var src1 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
private int a;
}
";
var src2 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
private int a;
private int b;
private int c;
private static int d;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_));
}
[Fact]
public void Field_Insert_WithInitializersAndLambdas1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
public C()
{
F(<N:0.1>c => c + 1</N:0.1>);
}
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(b => b + 1); // new field
public C()
{
F(<N:0.1>c => c + 1</N:0.1>);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0])
});
}
[Fact]
public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(b => b + 1); // new field
public C() // new ctor replacing existing implicit constructor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0])
});
}
[Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
public C(int x) {}
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
public C(int x) {}
public C() // new ctor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()"));
// TODO (bug https://github.com/dotnet/roslyn/issues/2504):
//edits.VerifySemantics(
// ActiveStatementsDescription.Empty,
// new[]
// {
// SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0])
// });
}
[Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0.0>a => a + 1</N:0.0>);
int B = F(b => b + 1); // new field
public C(int x) // new ctor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
_ = GetSyntaxMap(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)"));
// TODO (bug https://github.com/dotnet/roslyn/issues/2504):
//edits.VerifySemantics(
// ActiveStatementsDescription.Empty,
// new[]
// {
// SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")),
// SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0])
// });
}
[Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1()
{
var src1 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(null);
}
";
var src2 = @"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(null);
int B = F(b => b + 1); // new field
public C(int x) // new ctor
{
F(c => c + 1);
}
}
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single())
});
}
[Fact]
public void Field_Insert_NotSupportedByRuntime()
{
var src1 = "class C { }";
var src2 = "class C { public int a = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddStaticFieldToExistingType,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field));
}
[Fact]
public void Field_Insert_Static_NotSupportedByRuntime()
{
var src1 = "class C { }";
var src2 = "class C { public static int a = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddInstanceFieldToExistingType,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field));
}
[Fact]
public void Field_Attribute_Add_NotSupportedByRuntime()
{
var src1 = @"
class C
{
public int a = 1, x = 1;
}";
var src2 = @"
class C
{
[System.Obsolete]public int a = 1, x = 1;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public int a = 1, x = 1;]@18 -> [[System.Obsolete]public int a = 1, x = 1;]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field));
}
[Fact]
public void Field_Attribute_Add()
{
var src1 = @"
class C
{
public int a, b;
}";
var src2 = @"
class C
{
[System.Obsolete]public int a, b;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.b"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Field_Attribute_Add_WithInitializer()
{
var src1 = @"
class C
{
int a;
}";
var src2 = @"
class C
{
[System.Obsolete]int a = 0;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Field_Attribute_DeleteInsertUpdate_WithInitializer()
{
var srcA1 = "partial class C { int a = 1; }";
var srcB1 = "partial class C { }";
var srcA2 = "partial class C { }";
var srcB2 = "partial class C { [System.Obsolete]int a = 2; }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a"), preserveLocalVariables: true),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Field_Delete1()
{
var src1 = "class C { int a = 1; }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [int a = 1;]@10",
"Delete [int a = 1]@10",
"Delete [a = 1]@14");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a")));
}
[Fact]
public void Field_UnsafeModifier_Update()
{
var src1 = "struct Node { unsafe Node* left; }";
var src2 = "struct Node { Node* left; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [unsafe Node* left;]@14 -> [Node* left;]@14");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Field_ModifierAndType_Update()
{
var src1 = "struct Node { unsafe Node* left; }";
var src2 = "struct Node { Node left; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [unsafe Node* left;]@14 -> [Node left;]@14",
"Update [Node* left]@21 -> [Node left]@14");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "Node left", FeaturesResources.field));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("object", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Field_Type_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C { " + oldType + " F, G; }";
var src2 = "class C { " + newType + " F, G; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Field_Type_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C { " + oldType + " F, G; }";
var src2 = "class C { " + newType + " F, G; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field),
Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("object", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Field_Event_Type_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C { event System.Action<" + oldType + "> F, G; }";
var src2 = "class C { event System.Action<" + newType + "> F, G; }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Field_Event_Type_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C { event System.Action<" + oldType + "> F, G; }";
var src2 = "class C { event System.Action<" + newType + "> F, G; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_),
Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_));
}
[Fact]
public void Field_Type_Update_ReorderRemoveAdd()
{
var src1 = "class C { int F, G, H; bool U; }";
var src2 = "class C { string G, F; double V, U; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int F, G, H]@10 -> [string G, F]@10",
"Reorder [G]@17 -> @17",
"Update [bool U]@23 -> [double V, U]@23",
"Insert [V]@30",
"Delete [H]@20");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "G", FeaturesResources.field),
Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field),
Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field),
Diagnostic(RudeEditKind.TypeUpdate, "double V, U", FeaturesResources.field),
Diagnostic(RudeEditKind.Delete, "string G, F", DeletedSymbolDisplay(FeaturesResources.field, "H")));
}
[Fact]
public void Field_Event_Reorder()
{
var src1 = "class C { int a = 0; int b = 1; event int c = 2; }";
var src2 = "class C { event int c = 2; int a = 0; int b = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [event int c = 2;]@32 -> @10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "event int c = 2", CSharpFeaturesResources.event_field));
}
[Fact]
public void Field_Event_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { event int E = 2; }";
var srcA2 = "partial class C { event int E = 2; }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
DocumentResults(),
});
}
#endregion
#region Properties
[Theory]
[InlineData("static")]
[InlineData("virtual")]
[InlineData("abstract")]
[InlineData("override")]
[InlineData("sealed override", "override")]
public void Property_Modifiers_Update(string oldModifiers, string newModifiers = "")
{
if (oldModifiers != "")
{
oldModifiers += " ";
}
if (newModifiers != "")
{
newModifiers += " ";
}
var src1 = "class C { " + oldModifiers + "int F => 0; }";
var src2 = "class C { " + newModifiers + "int F => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [" + oldModifiers + "int F => 0;]@10 -> [" + newModifiers + "int F => 0;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F", FeaturesResources.property_));
}
[Fact]
public void Property_ExpressionBody_Rename()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { int Q => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_));
}
[Fact]
public void Property_ExpressionBody_Update()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { int P => 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [int P => 1;]@10 -> [int P => 2;]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")]
public void Property_ExpressionBody_ModifierUpdate()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { unsafe int P => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [int P => 1;]@10 -> [unsafe int P => 1;]@10");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Property_ExpressionBodyToBlockBody1()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { int P { get { return 2; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P => 1;]@10 -> [int P { get { return 2; } }]@10",
"Insert [{ get { return 2; } }]@16",
"Insert [get { return 2; }]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false)
});
}
[Fact]
public void Property_ExpressionBodyToBlockBody2()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { int P { get { return 2; } set { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P => 1;]@10 -> [int P { get { return 2; } set { } }]@10",
"Insert [{ get { return 2; } set { } }]@16",
"Insert [get { return 2; }]@18",
"Insert [set { }]@36");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_P"), preserveLocalVariables: false)
});
}
[Fact]
public void Property_BlockBodyToExpressionBody1()
{
var src1 = "class C { int P { get { return 2; } } }";
var src2 = "class C { int P => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P { get { return 2; } }]@10 -> [int P => 1;]@10",
"Delete [{ get { return 2; } }]@16",
"Delete [get { return 2; }]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false)
});
}
[Fact]
public void Property_BlockBodyToExpressionBody2()
{
var src1 = "class C { int P { get { return 2; } set { } } }";
var src2 = "class C { int P => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P { get { return 2; } set { } }]@10 -> [int P => 1;]@10",
"Delete [{ get { return 2; } set { } }]@16",
"Delete [get { return 2; }]@18",
"Delete [set { }]@36");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set")));
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_ExpressionBodyToGetterExpressionBody()
{
var src1 = "class C { int P => 1; }";
var src2 = "class C { int P { get => 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P => 1;]@10 -> [int P { get => 2; }]@10",
"Insert [{ get => 2; }]@16",
"Insert [get => 2;]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_GetterExpressionBodyToExpressionBody()
{
var src1 = "class C { int P { get => 2; } }";
var src2 = "class C { int P => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P { get => 2; }]@10 -> [int P => 1;]@10",
"Delete [{ get => 2; }]@16",
"Delete [get => 2;]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_GetterBlockBodyToGetterExpressionBody()
{
var src1 = "class C { int P { get { return 2; } } }";
var src2 = "class C { int P { get => 2; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_SetterBlockBodyToSetterExpressionBody()
{
var src1 = "class C { int P { set { } } }";
var src2 = "class C { int P { set => F(); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [set { }]@18 -> [set => F();]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_InitBlockBodyToInitExpressionBody()
{
var src1 = "class C { int P { init { } } }";
var src2 = "class C { int P { init => F(); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [init { }]@18 -> [init => F();]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod, preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_GetterExpressionBodyToGetterBlockBody()
{
var src1 = "class C { int P { get => 2; } }";
var src2 = "class C { int P { get { return 2; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_GetterBlockBodyWithSetterToGetterExpressionBodyWithSetter()
{
var src1 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }";
var src2 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Property_GetterExpressionBodyWithSetterToGetterBlockBodyWithSetter()
{
var src1 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }";
var src2 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_P"), preserveLocalVariables: false)
});
}
[Fact]
public void Property_Rename1()
{
var src1 = "class C { int P { get { return 1; } } }";
var src2 = "class C { int Q { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_));
}
[Fact]
public void Property_Rename2()
{
var src1 = "class C { int I.P { get { return 1; } } }";
var src2 = "class C { int J.P { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "int J.P", FeaturesResources.property_));
}
[Fact]
public void Property_RenameAndUpdate()
{
var src1 = "class C { int P { get { return 1; } } }";
var src2 = "class C { int Q { get { return 2; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_));
}
[Fact]
public void PropertyDelete()
{
var src1 = "class C { int P { get { return 1; } } }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.property_, "P")));
}
[Fact]
public void PropertyReorder1()
{
var src1 = "class C { int P { get { return 1; } } int Q { get { return 1; } } }";
var src2 = "class C { int Q { get { return 1; } } int P { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int Q { get { return 1; } }]@38 -> @10");
// TODO: we can allow the move since the property doesn't have a backing field
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.property_));
}
[Fact]
public void PropertyReorder2()
{
var src1 = "class C { int P { get; set; } int Q { get; set; } }";
var src2 = "class C { int Q { get; set; } int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int Q { get; set; }]@30 -> @10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.auto_property));
}
[Fact]
public void PropertyAccessorReorder_GetSet()
{
var src1 = "class C { int P { get { return 1; } set { } } }";
var src2 = "class C { int P { set { } get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [set { }]@36 -> @18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyAccessorReorder_GetInit()
{
var src1 = "class C { int P { get { return 1; } init { } } }";
var src2 = "class C { int P { init { } get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [init { }]@36 -> @18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PropertyTypeUpdate()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { char P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P { get; set; }]@10 -> [char P { get; set; }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "char P", FeaturesResources.property_));
}
[Fact]
public void PropertyUpdate_AddAttribute()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { [System.Obsolete]int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int P", FeaturesResources.property_));
}
[Fact]
public void PropertyUpdate_AddAttribute_SupportedByRuntime()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { [System.Obsolete]int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void PropertyAccessorUpdate_AddAttribute()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { [System.Obsolete]get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "get", CSharpFeaturesResources.property_getter));
}
[Fact]
public void PropertyAccessorUpdate_AddAttribute2()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { get; [System.Obsolete]set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "set", CSharpFeaturesResources.property_setter));
}
[Fact]
public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { [System.Obsolete]get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime2()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { get; [System.Obsolete]set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void PropertyInsert()
{
var src1 = "class C { }";
var src2 = "class C { int P { get => 1; set { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("P")));
}
[Fact]
public void PropertyInsert_NotSupportedByRuntime()
{
var src1 = "class C { }";
var src2 = "class C { int P { get => 1; set { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "int P", FeaturesResources.auto_property));
}
[WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")]
[Fact]
public void PropertyInsert_PInvoke()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
class C
{
}";
var src2 = @"
using System;
using System.Runtime.InteropServices;
class C
{
private static extern int P1 { [DllImport(""x.dll"")]get; }
private static extern int P2 { [DllImport(""x.dll"")]set; }
private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; }
}
";
var edits = GetTopEdits(src1, src2);
// CLR doesn't support methods without a body
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertExtern, "private static extern int P1", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertExtern, "private static extern int P2", FeaturesResources.property_),
Diagnostic(RudeEditKind.InsertExtern, "private static extern int P3", FeaturesResources.property_));
}
[Fact]
public void PropertyInsert_IntoStruct()
{
var src1 = @"
struct S
{
public int a;
public S(int z) { a = z; }
}
";
var src2 = @"
struct S
{
public int a;
private static int c { get; set; }
private static int e { get { return 0; } set { } }
private static int g { get; } = 1;
private static int i { get; set; } = 1;
private static int k => 1;
public S(int z) { a = z; }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoStruct, "private static int c { get; set; }", FeaturesResources.auto_property, CSharpFeaturesResources.struct_),
Diagnostic(RudeEditKind.InsertIntoStruct, "private static int g { get; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_),
Diagnostic(RudeEditKind.InsertIntoStruct, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_));
}
[Fact]
public void PropertyInsert_IntoLayoutClass_Sequential()
{
var src1 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
private int a;
}
";
var src2 = @"
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
private int a;
private int b { get; set; }
private static int c { get; set; }
private int d { get { return 0; } set { } }
private static int e { get { return 0; } set { } }
private int f { get; } = 1;
private static int g { get; } = 1;
private int h { get; set; } = 1;
private static int i { get; set; } = 1;
private int j => 1;
private static int k => 1;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int b { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int c { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int f { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int g { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int h { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_),
Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_));
}
// Design: Adding private accessors should also be allowed since we now allow adding private methods
// and adding public properties and/or public accessors are not allowed.
[Fact]
public void PrivateProperty_AccessorAdd()
{
var src1 = "class C { int _p; int P { get { return 1; } } }";
var src2 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set { _p = value; }]@44");
edits.VerifyRudeDiagnostics();
}
[WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")]
[Fact]
public void PrivatePropertyAccessorDelete()
{
var src1 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }";
var src2 = "class C { int _p; int P { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [set { _p = value; }]@44");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set")));
}
[Fact]
public void PrivateAutoPropertyAccessorAdd1()
{
var src1 = "class C { int P { get; } }";
var src2 = "class C { int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set;]@23");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PrivateAutoPropertyAccessorAdd2()
{
var src1 = "class C { public int P { get; } }";
var src2 = "class C { public int P { get; private set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [private set;]@30");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PrivateAutoPropertyAccessorAdd4()
{
var src1 = "class C { public int P { get; } }";
var src2 = "class C { public int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set;]@30");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PrivateAutoPropertyAccessorAdd5()
{
var src1 = "class C { public int P { get; } }";
var src2 = "class C { public int P { get; internal set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [internal set;]@30");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PrivateAutoPropertyAccessorAdd6()
{
var src1 = "class C { int P { get; } = 1; }";
var src2 = "class C { int P { get; set; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set;]@23");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void PrivateAutoPropertyAccessorAdd_Init()
{
var src1 = "class C { int P { get; } = 1; }";
var src2 = "class C { int P { get; init; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [init;]@23");
edits.VerifyRudeDiagnostics();
}
[WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")]
[Fact]
public void PrivateAutoPropertyAccessorDelete_Get()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [get;]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_getter, "P.get")));
}
[Fact]
public void AutoPropertyAccessor_SetToInit()
{
var src1 = "class C { int P { get; set; } }";
var src2 = "class C { int P { get; init; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [set;]@23 -> [init;]@23");
// not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq)
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.AccessorKindUpdate, "init", CSharpFeaturesResources.property_setter));
}
[Fact]
public void AutoPropertyAccessor_InitToSet()
{
var src1 = "class C { int P { get; init; } }";
var src2 = "class C { int P { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [init;]@23 -> [set;]@23");
// not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq)
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter));
}
[Fact]
public void PrivateAutoPropertyAccessorDelete_Set()
{
var src1 = "class C { int P { get; set; } = 1; }";
var src2 = "class C { int P { get; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [set;]@23");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set")));
}
[Fact]
public void PrivateAutoPropertyAccessorDelete_Init()
{
var src1 = "class C { int P { get; init; } = 1; }";
var src2 = "class C { int P { get; } = 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [init;]@23");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.init")));
}
[Fact]
public void AutoPropertyAccessorUpdate()
{
var src1 = "class C { int P { get; } }";
var src2 = "class C { int P { set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get;]@18 -> [set;]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter));
}
[WorkItem(992578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992578")]
[Fact]
public void InsertIncompleteProperty()
{
var src1 = "class C { }";
var src2 = "class C { public int P { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [public int P { }]@10", "Insert [{ }]@23");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Property_ReadOnlyRef_Insert()
{
var src1 = "class Test { }";
var src2 = "class Test { ref readonly int P { get; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [ref readonly int P { get; }]@13",
"Insert [{ get; }]@32",
"Insert [get;]@34");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Property_ReadOnlyRef_Update()
{
var src1 = "class Test { int P { get; } }";
var src2 = "class Test { ref readonly int P { get; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int P { get; }]@13 -> [ref readonly int P { get; }]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int P", FeaturesResources.property_));
}
[Fact]
public void Property_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int P { get => 1; set { } } }";
var srcA2 = "partial class C { int P { get => 1; set { } } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod)
}),
DocumentResults(),
});
}
[Fact]
public void PropertyInit_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int Q { get => 1; init { } }}";
var srcA2 = "partial class C { int Q { get => 1; init { } }}";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod)
}),
DocumentResults(),
});
}
[Fact]
public void AutoProperty_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }";
var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }";
var srcB2 = "partial class C { }";
// Accessors need to be updated even though they do not have an explicit body.
// There is still a sequence point generated for them whose location needs to be updated.
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod),
}),
DocumentResults(),
});
}
[Fact]
public void AutoPropertyWithInitializer_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int P { get; set; } = 1; }";
var srcA2 = "partial class C { int P { get; set; } = 1; }";
var srcB2 = "partial class C { }";
// Accessors need to be updated even though they do not have an explicit body.
// There is still a sequence point generated for them whose location needs to be updated.
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true)
}),
DocumentResults(),
});
}
[Fact]
public void PropertyWithExpressionBody_Partial_InsertDeleteUpdate()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int P => 1; }";
var srcA2 = "partial class C { int P => 2; }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }),
DocumentResults(),
});
}
[Fact]
public void AutoProperty_ReadOnly_Add()
{
var src1 = @"
struct S
{
int P { get; }
}";
var src2 = @"
struct S
{
readonly int P { get; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Property_InMutableStruct_ReadOnly_Add()
{
var src1 = @"
struct S
{
int P1 { get => 1; }
int P2 { get => 1; set {}}
int P3 { get => 1; set {}}
int P4 { get => 1; set {}}
}";
var src2 = @"
struct S
{
readonly int P1 { get => 1; }
int P2 { readonly get => 1; set {}}
int P3 { get => 1; readonly set {}}
readonly int P4 { get => 1; set {}}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P1", CSharpFeaturesResources.property_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_setter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.property_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.property_setter));
}
[Fact]
public void Property_InReadOnlyStruct_ReadOnly_Add()
{
// indent to align accessor bodies and avoid updates caused by sequence point location changes
var src1 = @"
readonly struct S
{
int P1 { get => 1; }
int P2 { get => 1; set {}}
int P3 { get => 1; set {}}
int P4 { get => 1; set {}}
}";
var src2 = @"
readonly struct S
{
readonly int P1 { get => 1; }
int P2 { readonly get => 1; set {}}
int P3 { get => 1; readonly set {}}
readonly int P4 { get => 1; set {}}
}";
var edits = GetTopEdits(src1, src2);
// updates only for accessors whose modifiers were explicitly updated
edits.VerifySemantics(new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P3").SetMethod, preserveLocalVariables: false)
});
}
#endregion
#region Indexers
[Theory]
[InlineData("virtual")]
[InlineData("abstract")]
[InlineData("override")]
[InlineData("sealed override", "override")]
public void Indexer_Modifiers_Update(string oldModifiers, string newModifiers = "")
{
if (oldModifiers != "")
{
oldModifiers += " ";
}
if (newModifiers != "")
{
newModifiers += " ";
}
var src1 = "class C { " + oldModifiers + "int this[int a] => 0; }";
var src2 = "class C { " + newModifiers + "int this[int a] => 0; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [" + oldModifiers + "int this[int a] => 0;]@10 -> [" + newModifiers + "int this[int a] => 0;]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int this[int a]", FeaturesResources.indexer_));
}
[Fact]
public void Indexer_GetterUpdate()
{
var src1 = "class C { int this[int a] { get { return 1; } } }";
var src2 = "class C { int this[int a] { get { return 2; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [get { return 1; }]@28 -> [get { return 2; }]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact]
public void Indexer_SetterUpdate()
{
var src1 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value); } } }";
var src2 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value + 1); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [set { System.Console.WriteLine(value); }]@46 -> [set { System.Console.WriteLine(value + 1); }]@46");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false)
});
}
[Fact]
public void Indexer_InitUpdate()
{
var src1 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value); } } }";
var src2 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value + 1); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [init { System.Console.WriteLine(value); }]@46 -> [init { System.Console.WriteLine(value + 1); }]@46");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false)
});
}
[Fact]
public void IndexerWithExpressionBody_Update()
{
var src1 = "class C { int this[int a] => 1; }";
var src2 = "class C { int this[int a] => 2; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => 1;]@10 -> [int this[int a] => 2;]@10");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void IndexerWithExpressionBody_Update_LiftedParameter()
{
var src1 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => a + 1)() + 10;
}
";
var src2 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => 2)() + 11; // not capturing a anymore
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => new Func<int>(() => a + 1)() + 10;]@35 -> [int this[int a] => new Func<int>(() => 2)() + 11;]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a"));
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void IndexerWithExpressionBody_Update_LiftedParameter_2()
{
var src1 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => a + 1)();
}
";
var src2 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => 2)(); // not capturing a anymore
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => new Func<int>(() => a + 1)();]@35 -> [int this[int a] => new Func<int>(() => 2)();]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a"));
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void IndexerWithExpressionBody_Update_LiftedParameter_3()
{
var src1 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => { return a + 1; })();
}
";
var src2 = @"
using System;
class C
{
int this[int a] => new Func<int>(() => { return 2; })(); // not capturing a anymore
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => new Func<int>(() => { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(() => { return 2; })();]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a"));
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void IndexerWithExpressionBody_Update_LiftedParameter_4()
{
var src1 = @"
using System;
class C
{
int this[int a] => new Func<int>(delegate { return a + 1; })();
}
";
var src2 = @"
using System;
class C
{
int this[int a] => new Func<int>(delegate { return 2; })(); // not capturing a anymore
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => new Func<int>(delegate { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(delegate { return 2; })();]@35");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a"));
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_ExpressionBodyToBlockBody()
{
var src1 = "class C { int this[int a] => 1; }";
var src2 = "class C { int this[int a] { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } }]@10",
"Insert [{ get { return 1; } }]@26",
"Insert [get { return 1; }]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_BlockBodyToExpressionBody()
{
var src1 = "class C { int this[int a] { get { return 1; } } }";
var src2 = "class C { int this[int a] => 1; } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] { get { return 1; } }]@10 -> [int this[int a] => 1;]@10",
"Delete [{ get { return 1; } }]@26",
"Delete [get { return 1; }]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_GetterExpressionBodyToBlockBody()
{
var src1 = "class C { int this[int a] { get => 1; } }";
var src2 = "class C { int this[int a] { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_BlockBodyToGetterExpressionBody()
{
var src1 = "class C { int this[int a] { get { return 1; } } }";
var src2 = "class C { int this[int a] { get => 1; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28");
edits.VerifyRudeDiagnostics();
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_GetterExpressionBodyToExpressionBody()
{
var src1 = "class C { int this[int a] { get => 1; } }";
var src2 = "class C { int this[int a] => 1; } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] { get => 1; }]@10 -> [int this[int a] => 1;]@10",
"Delete [{ get => 1; }]@26",
"Delete [get => 1;]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_ExpressionBodyToGetterExpressionBody()
{
var src1 = "class C { int this[int a] => 1; }";
var src2 = "class C { int this[int a] { get => 1; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => 1;]@10 -> [int this[int a] { get => 1; }]@10",
"Insert [{ get => 1; }]@26",
"Insert [get => 1;]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_GetterBlockBodyToGetterExpressionBody()
{
var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }";
var src2 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_SetterBlockBodyToSetterExpressionBody()
{
var src1 = "class C { int this[int a] { set { } } void F() { } }";
var src2 = "class C { int this[int a] { set => F(); } void F() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [set { }]@28 -> [set => F();]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_InitBlockBodyToInitExpressionBody()
{
var src1 = "class C { int this[int a] { init { } } void F() { } }";
var src2 = "class C { int this[int a] { init => F(); } void F() { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [init { }]@28 -> [init => F();]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")),
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_GetterExpressionBodyToGetterBlockBody()
{
var src1 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }";
var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false)
});
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_GetterAndSetterBlockBodiesToExpressionBody()
{
var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }";
var src2 = "class C { int this[int a] => 1; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10 -> [int this[int a] => 1;]@10",
"Delete [{ get { return 1; } set { Console.WriteLine(0); } }]@26",
"Delete [get { return 1; }]@28",
"Delete [set { Console.WriteLine(0); }]@46");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set")));
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Indexer_ExpressionBodyToGetterAndSetterBlockBodies()
{
var src1 = "class C { int this[int a] => 1; }";
var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10",
"Insert [{ get { return 1; } set { Console.WriteLine(0); } }]@26",
"Insert [get { return 1; }]@28",
"Insert [set { Console.WriteLine(0); }]@46");
edits.VerifySemantics(ActiveStatementsDescription.Empty, new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_Item"), preserveLocalVariables: false)
});
}
[Fact]
public void Indexer_Rename()
{
var src1 = "class C { int I.this[int a] { get { return 1; } } }";
var src2 = "class C { int J.this[int a] { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "int J.this[int a]", CSharpFeaturesResources.indexer));
}
[Fact]
public void Indexer_Reorder1()
{
var src1 = "class C { int this[int a] { get { return 1; } } int this[string a] { get { return 1; } } }";
var src2 = "class C { int this[string a] { get { return 1; } } int this[int a] { get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int this[string a] { get { return 1; } }]@48 -> @10");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Indexer_AccessorReorder()
{
var src1 = "class C { int this[int a] { get { return 1; } set { } } }";
var src2 = "class C { int this[int a] { set { } get { return 1; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [set { }]@46 -> @28");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Indexer_TypeUpdate()
{
var src1 = "class C { int this[int a] { get; set; } }";
var src2 = "class C { string this[int a] { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int a] { get; set; }]@10 -> [string this[int a] { get; set; }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "string this[int a]", CSharpFeaturesResources.indexer));
}
[Fact]
public void Tuple_TypeUpdate()
{
var src1 = "class C { (int, int) M() { throw new System.Exception(); } }";
var src2 = "class C { (string, int) M() { throw new System.Exception(); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int, int) M() { throw new System.Exception(); }]@10 -> [(string, int) M() { throw new System.Exception(); }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "(string, int) M()", FeaturesResources.method));
}
[Fact]
public void TupleElementDelete()
{
var src1 = "class C { (int, int, int a) M() { return (1, 2, 3); } }";
var src2 = "class C { (int, int) M() { return (1, 2); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int, int, int a) M() { return (1, 2, 3); }]@10 -> [(int, int) M() { return (1, 2); }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "(int, int) M()", FeaturesResources.method));
}
[Fact]
public void TupleElementAdd()
{
var src1 = "class C { (int, int) M() { return (1, 2); } }";
var src2 = "class C { (int, int, int a) M() { return (1, 2, 3); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int, int) M() { return (1, 2); }]@10 -> [(int, int, int a) M() { return (1, 2, 3); }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "(int, int, int a) M()", FeaturesResources.method));
}
[Fact]
public void Indexer_ParameterUpdate()
{
var src1 = "class C { int this[int a] { get; set; } }";
var src2 = "class C { int this[string a] { get; set; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "string a", FeaturesResources.parameter));
}
[Fact]
public void Indexer_AddGetAccessor()
{
var src1 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
set { arr[i] = value; }
}
}";
var src2 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { return arr[i]; }
set { arr[i] = value; }
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [get { return arr[i]; }]@304");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InsertIntoGenericType, "get", CSharpFeaturesResources.indexer_getter));
}
[Fact]
public void Indexer_AddSetAccessor()
{
var src1 = @"
class C
{
public int this[int i] { get { return default; } }
}";
var src2 = @"
class C
{
public int this[int i] { get { return default; } set { } }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set { }]@67");
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod));
}
[Fact]
public void Indexer_AddSetAccessor_GenericType()
{
var src1 = @"
class C<T>
{
public T this[int i] { get { return default; } }
}";
var src2 = @"
class C<T>
{
public T this[int i] { get { return default; } set { } }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [set { }]@68");
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertIntoGenericType, "set", CSharpFeaturesResources.indexer_setter));
}
[WorkItem(750109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")]
[Fact]
public void Indexer_DeleteGetAccessor()
{
var src1 = @"
class C<T>
{
public T this[int i]
{
get { return arr[i]; }
set { arr[i] = value; }
}
}";
var src2 = @"
class C<T>
{
public T this[int i]
{
set { arr[i] = value; }
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [get { return arr[i]; }]@58");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "public T this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_getter, "this[int i].get")));
}
[Fact]
public void Indexer_DeleteSetAccessor()
{
var src1 = @"
class C
{
public int this[int i] { get { return 0; } set { } }
}";
var src2 = @"
class C
{
public int this[int i] { get { return 0; } }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [set { }]@61");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "public int this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int i].set")));
}
[Fact, WorkItem(1174850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174850")]
public void Indexer_Insert()
{
var src1 = "struct C { }";
var src2 = "struct C { public int this[int x, int y] { get { return x + y; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Indexer_ReadOnlyRef_Parameter_InsertWhole()
{
var src1 = "class Test { }";
var src2 = "class Test { int this[in int i] => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [int this[in int i] => throw null;]@13",
"Insert [[in int i]]@21",
"Insert [in int i]@22");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Indexer_ReadOnlyRef_Parameter_Update()
{
var src1 = "class Test { int this[int i] => throw null; }";
var src2 = "class Test { int this[in int i] => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int i]@22 -> [in int i]@22");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "in int i", FeaturesResources.parameter));
}
[Fact]
public void Indexer_ReadOnlyRef_ReturnType_Insert()
{
var src1 = "class Test { }";
var src2 = "class Test { ref readonly int this[int i] => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [ref readonly int this[int i] => throw null;]@13",
"Insert [[int i]]@34",
"Insert [int i]@35");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Indexer_ReadOnlyRef_ReturnType_Update()
{
var src1 = "class Test { int this[int i] => throw null; }";
var src2 = "class Test { ref readonly int this[int i] => throw null; }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int this[int i] => throw null;]@13 -> [ref readonly int this[int i] => throw null;]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int this[int i]", FeaturesResources.indexer_));
}
[Fact]
public void Indexer_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }";
var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)
}),
DocumentResults(),
});
}
[Fact]
public void IndexerInit_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}";
var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)
}),
DocumentResults(),
});
}
[Fact]
public void AutoIndexer_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { int this[int x] { get; set; } }";
var srcA2 = "partial class C { int this[int x] { get; set; } }";
var srcB2 = "partial class C { }";
// Accessors need to be updated even though they do not have an explicit body.
// There is still a sequence point generated for them whose location needs to be updated.
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod),
}),
DocumentResults(),
});
}
[Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")]
public void IndexerWithExpressionBody_Partial_InsertDeleteUpdate_LiftedParameter()
{
var srcA1 = @"
partial class C
{
}";
var srcB1 = @"
partial class C
{
int this[int a] => new System.Func<int>(() => a + 1);
}";
var srcA2 = @"
partial class C
{
int this[int a] => new System.Func<int>(() => 2); // no capture
}";
var srcB2 = @"
partial class C
{
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a") }),
DocumentResults(),
});
}
[Fact]
public void AutoIndexer_ReadOnly_Add()
{
var src1 = @"
struct S
{
int this[int x] { get; }
}";
var src2 = @"
struct S
{
readonly int this[int x] { get; }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter));
}
[Fact]
public void Indexer_InMutableStruct_ReadOnly_Add()
{
var src1 = @"
struct S
{
int this[int x] { get => 1; }
int this[uint x] { get => 1; set {}}
int this[byte x] { get => 1; set {}}
int this[sbyte x] { get => 1; set {}}
}";
var src2 = @"
struct S
{
readonly int this[int x] { get => 1; }
int this[uint x] { readonly get => 1; set {}}
int this[byte x] { get => 1; readonly set {}}
readonly int this[sbyte x] { get => 1; set {}}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_setter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.indexer_getter),
Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.indexer_setter));
}
[Fact]
public void Indexer_InReadOnlyStruct_ReadOnly_Add()
{
// indent to align accessor bodies and avoid updates caused by sequence point location changes
var src1 = @"
readonly struct S
{
int this[int x] { get => 1; }
int this[uint x] { get => 1; set {}}
int this[byte x] { get => 1; set {}}
int this[sbyte x] { get => 1; set {}}
}";
var src2 = @"
readonly struct S
{
readonly int this[int x] { get => 1; }
int this[uint x] { readonly get => 1; set {}}
int this[byte x] { get => 1; readonly set {}}
readonly int this[sbyte x] { get => 1; set {}}
}";
var edits = GetTopEdits(src1, src2);
// updates only for accessors whose modifiers were explicitly updated
edits.VerifySemantics(new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "UInt32").GetMethod, preserveLocalVariables: false),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false)
});
}
#endregion
#region Events
[Theory]
[InlineData("static")]
[InlineData("virtual")]
[InlineData("abstract")]
[InlineData("override")]
[InlineData("sealed override", "override")]
public void Event_Modifiers_Update(string oldModifiers, string newModifiers = "")
{
if (oldModifiers != "")
{
oldModifiers += " ";
}
if (newModifiers != "")
{
newModifiers += " ";
}
var src1 = "class C { " + oldModifiers + "event Action F { add {} remove {} } }";
var src2 = "class C { " + newModifiers + "event Action F { add {} remove {} } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [" + oldModifiers + "event Action F { add {} remove {} }]@10 -> [" + newModifiers + "event Action F { add {} remove {} }]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "event Action F", FeaturesResources.event_));
}
[Fact]
public void Event_Accessor_Reorder1()
{
var src1 = "class C { event int E { add { } remove { } } }";
var src2 = "class C { event int E { remove { } add { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [remove { }]@32 -> @24");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Event_Accessor_Reorder2()
{
var src1 = "class C { event int E1 { add { } remove { } } event int E1 { add { } remove { } } }";
var src2 = "class C { event int E2 { remove { } add { } } event int E2 { remove { } add { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [event int E1 { add { } remove { } }]@10 -> [event int E2 { remove { } add { } }]@10",
"Update [event int E1 { add { } remove { } }]@49 -> [event int E2 { remove { } add { } }]@49",
"Reorder [remove { }]@33 -> @25",
"Reorder [remove { }]@72 -> @64");
}
[Fact]
public void Event_Accessor_Reorder3()
{
var src1 = "class C { event int E1 { add { } remove { } } event int E2 { add { } remove { } } }";
var src2 = "class C { event int E2 { remove { } add { } } event int E1 { remove { } add { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [event int E2 { add { } remove { } }]@49 -> @10",
"Reorder [remove { }]@72 -> @25",
"Reorder [remove { }]@33 -> @64");
}
[Fact]
public void Event_Insert()
{
var src1 = "class C { }";
var src2 = "class C { event int E { remove { } add { } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("E")));
}
[Fact]
public void Event_Delete()
{
var src1 = "class C { event int E { remove { } add { } } }";
var src2 = "class C { }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.event_, "E")));
}
[Fact]
public void Event_Insert_IntoLayoutClass_Sequential()
{
var src1 = @"
using System;
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
}
";
var src2 = @"
using System;
using System.Runtime.InteropServices;
[StructLayoutAttribute(LayoutKind.Sequential)]
class C
{
private event Action c { add { } remove { } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Event_ExpressionBodyToBlockBody()
{
var src1 = @"
using System;
public class C
{
event Action E { add => F(); remove => F(); }
}
";
var src2 = @"
using System;
public class C
{
event Action E { add { F(); } remove { } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [add => F();]@57 -> [add { F(); }]@56",
"Update [remove => F();]@69 -> [remove { }]@69"
);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")]
public void Event_BlockBodyToExpressionBody()
{
var src1 = @"
using System;
public class C
{
event Action E { add { F(); } remove { } }
}
";
var src2 = @"
using System;
public class C
{
event Action E { add => F(); remove => F(); }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [add { F(); }]@56 -> [add => F();]@57",
"Update [remove { }]@69 -> [remove => F();]@69"
);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Event_Partial_InsertDelete()
{
var srcA1 = "partial class C { }";
var srcB1 = "partial class C { event int E { add { } remove { } } }";
var srcA2 = "partial class C { event int E { add { } remove { } } }";
var srcB2 = "partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod)
}),
DocumentResults(),
});
}
[Fact]
public void Event_InMutableStruct_ReadOnly_Add()
{
var src1 = @"
struct S
{
public event Action E { add {} remove {} }
}";
var src2 = @"
struct S
{
public readonly event Action E { add {} remove {} }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly event Action E", FeaturesResources.event_));
}
[Fact]
public void Event_InReadOnlyStruct_ReadOnly_Add1()
{
var src1 = @"
readonly struct S
{
public event Action E { add {} remove {} }
}";
var src2 = @"
readonly struct S
{
public readonly event Action E { add {} remove {} }
}";
var edits = GetTopEdits(src1, src2);
// Currently, an edit is produced eventhough bodies nor IsReadOnly attribute have changed. Consider improving.
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").AddMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").RemoveMethod));
}
[Fact]
public void Field_Event_Attribute_Add()
{
var src1 = @"
class C
{
event Action F;
}";
var src2 = @"
class C
{
[System.Obsolete]event Action F;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [event Action F;]@18 -> [[System.Obsolete]event Action F;]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Event_Attribute_Add()
{
var src1 = @"
class C
{
event Action F { add {} remove {} }
}";
var src2 = @"
class C
{
[System.Obsolete]event Action F { add {} remove {} }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [event Action F { add {} remove {} }]@18 -> [[System.Obsolete]event Action F { add {} remove {} }]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Event_Accessor_Attribute_Add()
{
var src1 = @"
class C
{
event Action F { add {} remove {} }
}";
var src2 = @"
class C
{
event Action F { add {} [System.Obsolete]remove {} }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [remove {}]@42 -> [[System.Obsolete]remove {}]@42");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Field_Event_Attribute_Delete()
{
var src1 = @"
class C
{
[System.Obsolete]event Action F;
}";
var src2 = @"
class C
{
event Action F;
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete]event Action F;]@18 -> [event Action F;]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F"))
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Event_Attribute_Delete()
{
var src1 = @"
class C
{
[System.Obsolete]event Action F { add {} remove {} }
}";
var src2 = @"
class C
{
event Action F { add {} remove {} }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete]event Action F { add {} remove {} }]@18 -> [event Action F { add {} remove {} }]@18");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod),
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Event_Accessor_Attribute_Delete()
{
var src1 = @"
class C
{
event Action F { add {} [System.Obsolete]remove {} }
}";
var src2 = @"
class C
{
event Action F { add {} remove {} }
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete]remove {}]@42 -> [remove {}]@42");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor));
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] {
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
#endregion
#region Parameter
[Fact]
public void ParameterRename_Method1()
{
var src1 = @"class C { public void M(int a) {} }";
var src2 = @"class C { public void M(int b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@24 -> [int b]@24");
}
[Fact]
public void ParameterRename_Ctor1()
{
var src1 = @"class C { public C(int a) {} }";
var src2 = @"class C { public C(int b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@19 -> [int b]@19");
}
[Fact]
public void ParameterRename_Operator1()
{
var src1 = @"class C { public static implicit operator int(C a) {} }";
var src2 = @"class C { public static implicit operator int(C b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [C a]@46 -> [C b]@46");
}
[Fact]
public void ParameterRename_Operator2()
{
var src1 = @"class C { public static int operator +(C a, C b) { return 0; } }";
var src2 = @"class C { public static int operator +(C a, C x) { return 0; } } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [C b]@44 -> [C x]@44");
}
[Fact]
public void ParameterRename_Indexer2()
{
var src1 = @"class C { public int this[int a, int b] { get { return 0; } } }";
var src2 = @"class C { public int this[int a, int x] { get { return 0; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int b]@33 -> [int x]@33");
}
[Fact]
public void ParameterInsert1()
{
var src1 = @"class C { public void M() {} }";
var src2 = @"class C { public void M(int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [int a]@24");
}
[Fact]
public void ParameterInsert2()
{
var src1 = @"class C { public void M(int a) {} }";
var src2 = @"class C { public void M(int a, ref int b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int a)]@23 -> [(int a, ref int b)]@23",
"Insert [ref int b]@31");
}
[Fact]
public void ParameterDelete1()
{
var src1 = @"class C { public void M(int a) {} }";
var src2 = @"class C { public void M() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [int a]@24");
}
[Fact]
public void ParameterDelete2()
{
var src1 = @"class C { public void M(int a, int b) {} }";
var src2 = @"class C { public void M(int b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int a, int b)]@23 -> [(int b)]@23",
"Delete [int a]@24");
}
[Fact]
public void ParameterUpdate()
{
var src1 = @"class C { public void M(int a) {} }";
var src2 = @"class C { public void M(int b) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@24 -> [int b]@24");
}
[Fact]
public void ParameterReorder()
{
var src1 = @"class C { public void M(int a, int b) {} }";
var src2 = @"class C { public void M(int b, int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int b]@31 -> @24");
}
[Fact]
public void ParameterReorderAndUpdate()
{
var src1 = @"class C { public void M(int a, int b) {} }";
var src2 = @"class C { public void M(int b, int c) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int b]@31 -> @24",
"Update [int a]@24 -> [int c]@31");
}
[Theory]
[InlineData("string", "string?")]
[InlineData("object", "dynamic")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void Parameter_Type_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
var src1 = "class C { static void M(" + oldType + " a) {} }";
var src2 = "class C { static void M(" + newType + " a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void Parameter_Type_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C { static void M(" + oldType + " a) {} }";
var src2 = "class C { static void M(" + newType + " a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.TypeUpdate, newType + " a", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Type_Nullable()
{
var src1 = @"
#nullable enable
class C { static void M(string a) { } }
";
var src2 = @"
#nullable disable
class C { static void M(string a) { } }
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics();
}
[Theory]
[InlineData("this")]
[InlineData("ref")]
[InlineData("out")]
[InlineData("params")]
public void Parameter_Modifier_Remove(string modifier)
{
var src1 = @"static class C { static void F(" + modifier + " int[] a) { } }";
var src2 = @"static class C { static void F(int[] a) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ModifiersUpdate, "int[] a", FeaturesResources.parameter));
}
[Theory]
[InlineData("int a = 1", "int a = 2")]
[InlineData("int a = 1", "int a")]
[InlineData("int a", "int a = 2")]
[InlineData("object a = null", "object a")]
[InlineData("object a", "object a = null")]
[InlineData("double a = double.NaN", "double a = 1.2")]
public void Parameter_Initializer_Update(string oldParameter, string newParameter)
{
var src1 = @"static class C { static void F(" + oldParameter + ") { } }";
var src2 = @"static class C { static void F(" + newParameter + ") { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.InitializerUpdate, newParameter, FeaturesResources.parameter));
}
[Fact]
public void Parameter_Initializer_NaN()
{
var src1 = @"static class C { static void F(double a = System.Double.NaN) { } }";
var src2 = @"static class C { static void F(double a = double.NaN) { } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void Parameter_Initializer_InsertDeleteUpdate()
{
var srcA1 = @"partial class C { }";
var srcB1 = @"partial class C { public static void F(int x = 1) {} }";
var srcA2 = @"partial class C { public static void F(int x = 2) {} }";
var srcB2 = @"partial class C { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(
diagnostics: new[]
{
Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter)
}),
DocumentResults(),
});
}
[Fact]
public void Parameter_Attribute_Insert()
{
var attribute = "public class A : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M(int a) {} }";
var src2 = attribute + @"class C { public void M([A]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@63 -> [[A]int a]@63");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute1()
{
var attribute = "public class AAttribute : System.Security.Permissions.SecurityAttribute { }\n\n";
var src1 = attribute + @"class C { public void M(int a) {} }";
var src2 = attribute + @"class C { public void M([A]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@101 -> [[A]int a]@101");
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.ChangingNonCustomAttribute, "int a", "AAttribute", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute2()
{
var attribute = "public class BAttribute : System.Security.Permissions.SecurityAttribute { }\n\n" +
"public class AAttribute : BAttribute { }\n\n";
var src1 = attribute + @"class C { public void M(int a) {} }";
var src2 = attribute + @"class C { public void M([A]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@143 -> [[A]int a]@143");
edits.VerifyRudeDiagnostics(
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.ChangingNonCustomAttribute, "int a", "AAttribute", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Insert_NotSupportedByRuntime1()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M(int a) {} }";
var src2 = attribute + @"class C { public void M([A]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@72 -> [[A]int a]@72");
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Insert_NotSupportedByRuntime2()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M([A]int a) {} }";
var src2 = attribute + @"class C { public void M([A, B]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]int a]@120 -> [[A, B]int a]@120");
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Delete_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M([A]int a) {} }";
var src2 = attribute + @"class C { public void M(int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]int a]@72 -> [int a]@72");
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Update_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M([System.Obsolete(""1""), B]int a) {} }";
var src2 = attribute + @"class C { public void M([System.Obsolete(""2""), A]int a) {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete(\"1\"), B]int a]@120 -> [[System.Obsolete(\"2\"), A]int a]@120");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter));
}
[Fact]
public void Parameter_Attribute_Update()
{
var attribute = "class A : System.Attribute { public A(int x) {} } ";
var src1 = attribute + "class C { void F([A(0)]int a) {} }";
var src2 = attribute + "class C { void F([A(1)]int a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A(0)]int a]@67 -> [[A(1)]int a]@67");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Parameter_Attribute_Update_WithBodyUpdate()
{
var attribute = "class A : System.Attribute { public A(int x) {} } ";
var src1 = attribute + "class C { void F([A(0)]int a) { F(0); } }";
var src2 = attribute + "class C { void F([A(1)]int a) { F(1); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void F([A(0)]int a) { F(0); }]@60 -> [void F([A(1)]int a) { F(1); }]@60",
"Update [[A(0)]int a]@67 -> [[A(1)]int a]@67");
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
#endregion
#region Method Type Parameter
[Fact]
public void MethodTypeParameterInsert1()
{
var src1 = @"class C { public void M() {} }";
var src2 = @"class C { public void M<A>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [<A>]@23",
"Insert [A]@24");
}
[Fact]
public void MethodTypeParameterInsert2()
{
var src1 = @"class C { public void M<A>() {} }";
var src2 = @"class C { public void M<A,B>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [<A>]@23 -> [<A,B>]@23",
"Insert [B]@26");
}
[Fact]
public void MethodTypeParameterDelete1()
{
var src1 = @"class C { public void M<A>() {} }";
var src2 = @"class C { public void M() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [<A>]@23",
"Delete [A]@24");
}
[Fact]
public void MethodTypeParameterDelete2()
{
var src1 = @"class C { public void M<A,B>() {} }";
var src2 = @"class C { public void M<B>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [<A,B>]@23 -> [<B>]@23",
"Delete [A]@24");
}
[Fact]
public void MethodTypeParameterUpdate()
{
var src1 = @"class C { public void M<A>() {} }";
var src2 = @"class C { public void M<B>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [A]@24 -> [B]@24");
}
[Fact]
public void MethodTypeParameterReorder()
{
var src1 = @"class C { public void M<A,B>() {} }";
var src2 = @"class C { public void M<B,A>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@26 -> @24");
}
[Fact]
public void MethodTypeParameterReorderAndUpdate()
{
var src1 = @"class C { public void M<A,B>() {} }";
var src2 = @"class C { public void M<B,C>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@26 -> @24",
"Update [A]@24 -> [C]@26");
}
[Fact]
public void MethodTypeParameter_Attribute_Insert1()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M<T>() {} }";
var src2 = attribute + @"class C { public void M<[A]T>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@72 -> [[A]T]@72");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"),
Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method));
}
[Fact]
public void MethodTypeParameter_Attribute_Insert2()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M<[A]T>() {} }";
var src2 = attribute + @"class C { public void M<[A, B]T>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]T]@120 -> [[A, B]T]@120");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"),
Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method));
}
[Fact]
public void MethodTypeParameter_Attribute_Delete()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M<[A]T>() {} }";
var src2 = attribute + @"class C { public void M<T>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]T]@72 -> [T]@72");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"));
}
[Fact]
public void MethodTypeParameter_Attribute_Update_NotSupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C { public void M<[System.Obsolete(""1""), B]T>() {} }";
var src2 = attribute + @"class C { public void M<[System.Obsolete(""2""), A]T>() {} } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete(\"1\"), B]T]@120 -> [[System.Obsolete(\"2\"), A]T]@120");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"));
}
[Fact]
public void MethodTypeParameter_Attribute_Update()
{
var attribute = "class A : System.Attribute { public A(int x) {} } ";
var src1 = attribute + "class C { void F<[A(0)]T>(T a) {} }";
var src2 = attribute + "class C { void F<[A(1)]T>(T a) {} }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A(0)]T]@67 -> [[A(1)]T]@67");
edits.VerifyRudeDiagnostics(
EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"));
}
[Fact]
public void MethodTypeParameter_Attribute_Update_WithBodyUpdate()
{
var attribute = "class A : System.Attribute { public A(int x) {} } ";
var src1 = attribute + "class C { void F<[A(0)]T>(T a) { F(0); } }";
var src2 = attribute + "class C { void F<[A(1)]T>(T a) { F(1); } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void F<[A(0)]T>(T a) { F(0); }]@60 -> [void F<[A(1)]T>(T a) { F(1); }]@60",
"Update [[A(0)]T]@67 -> [[A(1)]T]@67");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<[A(1)]T>(T a)"),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericMethodUpdate, "T"));
}
#endregion
#region Type Type Parameter
[Fact]
public void TypeTypeParameterInsert1()
{
var src1 = @"class C {}";
var src2 = @"class C<A> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [<A>]@7",
"Insert [A]@8");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "A", FeaturesResources.type_parameter));
}
[Fact]
public void TypeTypeParameterInsert2()
{
var src1 = @"class C<A> {}";
var src2 = @"class C<A,B> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [<A>]@7 -> [<A,B>]@7",
"Insert [B]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "B", FeaturesResources.type_parameter));
}
[Fact]
public void TypeTypeParameterDelete1()
{
var src1 = @"class C<A> { }";
var src2 = @"class C { } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [<A>]@7",
"Delete [A]@8");
}
[Fact]
public void TypeTypeParameterDelete2()
{
var src1 = @"class C<A,B> {}";
var src2 = @"class C<B> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [<A,B>]@7 -> [<B>]@7",
"Delete [A]@8");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C<B>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "A")));
}
[Fact]
public void TypeTypeParameterUpdate()
{
var src1 = @"class C<A> {}";
var src2 = @"class C<B> {} ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [A]@8 -> [B]@8");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Renamed, "B", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "B"));
}
[Fact]
public void TypeTypeParameterReorder()
{
var src1 = @"class C<A,B> { }";
var src2 = @"class C<B,A> { } ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@10 -> @8");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter));
}
[Fact]
public void TypeTypeParameterReorderAndUpdate()
{
var src1 = @"class C<A,B> {}";
var src2 = @"class C<B,C> {} ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@10 -> @8",
"Update [A]@8 -> [C]@10");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.Renamed, "C", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "C"));
}
[Fact]
public void TypeTypeParameterAttributeInsert1()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C<T> {}";
var src2 = attribute + @"class C<[A]T> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@56 -> [[A]T]@56");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void TypeTypeParameterAttributeInsert2()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C<[A]T> {}";
var src2 = attribute + @"class C<[A, B]T> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]T]@104 -> [[A, B]T]@104");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void TypeTypeParameterAttributeInsert_SupportedByRuntime()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C<T> {}";
var src2 = attribute + @"class C<[A]T> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@56 -> [[A]T]@56");
edits.VerifyRudeDiagnostics(
EditAndContinueTestHelpers.Net6RuntimeCapabilities,
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void TypeTypeParameterAttributeDelete()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C<[A]T> {}";
var src2 = attribute + @"class C<T> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]T]@56 -> [T]@56");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void TypeTypeParameterAttributeUpdate()
{
var attribute = "public class AAttribute : System.Attribute { }\n\n" +
"public class BAttribute : System.Attribute { }\n\n";
var src1 = attribute + @"class C<[System.Obsolete(""1""), B]T> {}";
var src2 = attribute + @"class C<[System.Obsolete(""2""), A]T> {} ";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [[System.Obsolete(\"1\"), B]T]@104 -> [[System.Obsolete(\"2\"), A]T]@104");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Fact]
public void TypeTypeParameter_Partial_Attribute_AddMultiple()
{
var attributes = @"
class A : System.Attribute {}
class B : System.Attribute {}
";
var srcA1 = "partial class C<T> { }" + attributes;
var srcB1 = "partial class C<T> { }";
var srcA2 = "partial class C<[A]T> { }" + attributes;
var srcB2 = "partial class C<[B]T> { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"),
}),
DocumentResults(diagnostics: new[]
{
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"),
}),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable()
{
var attributes = @"
class A : System.Attribute {}
class B : System.Attribute {}
";
var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<T> { }" + attributes;
var srcB1 = "partial class C<T> { }";
var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes;
var srcB2 = "partial class C<[B]T> { }";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")
}),
DocumentResults(semanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C")
}),
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
#endregion
#region Type Parameter Constraints
[Theory]
[InlineData("nonnull")]
[InlineData("struct")]
[InlineData("class")]
[InlineData("new()")]
[InlineData("unmanaged")]
[InlineData("System.IDisposable")]
[InlineData("System.Delegate")]
public void TypeConstraint_Insert(string newConstraint)
{
var src1 = "class C<S,T> { }";
var src2 = "class C<S,T> where T : " + newConstraint + " { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [where T : " + newConstraint + "]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingConstraints, "where T : " + newConstraint, FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : " + newConstraint));
}
[Theory]
[InlineData("nonnull")]
[InlineData("struct")]
[InlineData("class")]
[InlineData("new()")]
[InlineData("unmanaged")]
[InlineData("System.IDisposable")]
[InlineData("System.Delegate")]
public void TypeConstraint_Delete(string oldConstraint)
{
var src1 = "class C<S,T> where T : " + oldConstraint + " { }";
var src2 = "class C<S,T> { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [where T : " + oldConstraint + "]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingConstraints, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "T"));
}
[Theory]
[InlineData("string", "string?")]
[InlineData("(int a, int b)", "(int a, int c)")]
public void TypeConstraint_Update_RuntimeTypeUnchanged(string oldType, string newType)
{
// note: dynamic is not allowed in constraints
var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}";
var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">"));
}
[Theory]
[InlineData("int", "string")]
[InlineData("int", "int?")]
[InlineData("(int a, int b)", "(int a, double b)")]
public void TypeConstraint_Update_RuntimeTypeChanged(string oldType, string newType)
{
var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}";
var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingConstraints, "where T : System.Collections.Generic.List<" + newType + ">", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">"));
}
[Fact]
public void TypeConstraint_Delete_WithParameter()
{
var src1 = "class C<S,T> where S : new() where T : class { }";
var src2 = "class C<S> where S : new() { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "class C<S>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T")));
}
[Fact]
public void TypeConstraint_MultipleClauses_Insert()
{
var src1 = "class C<S,T> where T : class { }";
var src2 = "class C<S,T> where S : unmanaged where T : class { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Insert [where S : unmanaged]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingConstraints, "where S : unmanaged", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : unmanaged"));
}
[Fact]
public void TypeConstraint_MultipleClauses_Delete()
{
var src1 = "class C<S,T> where S : new() where T : class { }";
var src2 = "class C<S,T> where T : class { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Delete [where S : new()]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingConstraints, "S", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "S"));
}
[Fact]
public void TypeConstraint_MultipleClauses_Reorder()
{
var src1 = "class C<S,T> where S : struct where T : class { }";
var src2 = "class C<S,T> where T : class where S : struct { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [where T : class]@30 -> @13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void TypeConstraint_MultipleClauses_UpdateAndReorder()
{
var src1 = "class C<S,T> where S : new() where T : class { }";
var src2 = "class C<T,S> where T : class, I where S : class, new() { }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Reorder [where T : class]@29 -> @13",
"Reorder [T]@10 -> @8",
"Update [where T : class]@29 -> [where T : class, I]@13",
"Update [where S : new()]@13 -> [where S : class, new()]@32");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "T", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.ChangingConstraints, "where T : class, I", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : class, I"),
Diagnostic(RudeEditKind.ChangingConstraints, "where S : class, new()", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : class, new()"));
}
#endregion
#region Top Level Statements
[Fact]
public void TopLevelStatements_Update()
{
var src1 = @"
using System;
Console.WriteLine(""Hello"");
";
var src2 = @"
using System;
Console.WriteLine(""Hello World"");
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19");
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_InsertAndUpdate()
{
var src1 = @"
using System;
Console.WriteLine(""Hello"");
";
var src2 = @"
using System;
Console.WriteLine(""Hello World"");
Console.WriteLine(""What is your name?"");
var name = Console.ReadLine();
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19",
"Insert [Console.WriteLine(\"What is your name?\");]@54",
"Insert [var name = Console.ReadLine();]@96");
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_Insert_NoImplicitMain()
{
var src1 = @"
using System;
";
var src2 = @"
using System;
Console.WriteLine(""Hello World"");
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19");
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_Insert_ImplicitMain()
{
var src1 = @"
using System;
Console.WriteLine(""Hello"");
";
var src2 = @"
using System;
Console.WriteLine(""Hello"");
Console.WriteLine(""World"");
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48");
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_Delete_NoImplicitMain()
{
var src1 = @"
using System;
Console.WriteLine(""Hello World"");
";
var src2 = @"
using System;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19");
edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.global_statement));
}
[Fact]
public void TopLevelStatements_Delete_ImplicitMain()
{
var src1 = @"
using System;
Console.WriteLine(""Hello"");
Console.WriteLine(""World"");
";
var src2 = @"
using System;
Console.WriteLine(""Hello"");
";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48");
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_StackAlloc()
{
var src1 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(1); }";
var src2 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(2); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", CSharpFeaturesResources.global_statement));
}
[Fact]
public void TopLevelStatements_VoidToInt1()
{
var src1 = @"
using System;
Console.Write(1);
";
var src2 = @"
using System;
Console.Write(1);
return 1;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;"));
}
[Fact]
public void TopLevelStatements_VoidToInt2()
{
var src1 = @"
using System;
Console.Write(1);
return;
";
var src2 = @"
using System;
Console.Write(1);
return 1;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;"));
}
[Fact]
public void TopLevelStatements_VoidToInt3()
{
var src1 = @"
using System;
Console.Write(1);
int Goo()
{
return 1;
}
";
var src2 = @"
using System;
Console.Write(1);
return 1;
int Goo()
{
return 1;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;"));
}
[Fact]
public void TopLevelStatements_AddAwait()
{
var src1 = @"
using System.Threading.Tasks;
await Task.Delay(100);
";
var src2 = @"
using System.Threading.Tasks;
await Task.Delay(100);
await Task.Delay(200);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression));
}
[Fact]
public void TopLevelStatements_DeleteAwait()
{
var src1 = @"
using System.Threading.Tasks;
await Task.Delay(100);
await Task.Delay(200);
";
var src2 = @"
using System.Threading.Tasks;
await Task.Delay(100);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression));
}
[Fact]
public void TopLevelStatements_VoidToTask()
{
var src1 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
";
var src2 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "await Task.Delay(100);"));
}
[Fact]
public void TopLevelStatements_TaskToTaskInt()
{
var src1 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
";
var src2 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
return 1;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;"));
}
[Fact]
public void TopLevelStatements_VoidToTaskInt()
{
var src1 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
";
var src2 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
return await GetInt();
Task<int> GetInt()
{
return Task.FromResult(1);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return await GetInt();"));
}
[Fact]
public void TopLevelStatements_IntToVoid1()
{
var src1 = @"
using System;
Console.Write(1);
return 1;
";
var src2 = @"
using System;
Console.Write(1);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"));
}
[Fact]
public void TopLevelStatements_IntToVoid2()
{
var src1 = @"
using System;
Console.Write(1);
return 1;
";
var src2 = @"
using System;
Console.Write(1);
return;
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return;"));
}
[Fact]
public void TopLevelStatements_IntToVoid3()
{
var src1 = @"
using System;
Console.Write(1);
return 1;
int Goo()
{
return 1;
}
";
var src2 = @"
using System;
Console.Write(1);
int Goo()
{
return 1;
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "int Goo()\r\n{\r\n return 1;\r\n}"));
}
[Fact]
public void TopLevelStatements_IntToVoid4()
{
var src1 = @"
using System;
Console.Write(1);
return 1;
public class C
{
public int Goo()
{
return 1;
}
}
";
var src2 = @"
using System;
Console.Write(1);
public class C
{
public int Goo()
{
return 1;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"));
}
[Fact]
public void TopLevelStatements_TaskToVoid()
{
var src1 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
";
var src2 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"),
Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression));
}
[Fact]
public void TopLevelStatements_TaskIntToTask()
{
var src1 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
return 1;
";
var src2 = @"
using System;
using System.Threading.Tasks;
await Task.Delay(100);
Console.Write(1);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"));
}
[Fact]
public void TopLevelStatements_TaskIntToVoid()
{
var src1 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
return await GetInt();
Task<int> GetInt()
{
return Task.FromResult(1);
}
";
var src2 = @"
using System;
using System.Threading.Tasks;
Console.Write(1);
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"),
Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression));
}
[Fact]
public void TopLevelStatements_WithLambda_Insert()
{
var src1 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
";
var src2 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
Console.WriteLine(1);
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) });
}
[Fact]
public void TopLevelStatements_WithLambda_Update()
{
var src1 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
Console.WriteLine(1);
public class C { }
";
var src2 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
Console.WriteLine(2);
public class C { }
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) });
}
[Fact]
public void TopLevelStatements_WithLambda_Delete()
{
var src1 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
Console.WriteLine(1);
public class C { }
";
var src2 = @"
using System;
Func<int> a = () => { <N:0.0>return 1;</N:0.0> };
Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> };
public class C { }
";
var edits = GetTopEdits(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) });
}
[Fact]
public void TopLevelStatements_UpdateMultiple()
{
var src1 = @"
using System;
Console.WriteLine(1);
Console.WriteLine(2);
public class C { }
";
var src2 = @"
using System;
Console.WriteLine(3);
Console.WriteLine(4);
public class C { }
";
var edits = GetTopEdits(src1, src2);
// Since each individual statement is a separate update to a separate node, this just validates we correctly
// only analyze the things once
edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")));
}
[Fact]
public void TopLevelStatements_MoveToOtherFile()
{
var srcA1 = @"
using System;
Console.WriteLine(1);
public class A
{
}";
var srcB1 = @"
using System;
public class B
{
}";
var srcA2 = @"
using System;
public class A
{
}";
var srcB2 = @"
using System;
Console.WriteLine(2);
public class B
{
}";
EditAndContinueValidation.VerifySemantics(
new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) },
new[]
{
DocumentResults(),
DocumentResults(semanticEdits: new [] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")) }),
});
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Features/Core/Portable/Diagnostics/AbstractHostDiagnosticUpdateSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Diagnostic update source for reporting workspace host specific diagnostics,
/// which may not be related to any given project/document in the solution.
/// For example, these include diagnostics generated for exceptions from third party analyzers.
/// </summary>
internal abstract class AbstractHostDiagnosticUpdateSource : IDiagnosticUpdateSource
{
private ImmutableDictionary<DiagnosticAnalyzer, ImmutableHashSet<DiagnosticData>> _analyzerHostDiagnosticsMap =
ImmutableDictionary<DiagnosticAnalyzer, ImmutableHashSet<DiagnosticData>>.Empty;
public abstract Workspace Workspace { get; }
public bool SupportGetDiagnostics => false;
public ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken)
=> new(ImmutableArray<DiagnosticData>.Empty);
public event EventHandler<DiagnosticsUpdatedArgs>? DiagnosticsUpdated;
public event EventHandler DiagnosticsCleared { add { } remove { } }
public void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs args)
=> DiagnosticsUpdated?.Invoke(this, args);
public void ReportAnalyzerDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, ProjectId? projectId)
{
// check whether we are reporting project specific diagnostic or workspace wide diagnostic
var project = (projectId != null) ? Workspace.CurrentSolution.GetProject(projectId) : null;
// check whether project the diagnostic belong to still exist
if (projectId != null && project == null)
{
// project the diagnostic belong to already removed from the solution.
// ignore the diagnostic
return;
}
var diagnosticData = (project != null) ?
DiagnosticData.Create(diagnostic, project) :
DiagnosticData.Create(diagnostic, Workspace.Options);
ReportAnalyzerDiagnostic(analyzer, diagnosticData, project);
}
public void ReportAnalyzerDiagnostic(DiagnosticAnalyzer analyzer, DiagnosticData diagnosticData, Project? project)
{
var raiseDiagnosticsUpdated = true;
var dxs = ImmutableInterlocked.AddOrUpdate(ref _analyzerHostDiagnosticsMap,
analyzer,
ImmutableHashSet.Create(diagnosticData),
(a, existing) =>
{
var newDiags = existing.Add(diagnosticData);
raiseDiagnosticsUpdated = newDiags.Count > existing.Count;
return newDiags;
});
if (raiseDiagnosticsUpdated)
{
RaiseDiagnosticsUpdated(MakeCreatedArgs(analyzer, dxs, project));
}
}
public void ClearAnalyzerReferenceDiagnostics(AnalyzerFileReference analyzerReference, string language, ProjectId projectId)
{
var analyzers = analyzerReference.GetAnalyzers(language);
ClearAnalyzerDiagnostics(analyzers, projectId);
}
public void ClearAnalyzerDiagnostics(ImmutableArray<DiagnosticAnalyzer> analyzers, ProjectId projectId)
{
foreach (var analyzer in analyzers)
{
ClearAnalyzerDiagnostics(analyzer, projectId);
}
}
public void ClearAnalyzerDiagnostics(ProjectId projectId)
{
foreach (var (analyzer, _) in _analyzerHostDiagnosticsMap)
{
ClearAnalyzerDiagnostics(analyzer, projectId);
}
}
private void ClearAnalyzerDiagnostics(DiagnosticAnalyzer analyzer, ProjectId projectId)
{
if (!_analyzerHostDiagnosticsMap.TryGetValue(analyzer, out var existing))
{
return;
}
// Check if analyzer is shared by analyzer references from different projects.
var sharedAnalyzer = existing.Contains(d => d.ProjectId != null && d.ProjectId != projectId);
if (sharedAnalyzer)
{
var newDiags = existing.Where(d => d.ProjectId != projectId).ToImmutableHashSet();
if (newDiags.Count < existing.Count &&
ImmutableInterlocked.TryUpdate(ref _analyzerHostDiagnosticsMap, analyzer, newDiags, existing))
{
var project = Workspace.CurrentSolution.GetProject(projectId);
RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project));
}
}
else if (ImmutableInterlocked.TryRemove(ref _analyzerHostDiagnosticsMap, analyzer, out existing))
{
var project = Workspace.CurrentSolution.GetProject(projectId);
RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project));
if (existing.Any(d => d.ProjectId == null))
{
RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project: null));
}
}
}
private DiagnosticsUpdatedArgs MakeCreatedArgs(DiagnosticAnalyzer analyzer, ImmutableHashSet<DiagnosticData> items, Project? project)
{
return DiagnosticsUpdatedArgs.DiagnosticsCreated(
CreateId(analyzer, project), Workspace, project?.Solution, project?.Id, documentId: null, diagnostics: items.ToImmutableArray());
}
private DiagnosticsUpdatedArgs MakeRemovedArgs(DiagnosticAnalyzer analyzer, Project? project)
{
return DiagnosticsUpdatedArgs.DiagnosticsRemoved(
CreateId(analyzer, project), Workspace, project?.Solution, project?.Id, documentId: null);
}
private HostArgsId CreateId(DiagnosticAnalyzer analyzer, Project? project) => new(this, analyzer, project?.Id);
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly AbstractHostDiagnosticUpdateSource _abstractHostDiagnosticUpdateSource;
public TestAccessor(AbstractHostDiagnosticUpdateSource abstractHostDiagnosticUpdateSource)
=> _abstractHostDiagnosticUpdateSource = abstractHostDiagnosticUpdateSource;
internal ImmutableArray<DiagnosticData> GetReportedDiagnostics()
=> _abstractHostDiagnosticUpdateSource._analyzerHostDiagnosticsMap.Values.Flatten().ToImmutableArray();
internal ImmutableHashSet<DiagnosticData> GetReportedDiagnostics(DiagnosticAnalyzer analyzer)
{
if (!_abstractHostDiagnosticUpdateSource._analyzerHostDiagnosticsMap.TryGetValue(analyzer, out var diagnostics))
{
diagnostics = ImmutableHashSet<DiagnosticData>.Empty;
}
return diagnostics;
}
}
private sealed class HostArgsId : AnalyzerUpdateArgsId
{
private readonly AbstractHostDiagnosticUpdateSource _source;
private readonly ProjectId? _projectId;
public HostArgsId(AbstractHostDiagnosticUpdateSource source, DiagnosticAnalyzer analyzer, ProjectId? projectId) : base(analyzer)
{
_source = source;
_projectId = projectId;
}
public override bool Equals(object? obj)
{
if (obj is not HostArgsId other)
{
return false;
}
return _source == other._source && _projectId == other._projectId && base.Equals(obj);
}
public override int GetHashCode()
=> Hash.Combine(_source.GetHashCode(), Hash.Combine(_projectId == null ? 1 : _projectId.GetHashCode(), base.GetHashCode()));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Diagnostic update source for reporting workspace host specific diagnostics,
/// which may not be related to any given project/document in the solution.
/// For example, these include diagnostics generated for exceptions from third party analyzers.
/// </summary>
internal abstract class AbstractHostDiagnosticUpdateSource : IDiagnosticUpdateSource
{
private ImmutableDictionary<DiagnosticAnalyzer, ImmutableHashSet<DiagnosticData>> _analyzerHostDiagnosticsMap =
ImmutableDictionary<DiagnosticAnalyzer, ImmutableHashSet<DiagnosticData>>.Empty;
public abstract Workspace Workspace { get; }
public bool SupportGetDiagnostics => false;
public ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken)
=> new(ImmutableArray<DiagnosticData>.Empty);
public event EventHandler<DiagnosticsUpdatedArgs>? DiagnosticsUpdated;
public event EventHandler DiagnosticsCleared { add { } remove { } }
public void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs args)
=> DiagnosticsUpdated?.Invoke(this, args);
public void ReportAnalyzerDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, ProjectId? projectId)
{
// check whether we are reporting project specific diagnostic or workspace wide diagnostic
var project = (projectId != null) ? Workspace.CurrentSolution.GetProject(projectId) : null;
// check whether project the diagnostic belong to still exist
if (projectId != null && project == null)
{
// project the diagnostic belong to already removed from the solution.
// ignore the diagnostic
return;
}
var diagnosticData = (project != null) ?
DiagnosticData.Create(diagnostic, project) :
DiagnosticData.Create(diagnostic, Workspace.Options);
ReportAnalyzerDiagnostic(analyzer, diagnosticData, project);
}
public void ReportAnalyzerDiagnostic(DiagnosticAnalyzer analyzer, DiagnosticData diagnosticData, Project? project)
{
var raiseDiagnosticsUpdated = true;
var dxs = ImmutableInterlocked.AddOrUpdate(ref _analyzerHostDiagnosticsMap,
analyzer,
ImmutableHashSet.Create(diagnosticData),
(a, existing) =>
{
var newDiags = existing.Add(diagnosticData);
raiseDiagnosticsUpdated = newDiags.Count > existing.Count;
return newDiags;
});
if (raiseDiagnosticsUpdated)
{
RaiseDiagnosticsUpdated(MakeCreatedArgs(analyzer, dxs, project));
}
}
public void ClearAnalyzerReferenceDiagnostics(AnalyzerFileReference analyzerReference, string language, ProjectId projectId)
{
var analyzers = analyzerReference.GetAnalyzers(language);
ClearAnalyzerDiagnostics(analyzers, projectId);
}
public void ClearAnalyzerDiagnostics(ImmutableArray<DiagnosticAnalyzer> analyzers, ProjectId projectId)
{
foreach (var analyzer in analyzers)
{
ClearAnalyzerDiagnostics(analyzer, projectId);
}
}
public void ClearAnalyzerDiagnostics(ProjectId projectId)
{
foreach (var (analyzer, _) in _analyzerHostDiagnosticsMap)
{
ClearAnalyzerDiagnostics(analyzer, projectId);
}
}
private void ClearAnalyzerDiagnostics(DiagnosticAnalyzer analyzer, ProjectId projectId)
{
if (!_analyzerHostDiagnosticsMap.TryGetValue(analyzer, out var existing))
{
return;
}
// Check if analyzer is shared by analyzer references from different projects.
var sharedAnalyzer = existing.Contains(d => d.ProjectId != null && d.ProjectId != projectId);
if (sharedAnalyzer)
{
var newDiags = existing.Where(d => d.ProjectId != projectId).ToImmutableHashSet();
if (newDiags.Count < existing.Count &&
ImmutableInterlocked.TryUpdate(ref _analyzerHostDiagnosticsMap, analyzer, newDiags, existing))
{
var project = Workspace.CurrentSolution.GetProject(projectId);
RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project));
}
}
else if (ImmutableInterlocked.TryRemove(ref _analyzerHostDiagnosticsMap, analyzer, out existing))
{
var project = Workspace.CurrentSolution.GetProject(projectId);
RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project));
if (existing.Any(d => d.ProjectId == null))
{
RaiseDiagnosticsUpdated(MakeRemovedArgs(analyzer, project: null));
}
}
}
private DiagnosticsUpdatedArgs MakeCreatedArgs(DiagnosticAnalyzer analyzer, ImmutableHashSet<DiagnosticData> items, Project? project)
{
return DiagnosticsUpdatedArgs.DiagnosticsCreated(
CreateId(analyzer, project), Workspace, project?.Solution, project?.Id, documentId: null, diagnostics: items.ToImmutableArray());
}
private DiagnosticsUpdatedArgs MakeRemovedArgs(DiagnosticAnalyzer analyzer, Project? project)
{
return DiagnosticsUpdatedArgs.DiagnosticsRemoved(
CreateId(analyzer, project), Workspace, project?.Solution, project?.Id, documentId: null);
}
private HostArgsId CreateId(DiagnosticAnalyzer analyzer, Project? project) => new(this, analyzer, project?.Id);
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly AbstractHostDiagnosticUpdateSource _abstractHostDiagnosticUpdateSource;
public TestAccessor(AbstractHostDiagnosticUpdateSource abstractHostDiagnosticUpdateSource)
=> _abstractHostDiagnosticUpdateSource = abstractHostDiagnosticUpdateSource;
internal ImmutableArray<DiagnosticData> GetReportedDiagnostics()
=> _abstractHostDiagnosticUpdateSource._analyzerHostDiagnosticsMap.Values.Flatten().ToImmutableArray();
internal ImmutableHashSet<DiagnosticData> GetReportedDiagnostics(DiagnosticAnalyzer analyzer)
{
if (!_abstractHostDiagnosticUpdateSource._analyzerHostDiagnosticsMap.TryGetValue(analyzer, out var diagnostics))
{
diagnostics = ImmutableHashSet<DiagnosticData>.Empty;
}
return diagnostics;
}
}
private sealed class HostArgsId : AnalyzerUpdateArgsId
{
private readonly AbstractHostDiagnosticUpdateSource _source;
private readonly ProjectId? _projectId;
public HostArgsId(AbstractHostDiagnosticUpdateSource source, DiagnosticAnalyzer analyzer, ProjectId? projectId) : base(analyzer)
{
_source = source;
_projectId = projectId;
}
public override bool Equals(object? obj)
{
if (obj is not HostArgsId other)
{
return false;
}
return _source == other._source && _projectId == other._projectId && base.Equals(obj);
}
public override int GetHashCode()
=> Hash.Combine(_source.GetHashCode(), Hash.Combine(_projectId == null ? 1 : _projectId.GetHashCode(), base.GetHashCode()));
}
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/EditorFeatures/Core/Options/ColorSchemeOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Editor.ColorSchemes;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.Options
{
internal static class ColorSchemeOptions
{
internal const string ColorSchemeSettingKey = "TextEditor.Roslyn.ColorScheme";
public static readonly Option2<SchemeName> ColorScheme = new(nameof(ColorSchemeOptions),
nameof(ColorScheme),
defaultValue: SchemeName.VisualStudio2019,
storageLocation: new RoamingProfileStorageLocation(ColorSchemeSettingKey));
public static readonly Option2<UseEnhancedColors> LegacyUseEnhancedColors = new(nameof(ColorSchemeOptions),
nameof(LegacyUseEnhancedColors),
defaultValue: UseEnhancedColors.Default,
storageLocation: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages"));
public enum UseEnhancedColors
{
Migrated = -2,
DoNotUse = -1,
Default = 0,
Use = 1
}
}
[ExportOptionProvider, Shared]
internal class ColorSchemeOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ColorSchemeOptionsProvider()
{
}
public ImmutableArray<IOption> Options => ImmutableArray.Create<IOption>(
ColorSchemeOptions.ColorScheme,
ColorSchemeOptions.LegacyUseEnhancedColors);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Editor.ColorSchemes;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.Options
{
internal static class ColorSchemeOptions
{
internal const string ColorSchemeSettingKey = "TextEditor.Roslyn.ColorScheme";
public static readonly Option2<SchemeName> ColorScheme = new(nameof(ColorSchemeOptions),
nameof(ColorScheme),
defaultValue: SchemeName.VisualStudio2019,
storageLocation: new RoamingProfileStorageLocation(ColorSchemeSettingKey));
public static readonly Option2<UseEnhancedColors> LegacyUseEnhancedColors = new(nameof(ColorSchemeOptions),
nameof(LegacyUseEnhancedColors),
defaultValue: UseEnhancedColors.Default,
storageLocation: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages"));
public enum UseEnhancedColors
{
Migrated = -2,
DoNotUse = -1,
Default = 0,
Use = 1
}
}
[ExportOptionProvider, Shared]
internal class ColorSchemeOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ColorSchemeOptionsProvider()
{
}
public ImmutableArray<IOption> Options => ImmutableArray.Create<IOption>(
ColorSchemeOptions.ColorScheme,
ColorSchemeOptions.LegacyUseEnhancedColors);
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/EditorFeatures/CSharpTest/EditAndContinue/StatementEditingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditAndContinue;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
[UseExportProvider]
public class StatementEditingTests : EditingTestBase
{
#region Strings
[Fact]
public void StringLiteral_update()
{
var src1 = @"
var x = ""Hello1"";
";
var src2 = @"
var x = ""Hello2"";
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [x = \"Hello1\"]@8 -> [x = \"Hello2\"]@8");
}
[Fact]
public void InterpolatedStringText_update()
{
var src1 = @"
var x = $""Hello1"";
";
var src2 = @"
var x = $""Hello2"";
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [x = $\"Hello1\"]@8 -> [x = $\"Hello2\"]@8");
}
[Fact]
public void Interpolation_update()
{
var src1 = @"
var x = $""Hello{123}"";
";
var src2 = @"
var x = $""Hello{124}"";
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [x = $\"Hello{123}\"]@8 -> [x = $\"Hello{124}\"]@8");
}
[Fact]
public void InterpolationFormatClause_update()
{
var src1 = @"
var x = $""Hello{123:N1}"";
";
var src2 = @"
var x = $""Hello{123:N2}"";
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [x = $\"Hello{123:N1}\"]@8 -> [x = $\"Hello{123:N2}\"]@8");
}
#endregion
#region Variable Declaration
[Fact]
public void VariableDeclaration_Insert()
{
var src1 = "if (x == 1) { x++; }";
var src2 = "var x = 1; if (x == 1) { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [var x = 1;]@2",
"Insert [var x = 1]@2",
"Insert [x = 1]@6");
}
[Fact]
public void VariableDeclaration_Update()
{
var src1 = "int x = F(1), y = G(2);";
var src2 = "int x = F(3), y = G(4);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [x = F(1)]@6 -> [x = F(3)]@6",
"Update [y = G(2)]@16 -> [y = G(4)]@16");
}
[Fact]
public void ParenthesizedVariableDeclaration_Update()
{
var src1 = @"
var (x1, (x2, x3)) = (1, (2, true));
var (a1, a2) = (1, () => { return 7; });
";
var src2 = @"
var (x1, (x2, x4)) = (1, (2, true));
var (a1, a3) = (1, () => { return 8; });
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [x3]@18 -> [x4]@18",
"Update [a2]@51 -> [a3]@51");
}
[Fact]
public void ParenthesizedVariableDeclaration_Insert()
{
var src1 = @"var (z1, z2) = (1, 2);";
var src2 = @"var (z1, z2, z3) = (1, 2, 5);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var (z1, z2) = (1, 2);]@2 -> [var (z1, z2, z3) = (1, 2, 5);]@2",
"Insert [z3]@15");
}
[Fact]
public void ParenthesizedVariableDeclaration_Delete()
{
var src1 = @"var (y1, y2, y3) = (1, 2, 7);";
var src2 = @"var (y1, y2) = (1, 4);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var (y1, y2, y3) = (1, 2, 7);]@2 -> [var (y1, y2) = (1, 4);]@2",
"Delete [y3]@15");
}
[Fact]
public void ParenthesizedVariableDeclaration_Insert_Mixed1()
{
var src1 = @"int a; (var z1, a) = (1, 2);";
var src2 = @"int a; (var z1, a, var z3) = (1, 2, 5);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(var z1, a) = (1, 2);]@9 -> [(var z1, a, var z3) = (1, 2, 5);]@9",
"Insert [z3]@25");
}
[Fact]
public void ParenthesizedVariableDeclaration_Insert_Mixed2()
{
var src1 = @"int a; (var z1, var z2) = (1, 2);";
var src2 = @"int a; (var z1, var z2, a) = (1, 2, 5);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(var z1, var z2) = (1, 2);]@9 -> [(var z1, var z2, a) = (1, 2, 5);]@9");
}
[Fact]
public void ParenthesizedVariableDeclaration_Delete_Mixed1()
{
var src1 = @"int a; (var y1, var y2, a) = (1, 2, 7);";
var src2 = @"int a; (var y1, var y2) = (1, 4);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(var y1, var y2, a) = (1, 2, 7);]@9 -> [(var y1, var y2) = (1, 4);]@9");
}
[Fact]
public void ParenthesizedVariableDeclaration_Delete_Mixed2()
{
var src1 = @"int a; (var y1, a, var y3) = (1, 2, 7);";
var src2 = @"int a; (var y1, a) = (1, 4);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(var y1, a, var y3) = (1, 2, 7);]@9 -> [(var y1, a) = (1, 4);]@9",
"Delete [y3]@25");
}
[Fact]
public void VariableDeclaraions_Reorder()
{
var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);";
var src2 = @"var (c, d) = (3, 4); var (a, b) = (1, 2);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [var (c, d) = (3, 4);]@23 -> @2");
}
[Fact]
public void VariableDeclaraions_Reorder_Mixed()
{
var src1 = @"int a; (a, int b) = (1, 2); (int c, int d) = (3, 4);";
var src2 = @"int a; (int c, int d) = (3, 4); (a, int b) = (1, 2);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [(int c, int d) = (3, 4);]@30 -> @9");
}
[Fact]
public void VariableNames_Reorder()
{
var src1 = @"var (a, b) = (1, 2);";
var src2 = @"var (b, a) = (2, 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var (a, b) = (1, 2);]@2 -> [var (b, a) = (2, 1);]@2",
"Reorder [b]@10 -> @7");
}
[Fact]
public void VariableNames_Reorder_Mixed()
{
var src1 = @"int a; (a, int b) = (1, 2);";
var src2 = @"int a; (int b, a) = (2, 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(a, int b) = (1, 2);]@9 -> [(int b, a) = (2, 1);]@9");
}
[Fact]
public void VariableNamesAndDeclaraions_Reorder()
{
var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);";
var src2 = @"var (d, c) = (3, 4); var (a, b) = (1, 2);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [var (c, d) = (3, 4);]@23 -> @2",
"Reorder [d]@31 -> @7");
}
[Fact]
public void ParenthesizedVariableDeclaration_Reorder()
{
var src1 = @"var (a, (b, c)) = (1, (2, 3));";
var src2 = @"var ((b, c), a) = ((2, 3), 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((b, c), a) = ((2, 3), 1);]@2",
"Reorder [a]@7 -> @15");
}
[Fact]
public void ParenthesizedVariableDeclaration_DoubleReorder()
{
var src1 = @"var (a, (b, c)) = (1, (2, 3));";
var src2 = @"var ((c, b), a) = ((2, 3), 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = ((2, 3), 1);]@2",
"Reorder [b]@11 -> @11",
"Reorder [c]@14 -> @8");
}
[Fact]
public void ParenthesizedVariableDeclaration_ComplexReorder()
{
var src1 = @"var (a, (b, c)) = (1, (2, 3)); var (x, (y, z)) = (4, (5, 6));";
var src2 = @"var (x, (y, z)) = (4, (5, 6)); var ((c, b), a) = (1, (2, 3)); ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [var (x, (y, z)) = (4, (5, 6));]@33 -> @2",
"Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = (1, (2, 3));]@33",
"Reorder [b]@11 -> @42",
"Reorder [c]@14 -> @39");
}
#endregion
#region Switch Statement
[Fact]
public void Switch1()
{
var src1 = "switch (a) { case 1: f(); break; } switch (b) { case 2: g(); break; }";
var src2 = "switch (b) { case 2: f(); break; } switch (a) { case 1: g(); break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [switch (b) { case 2: g(); break; }]@37 -> @2",
"Update [case 1: f(); break;]@15 -> [case 2: f(); break;]@15",
"Move [case 1: f(); break;]@15 -> @15",
"Update [case 2: g(); break;]@50 -> [case 1: g(); break;]@50",
"Move [case 2: g(); break;]@50 -> @50");
}
[Fact]
public void Switch_Case_Reorder()
{
var src1 = "switch (expr) { case 1: f(); break; case 2: case 3: case 4: g(); break; }";
var src2 = "switch (expr) { case 2: case 3: case 4: g(); break; case 1: f(); break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [case 2: case 3: case 4: g(); break;]@40 -> @18");
}
[Fact]
public void Switch_Case_Update()
{
var src1 = "switch (expr) { case 1: f(); break; }";
var src2 = "switch (expr) { case 2: f(); break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case 1: f(); break;]@18 -> [case 2: f(); break;]@18");
}
[Fact]
public void CasePatternLabel_UpdateDelete()
{
var src1 = @"
switch(shape)
{
case Point p: return 0;
case Circle c: return 1;
}
";
var src2 = @"
switch(shape)
{
case Circle circle: return 1;
}
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case Circle c: return 1;]@55 -> [case Circle circle: return 1;]@26",
"Update [c]@67 -> [circle]@38",
"Delete [case Point p: return 0;]@26",
"Delete [case Point p:]@26",
"Delete [p]@37",
"Delete [return 0;]@40");
}
#endregion
#region Switch Expression
[Fact]
public void MethodUpdate_UpdateSwitchExpression1()
{
var src1 = @"
class C
{
static int F(int a) => a switch { 0 => 0, _ => 1 };
}";
var src2 = @"
class C
{
static int F(int a) => a switch { 0 => 0, _ => 2 };
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, _ => 2 };]@18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateSwitchExpression2()
{
var src1 = @"
class C
{
static int F(int a) => a switch { 0 => 0, _ => 1 };
}";
var src2 = @"
class C
{
static int F(int a) => a switch { 1 => 0, _ => 2 };
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 1 => 0, _ => 2 };]@18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateSwitchExpression3()
{
var src1 = @"
class C
{
static int F(int a) => a switch { 0 => 0, _ => 1 };
}";
var src2 = @"
class C
{
static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 };
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 };]@18");
edits.VerifyRudeDiagnostics();
}
#endregion
#region Try Catch Finally
[Fact]
public void TryInsert1()
{
var src1 = "x++;";
var src2 = "try { x++; } catch { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [try { x++; } catch { }]@2",
"Insert [{ x++; }]@6",
"Insert [catch { }]@15",
"Move [x++;]@2 -> @8",
"Insert [{ }]@21");
}
[Fact]
public void TryInsert2()
{
var src1 = "{ x++; }";
var src2 = "try { x++; } catch { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [try { x++; } catch { }]@2",
"Move [{ x++; }]@2 -> @6",
"Insert [catch { }]@15",
"Insert [{ }]@21");
}
[Fact]
public void TryDelete1()
{
var src1 = "try { x++; } catch { }";
var src2 = "x++;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [x++;]@8 -> @2",
"Delete [try { x++; } catch { }]@2",
"Delete [{ x++; }]@6",
"Delete [catch { }]@15",
"Delete [{ }]@21");
}
[Fact]
public void TryDelete2()
{
var src1 = "try { x++; } catch { }";
var src2 = "{ x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ x++; }]@6 -> @2",
"Delete [try { x++; } catch { }]@2",
"Delete [catch { }]@15",
"Delete [{ }]@21");
}
[Fact]
public void TryReorder()
{
var src1 = "try { x++; } catch { /*1*/ } try { y++; } catch { /*2*/ }";
var src2 = "try { y++; } catch { /*2*/ } try { x++; } catch { /*1*/ } ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [try { y++; } catch { /*2*/ }]@31 -> @2");
}
[Fact]
public void Finally_DeleteHeader()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ /*3*/ }]@47 -> @39",
"Delete [finally { /*3*/ }]@39");
}
[Fact]
public void Finally_InsertHeader()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [finally { /*3*/ }]@39",
"Move [{ /*3*/ }]@39 -> @47");
}
[Fact]
public void CatchUpdate()
{
var src1 = "try { } catch (Exception e) { }";
var src2 = "try { } catch (IOException e) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(Exception e)]@16 -> [(IOException e)]@16");
}
[Fact]
public void CatchInsert()
{
var src1 = "try { /*1*/ } catch (Exception e) { /*2*/ } ";
var src2 = "try { /*1*/ } catch (IOException e) { /*3*/ } catch (Exception e) { /*2*/ } ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [catch (IOException e) { /*3*/ }]@16",
"Insert [(IOException e)]@22",
"Insert [{ /*3*/ }]@38");
}
[Fact]
public void CatchBodyUpdate()
{
var src1 = "try { } catch (E e) { x++; }";
var src2 = "try { } catch (E e) { y++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [x++;]@24 -> [y++;]@24");
}
[Fact]
public void CatchDelete()
{
var src1 = "try { } catch (IOException e) { } catch (Exception e) { } ";
var src2 = "try { } catch (IOException e) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [catch (Exception e) { }]@36",
"Delete [(Exception e)]@42",
"Delete [{ }]@56");
}
[Fact]
public void CatchReorder1()
{
var src1 = "try { } catch (IOException e) { } catch (Exception e) { } ";
var src2 = "try { } catch (Exception e) { } catch (IOException e) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [catch (Exception e) { }]@36 -> @10");
}
[Fact]
public void CatchReorder2()
{
var src1 = "try { } catch (IOException e) { } catch (Exception e) { } catch { }";
var src2 = "try { } catch (A e) { } catch (Exception e) { } catch (IOException e) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [catch (Exception e) { }]@36 -> @26",
"Reorder [catch { }]@60 -> @10",
"Insert [(A e)]@16");
}
[Fact]
public void CatchFilterReorder2()
{
var src1 = "try { } catch (Exception e) when (e != null) { } catch (Exception e) { } catch { }";
var src2 = "try { } catch when (s == 1) { } catch (Exception e) { } catch (Exception e) when (e != null) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [catch (Exception e) { }]@51 -> @34",
"Reorder [catch { }]@75 -> @10",
"Insert [when (s == 1)]@16");
}
[Fact]
public void CatchInsertDelete()
{
var src1 = @"
try { x++; } catch (E e) { /*1*/ } catch (Exception e) { /*2*/ }
try { Console.WriteLine(); } finally { /*3*/ }";
var src2 = @"
try { x++; } catch (Exception e) { /*2*/ }
try { Console.WriteLine(); } catch (E e) { /*1*/ } finally { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [catch (E e) { /*1*/ }]@79",
"Insert [(E e)]@85",
"Move [{ /*1*/ }]@29 -> @91",
"Delete [catch (E e) { /*1*/ }]@17",
"Delete [(E e)]@23");
}
[Fact]
public void Catch_DeleteHeader1()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ /*3*/ }]@52 -> @39",
"Delete [catch (E2 e) { /*3*/ }]@39",
"Delete [(E2 e)]@45");
}
[Fact]
public void Catch_InsertHeader1()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [catch (E2 e) { /*3*/ }]@39",
"Insert [(E2 e)]@45",
"Move [{ /*3*/ }]@39 -> @52");
}
[Fact]
public void Catch_DeleteHeader2()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ /*3*/ }]@45 -> @39",
"Delete [catch { /*3*/ }]@39");
}
[Fact]
public void Catch_InsertHeader2()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [catch { /*3*/ }]@39",
"Move [{ /*3*/ }]@39 -> @45");
}
[Fact]
public void Catch_InsertFilter1()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }";
var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [when (e == null)]@29");
}
[Fact]
public void Catch_InsertFilter2()
{
var src1 = "try { /*1*/ } catch when (e == null) { /*2*/ }";
var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [(E1 e)]@22");
}
[Fact]
public void Catch_InsertFilter3()
{
var src1 = "try { /*1*/ } catch { /*2*/ }";
var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [(E1 e)]@22",
"Insert [when (e == null)]@29");
}
[Fact]
public void Catch_DeleteDeclaration1()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }";
var src2 = "try { /*1*/ } catch { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [(E1 e)]@22");
}
[Fact]
public void Catch_DeleteFilter1()
{
var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [when (e == null)]@29");
}
[Fact]
public void Catch_DeleteFilter2()
{
var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var src2 = "try { /*1*/ } catch when (e == null) { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [(E1 e)]@22");
}
[Fact]
public void Catch_DeleteFilter3()
{
var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var src2 = "try { /*1*/ } catch { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [(E1 e)]@22",
"Delete [when (e == null)]@29");
}
[Fact]
public void TryCatchFinally_DeleteHeader()
{
var src1 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }";
var src2 = "{ /*1*/ } { /*2*/ } { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ /*1*/ }]@6 -> @2",
"Move [{ /*2*/ }]@22 -> @12",
"Move [{ /*3*/ }]@40 -> @22",
"Delete [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2",
"Delete [catch { /*2*/ }]@16",
"Delete [finally { /*3*/ }]@32");
}
[Fact]
public void TryCatchFinally_InsertHeader()
{
var src1 = "{ /*1*/ } { /*2*/ } { /*3*/ }";
var src2 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2",
"Move [{ /*1*/ }]@2 -> @6",
"Insert [catch { /*2*/ }]@16",
"Insert [finally { /*3*/ }]@32",
"Move [{ /*2*/ }]@12 -> @22",
"Move [{ /*3*/ }]@22 -> @40");
}
[Fact]
public void TryFilterFinally_InsertHeader()
{
var src1 = "{ /*1*/ } if (a == 1) { /*2*/ } { /*3*/ }";
var src2 = "try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }]@2",
"Move [{ /*1*/ }]@2 -> @6",
"Insert [catch when (a == 1) { /*2*/ }]@16",
"Insert [finally { /*3*/ }]@46",
"Insert [when (a == 1)]@22",
"Move [{ /*2*/ }]@24 -> @36",
"Move [{ /*3*/ }]@34 -> @54",
"Delete [if (a == 1) { /*2*/ }]@12");
}
#endregion
#region Blocks
[Fact]
public void Block_Insert()
{
var src1 = "";
var src2 = "{ x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [{ x++; }]@2",
"Insert [x++;]@4");
}
[Fact]
public void Block_Delete()
{
var src1 = "{ x++; }";
var src2 = "";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [{ x++; }]@2",
"Delete [x++;]@4");
}
[Fact]
public void Block_Reorder()
{
var src1 = "{ x++; } { y++; }";
var src2 = "{ y++; } { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [{ y++; }]@11 -> @2");
}
[Fact]
public void Block_AddLine()
{
var src1 = "{ x++; }";
var src2 = @"{ //
x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits();
}
#endregion
#region Checked/Unchecked
[Fact]
public void Checked_Insert()
{
var src1 = "";
var src2 = "checked { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [checked { x++; }]@2",
"Insert [{ x++; }]@10",
"Insert [x++;]@12");
}
[Fact]
public void Checked_Delete()
{
var src1 = "checked { x++; }";
var src2 = "";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [checked { x++; }]@2",
"Delete [{ x++; }]@10",
"Delete [x++;]@12");
}
[Fact]
public void Checked_Update()
{
var src1 = "checked { x++; }";
var src2 = "unchecked { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [checked { x++; }]@2 -> [unchecked { x++; }]@2");
}
[Fact]
public void Checked_DeleteHeader()
{
var src1 = "checked { x++; }";
var src2 = "{ x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ x++; }]@10 -> @2",
"Delete [checked { x++; }]@2");
}
[Fact]
public void Checked_InsertHeader()
{
var src1 = "{ x++; }";
var src2 = "checked { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [checked { x++; }]@2",
"Move [{ x++; }]@2 -> @10");
}
[Fact]
public void Unchecked_InsertHeader()
{
var src1 = "{ x++; }";
var src2 = "unchecked { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [unchecked { x++; }]@2",
"Move [{ x++; }]@2 -> @12");
}
#endregion
#region Unsafe
[Fact]
public void Unsafe_Insert()
{
var src1 = "";
var src2 = "unsafe { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [unsafe { x++; }]@2",
"Insert [{ x++; }]@9",
"Insert [x++;]@11");
}
[Fact]
public void Unsafe_Delete()
{
var src1 = "unsafe { x++; }";
var src2 = "";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [unsafe { x++; }]@2",
"Delete [{ x++; }]@9",
"Delete [x++;]@11");
}
[Fact]
public void Unsafe_DeleteHeader()
{
var src1 = "unsafe { x++; }";
var src2 = "{ x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ x++; }]@9 -> @2",
"Delete [unsafe { x++; }]@2");
}
[Fact]
public void Unsafe_InsertHeader()
{
var src1 = "{ x++; }";
var src2 = "unsafe { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [unsafe { x++; }]@2",
"Move [{ x++; }]@2 -> @9");
}
#endregion
#region Using Statement
[Fact]
public void Using1()
{
var src1 = @"using (a) { using (b) { Goo(); } }";
var src2 = @"using (a) { using (c) { using (b) { Goo(); } } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [using (c) { using (b) { Goo(); } }]@14",
"Insert [{ using (b) { Goo(); } }]@24",
"Move [using (b) { Goo(); }]@14 -> @26");
}
[Fact]
public void Using_DeleteHeader()
{
var src1 = @"using (a) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@12 -> @2",
"Delete [using (a) { Goo(); }]@2");
}
[Fact]
public void Using_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"using (a) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [using (a) { Goo(); }]@2",
"Move [{ Goo(); }]@2 -> @12");
}
#endregion
#region Lock Statement
[Fact]
public void Lock1()
{
var src1 = @"lock (a) { lock (b) { Goo(); } }";
var src2 = @"lock (a) { lock (c) { lock (b) { Goo(); } } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [lock (c) { lock (b) { Goo(); } }]@13",
"Insert [{ lock (b) { Goo(); } }]@22",
"Move [lock (b) { Goo(); }]@13 -> @24");
}
[Fact]
public void Lock_DeleteHeader()
{
var src1 = @"lock (a) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@11 -> @2",
"Delete [lock (a) { Goo(); }]@2");
}
[Fact]
public void Lock_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"lock (a) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [lock (a) { Goo(); }]@2",
"Move [{ Goo(); }]@2 -> @11");
}
#endregion
#region ForEach Statement
[Fact]
public void ForEach1()
{
var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }";
var src2 = @"foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [foreach (var c in g) { foreach (var b in f) { Goo(); } }]@25",
"Insert [{ foreach (var b in f) { Goo(); } }]@46",
"Move [foreach (var b in f) { Goo(); }]@25 -> @48");
var actual = ToMatchingPairs(edits.Match);
var expected = new MatchingPairs
{
{ "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }" },
{ "{ foreach (var b in f) { Goo(); } }", "{ foreach (var c in g) { foreach (var b in f) { Goo(); } } }" },
{ "foreach (var b in f) { Goo(); }", "foreach (var b in f) { Goo(); }" },
{ "{ Goo(); }", "{ Goo(); }" },
{ "Goo();", "Goo();" }
};
expected.AssertEqual(actual);
}
[Fact]
public void ForEach_Swap1()
{
var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }";
var src2 = @"foreach (var b in f) { foreach (var a in e) { Goo(); } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [foreach (var b in f) { Goo(); }]@25 -> @2",
"Move [foreach (var a in e) { foreach (var b in f) { Goo(); } }]@2 -> @25",
"Move [Goo();]@48 -> @48");
var actual = ToMatchingPairs(edits.Match);
var expected = new MatchingPairs
{
{ "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { Goo(); }" },
{ "{ foreach (var b in f) { Goo(); } }", "{ Goo(); }" },
{ "foreach (var b in f) { Goo(); }", "foreach (var b in f) { foreach (var a in e) { Goo(); } }" },
{ "{ Goo(); }", "{ foreach (var a in e) { Goo(); } }" },
{ "Goo();", "Goo();" }
};
expected.AssertEqual(actual);
}
[Fact]
public void Foreach_DeleteHeader()
{
var src1 = @"foreach (var a in b) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@23 -> @2",
"Delete [foreach (var a in b) { Goo(); }]@2");
}
[Fact]
public void Foreach_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"foreach (var a in b) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [foreach (var a in b) { Goo(); }]@2",
"Move [{ Goo(); }]@2 -> @23");
}
[Fact]
public void ForeachVariable_Update1()
{
var src1 = @"
foreach (var (a1, a2) in e) { }
foreach ((var b1, var b2) in e) { }
foreach (var a in e1) { }
";
var src2 = @"
foreach (var (a1, a3) in e) { }
foreach ((var b3, int b2) in e) { }
foreach (_ in e1) { }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [foreach ((var b1, var b2) in e) { }]@37 -> [foreach ((var b3, int b2) in e) { }]@37",
"Update [foreach (var a in e1) { }]@74 -> [foreach (_ in e1) { }]@74",
"Update [a2]@22 -> [a3]@22",
"Update [b1]@51 -> [b3]@51");
}
[Fact]
public void ForeachVariable_Update2()
{
var src1 = @"
foreach (_ in e2) { }
foreach (_ in e3) { A(); }
";
var src2 = @"
foreach (var b in e2) { }
foreach (_ in e4) { A(); }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [foreach (_ in e2) { }]@4 -> [foreach (var b in e2) { }]@4",
"Update [foreach (_ in e3) { A(); }]@27 -> [foreach (_ in e4) { A(); }]@31");
}
[Fact]
public void ForeachVariable_Insert()
{
var src1 = @"
foreach (var (a3, a4) in e) { }
foreach ((var b4, var b5) in e) { }
";
var src2 = @"
foreach (var (a3, a5, a4) in e) { }
foreach ((var b6, var b4, var b5) in e) { }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [foreach (var (a3, a4) in e) { }]@4 -> [foreach (var (a3, a5, a4) in e) { }]@4",
"Update [foreach ((var b4, var b5) in e) { }]@37 -> [foreach ((var b6, var b4, var b5) in e) { }]@41",
"Insert [a5]@22",
"Insert [b6]@55");
}
[Fact]
public void ForeachVariable_Delete()
{
var src1 = @"
foreach (var (a11, a12, a13) in e) { F(); }
foreach ((var b7, var b8, var b9) in e) { G(); }
";
var src2 = @"
foreach (var (a12, a13) in e1) { F(); }
foreach ((var b7, var b9) in e) { G(); }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [foreach (var (a11, a12, a13) in e) { F(); }]@4 -> [foreach (var (a12, a13) in e1) { F(); }]@4",
"Update [foreach ((var b7, var b8, var b9) in e) { G(); }]@49 -> [foreach ((var b7, var b9) in e) { G(); }]@45",
"Delete [a11]@18",
"Delete [b8]@71");
}
[Fact]
public void ForeachVariable_Reorder()
{
var src1 = @"
foreach (var (a, b) in e1) { }
foreach ((var x, var y) in e2) { }
";
var src2 = @"
foreach ((var x, var y) in e2) { }
foreach (var (a, b) in e1) { }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [foreach ((var x, var y) in e2) { }]@36 -> @4");
}
[Fact]
public void ForeachVariableEmbedded_Reorder()
{
var src1 = @"
foreach (var (a, b) in e1) {
foreach ((var x, var y) in e2) { }
}
";
var src2 = @"
foreach ((var x, var y) in e2) { }
foreach (var (a, b) in e1) { }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [foreach ((var x, var y) in e2) { }]@39 -> @4");
}
#endregion
#region For Statement
[Fact]
public void For1()
{
var src1 = @"for (int a = 0; a < 10; a++) { for (int a = 0; a < 20; a++) { Goo(); } }";
var src2 = @"for (int a = 0; a < 10; a++) { for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } }]@33",
"Insert [int b = 0]@38",
"Insert [b < 10]@49",
"Insert [b++]@57",
"Insert [{ for (int a = 0; a < 20; a++) { Goo(); } }]@62",
"Insert [b = 0]@42",
"Move [for (int a = 0; a < 20; a++) { Goo(); }]@33 -> @64");
}
[Fact]
public void For_DeleteHeader()
{
var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@43 -> @2",
"Delete [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2",
"Delete [int i = 10, j = 0]@7",
"Delete [i = 10]@11",
"Delete [j = 0]@19",
"Delete [i > j]@26",
"Delete [i--]@33",
"Delete [j++]@38");
}
[Fact]
public void For_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2",
"Insert [int i = 10, j = 0]@7",
"Insert [i > j]@26",
"Insert [i--]@33",
"Insert [j++]@38",
"Move [{ Goo(); }]@2 -> @43",
"Insert [i = 10]@11",
"Insert [j = 0]@19");
}
[Fact]
public void For_DeclaratorsToInitializers()
{
var src1 = @"for (var i = 10; i < 10; i++) { }";
var src2 = @"for (i = 10; i < 10; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [i = 10]@7",
"Delete [var i = 10]@7",
"Delete [i = 10]@11");
}
[Fact]
public void For_InitializersToDeclarators()
{
var src1 = @"for (i = 10, j = 0; i < 10; i++) { }";
var src2 = @"for (var i = 10, j = 0; i < 10; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [var i = 10, j = 0]@7",
"Insert [i = 10]@11",
"Insert [j = 0]@19",
"Delete [i = 10]@7",
"Delete [j = 0]@15");
}
[Fact]
public void For_Declarations_Reorder()
{
var src1 = @"for (var i = 10, j = 0; i > j; i++, j++) { }";
var src2 = @"for (var j = 0, i = 10; i > j; i++, j++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Reorder [j = 0]@19 -> @11");
}
[Fact]
public void For_Declarations_Insert()
{
var src1 = @"for (var i = 0, j = 1; i > j; i++, j++) { }";
var src2 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var i = 0, j = 1]@7 -> [var i = 0, j = 1, k = 2]@7",
"Insert [k = 2]@25");
}
[Fact]
public void For_Declarations_Delete()
{
var src1 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }";
var src2 = @"for (var i = 0, j = 1; i > j; i++, j++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var i = 0, j = 1, k = 2]@7 -> [var i = 0, j = 1]@7",
"Delete [k = 2]@25");
}
[Fact]
public void For_Initializers_Reorder()
{
var src1 = @"for (i = 10, j = 0; i > j; i++, j++) { }";
var src2 = @"for (j = 0, i = 10; i > j; i++, j++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Reorder [j = 0]@15 -> @7");
}
[Fact]
public void For_Initializers_Insert()
{
var src1 = @"for (i = 10; i < 10; i++) { }";
var src2 = @"for (i = 10, j = 0; i < 10; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Insert [j = 0]@15");
}
[Fact]
public void For_Initializers_Delete()
{
var src1 = @"for (i = 10, j = 0; i < 10; i++) { }";
var src2 = @"for (i = 10; i < 10; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Delete [j = 0]@15");
}
[Fact]
public void For_Initializers_Update()
{
var src1 = @"for (i = 1; i < 10; i++) { }";
var src2 = @"for (i = 2; i < 10; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [i = 1]@7 -> [i = 2]@7");
}
[Fact]
public void For_Initializers_Update_Lambda()
{
var src1 = @"for (int i = 10, j = F(() => 1); i > j; i++) { }";
var src2 = @"for (int i = 10, j = F(() => 2); i > j; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [() => 1]@25 -> [() => 2]@25");
}
[Fact]
public void For_Condition_Update()
{
var src1 = @"for (int i = 0; i < 10; i++) { }";
var src2 = @"for (int i = 0; i < 20; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [i < 10]@18 -> [i < 20]@18");
}
[Fact]
public void For_Condition_Lambda()
{
var src1 = @"for (int i = 0; F(() => 1); i++) { }";
var src2 = @"for (int i = 0; F(() => 2); i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [() => 1]@20 -> [() => 2]@20");
}
[Fact]
public void For_Incrementors_Reorder()
{
var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { }";
var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Reorder [j++]@38 -> @33");
}
[Fact]
public void For_Incrementors_Insert()
{
var src1 = @"for (int i = 10, j = 0; i > j; i--) { }";
var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Insert [j++]@33");
}
[Fact]
public void For_Incrementors_Delete()
{
var src1 = @"for (int i = 10, j = 0; i > j; j++, i--) { }";
var src2 = @"for (int i = 10, j = 0; i > j; j++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Delete [i--]@38");
}
[Fact]
public void For_Incrementors_Update()
{
var src1 = @"for (int i = 10, j = 0; i > j; j++) { }";
var src2 = @"for (int i = 10, j = 0; i > j; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [j++]@33 -> [i++]@33");
}
[Fact]
public void For_Incrementors_Update_Lambda()
{
var src1 = @"for (int i = 10, j = 0; i > j; F(() => 1)) { }";
var src2 = @"for (int i = 10, j = 0; i > j; F(() => 2)) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [() => 1]@35 -> [() => 2]@35");
}
#endregion
#region While Statement
[Fact]
public void While1()
{
var src1 = @"while (a) { while (b) { Goo(); } }";
var src2 = @"while (a) { while (c) { while (b) { Goo(); } } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [while (c) { while (b) { Goo(); } }]@14",
"Insert [{ while (b) { Goo(); } }]@24",
"Move [while (b) { Goo(); }]@14 -> @26");
}
[Fact]
public void While_DeleteHeader()
{
var src1 = @"while (a) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@12 -> @2",
"Delete [while (a) { Goo(); }]@2");
}
[Fact]
public void While_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"while (a) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [while (a) { Goo(); }]@2",
"Move [{ Goo(); }]@2 -> @12");
}
#endregion
#region Do Statement
[Fact]
public void Do1()
{
var src1 = @"do { do { Goo(); } while (b); } while (a);";
var src2 = @"do { do { do { Goo(); } while(b); } while(c); } while(a);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [do { do { Goo(); } while(b); } while(c);]@7",
"Insert [{ do { Goo(); } while(b); }]@10",
"Move [do { Goo(); } while (b);]@7 -> @12");
}
[Fact]
public void Do_DeleteHeader()
{
var src1 = @"do { Goo(); } while (a);";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@5 -> @2",
"Delete [do { Goo(); } while (a);]@2");
}
[Fact]
public void Do_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"do { Goo(); } while (a);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [do { Goo(); } while (a);]@2",
"Move [{ Goo(); }]@2 -> @5");
}
#endregion
#region If Statement
[Fact]
public void IfStatement_TestExpression_Update()
{
var src1 = "var x = 1; if (x == 1) { x++; }";
var src2 = "var x = 1; if (x == 2) { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if (x == 1) { x++; }]@13 -> [if (x == 2) { x++; }]@13");
}
[Fact]
public void ElseClause_Insert()
{
var src1 = "if (x == 1) x++; ";
var src2 = "if (x == 1) x++; else y++;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [else y++;]@19",
"Insert [y++;]@24");
}
[Fact]
public void ElseClause_InsertMove()
{
var src1 = "if (x == 1) x++; else y++;";
var src2 = "if (x == 1) x++; else if (x == 2) y++;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [if (x == 2) y++;]@24",
"Move [y++;]@24 -> @36");
}
[Fact]
public void If1()
{
var src1 = @"if (a) if (b) Goo();";
var src2 = @"if (a) if (c) if (b) Goo();";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [if (c) if (b) Goo();]@9",
"Move [if (b) Goo();]@9 -> @16");
}
[Fact]
public void If_DeleteHeader()
{
var src1 = @"if (a) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@9 -> @2",
"Delete [if (a) { Goo(); }]@2");
}
[Fact]
public void If_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"if (a) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [if (a) { Goo(); }]@2",
"Move [{ Goo(); }]@2 -> @9");
}
[Fact]
public void Else_DeleteHeader()
{
var src1 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }";
var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(/*2*/); }]@30 -> @25",
"Delete [else { Goo(/*2*/); }]@25");
}
[Fact]
public void Else_InsertHeader()
{
var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }";
var src2 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [else { Goo(/*2*/); }]@25",
"Move [{ Goo(/*2*/); }]@25 -> @30");
}
[Fact]
public void ElseIf_DeleteHeader()
{
var src1 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }";
var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(/*2*/); }]@37 -> @25",
"Delete [else if (b) { Goo(/*2*/); }]@25",
"Delete [if (b) { Goo(/*2*/); }]@30");
}
[Fact]
public void ElseIf_InsertHeader()
{
var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }";
var src2 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [else if (b) { Goo(/*2*/); }]@25",
"Insert [if (b) { Goo(/*2*/); }]@30",
"Move [{ Goo(/*2*/); }]@25 -> @37");
}
[Fact]
public void IfElseElseIf_InsertHeader()
{
var src1 = @"{ /*1*/ } { /*2*/ } { /*3*/ }";
var src2 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2",
"Move [{ /*1*/ }]@2 -> @9",
"Insert [else if (b) { /*2*/ } else { /*3*/ }]@19",
"Insert [if (b) { /*2*/ } else { /*3*/ }]@24",
"Move [{ /*2*/ }]@12 -> @31",
"Insert [else { /*3*/ }]@41",
"Move [{ /*3*/ }]@22 -> @46");
}
[Fact]
public void IfElseElseIf_DeleteHeader()
{
var src1 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }";
var src2 = @"{ /*1*/ } { /*2*/ } { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ /*1*/ }]@9 -> @2",
"Move [{ /*2*/ }]@31 -> @12",
"Move [{ /*3*/ }]@46 -> @22",
"Delete [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2",
"Delete [else if (b) { /*2*/ } else { /*3*/ }]@19",
"Delete [if (b) { /*2*/ } else { /*3*/ }]@24",
"Delete [else { /*3*/ }]@41");
}
#endregion
#region Switch Statement
[Fact]
public void SwitchStatement_Update_Expression()
{
var src1 = "var x = 1; switch (x + 1) { case 1: break; }";
var src2 = "var x = 1; switch (x + 2) { case 1: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [switch (x + 1) { case 1: break; }]@13 -> [switch (x + 2) { case 1: break; }]@13");
}
[Fact]
public void SwitchStatement_Update_SectionLabel()
{
var src1 = "var x = 1; switch (x) { case 1: break; }";
var src2 = "var x = 1; switch (x) { case 2: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case 1: break;]@26 -> [case 2: break;]@26");
}
[Fact]
public void SwitchStatement_Update_AddSectionLabel()
{
var src1 = "var x = 1; switch (x) { case 1: break; }";
var src2 = "var x = 1; switch (x) { case 1: case 2: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case 1: break;]@26 -> [case 1: case 2: break;]@26");
}
[Fact]
public void SwitchStatement_Update_DeleteSectionLabel()
{
var src1 = "var x = 1; switch (x) { case 1: case 2: break; }";
var src2 = "var x = 1; switch (x) { case 1: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case 1: case 2: break;]@26 -> [case 1: break;]@26");
}
[Fact]
public void SwitchStatement_Update_BlockInSection()
{
var src1 = "var x = 1; switch (x) { case 1: { x++; break; } }";
var src2 = "var x = 1; switch (x) { case 1: { x--; break; } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [x++;]@36 -> [x--;]@36");
}
[Fact]
public void SwitchStatement_Update_BlockInDefaultSection()
{
var src1 = "var x = 1; switch (x) { default: { x++; break; } }";
var src2 = "var x = 1; switch (x) { default: { x--; break; } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [x++;]@37 -> [x--;]@37");
}
[Fact]
public void SwitchStatement_Insert_Section()
{
var src1 = "var x = 1; switch (x) { case 1: break; }";
var src2 = "var x = 1; switch (x) { case 1: break; case 2: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [case 2: break;]@41",
"Insert [break;]@49");
}
[Fact]
public void SwitchStatement_Delete_Section()
{
var src1 = "var x = 1; switch (x) { case 1: break; case 2: break; }";
var src2 = "var x = 1; switch (x) { case 1: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [case 2: break;]@41",
"Delete [break;]@49");
}
#endregion
#region Lambdas
[Fact]
public void Lambdas_AddAttribute()
{
var src1 = "Func<int, int> x = (a) => a;";
var src2 = "Func<int, int> x = [A][return:A]([A]a) => a;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(a) => a]@21 -> [[A][return:A]([A]a) => a]@21",
"Update [a]@22 -> [[A]a]@35");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.method),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.method),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.parameter));
GetTopEdits(edits).VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Lambdas_InVariableDeclarator()
{
var src1 = "Action x = a => a, y = b => b;";
var src2 = "Action x = (a) => a, y = b => b + 1;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [a => a]@13 -> [(a) => a]@13",
"Update [b => b]@25 -> [b => b + 1]@27",
"Insert [(a)]@13",
"Insert [a]@14",
"Delete [a]@13");
}
[Fact]
public void Lambdas_InExpressionStatement()
{
var src1 = "F(a => a, b => b);";
var src2 = "F(b => b, a => a+1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [b => b]@12 -> @4",
"Update [a => a]@4 -> [a => a+1]@12");
}
[Fact]
public void Lambdas_ReorderArguments()
{
var src1 = "F(G(a => {}), G(b => {}));";
var src2 = "F(G(b => {}), G(a => {}));";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [b => {}]@18 -> @6");
}
[Fact]
public void Lambdas_InWhile()
{
var src1 = "while (F(a => a)) { /*1*/ }";
var src2 = "do { /*1*/ } while (F(a => a));";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [do { /*1*/ } while (F(a => a));]@2",
"Move [{ /*1*/ }]@20 -> @5",
"Move [a => a]@11 -> @24",
"Delete [while (F(a => a)) { /*1*/ }]@2");
}
[Fact]
public void Lambdas_InLambda_ChangeInLambdaSignature()
{
var src1 = "F(() => { G(x => y); });";
var src2 = "F(q => { G(() => y); });";
var edits = GetMethodEdits(src1, src2);
// changes were made to the outer lambda signature:
edits.VerifyEdits(
"Update [() => { G(x => y); }]@4 -> [q => { G(() => y); }]@4",
"Insert [q]@4",
"Delete [()]@4");
}
[Fact]
public void Lambdas_InLambda_ChangeOnlyInLambdaBody()
{
var src1 = "F(() => { G(x => y); });";
var src2 = "F(() => { G(() => y); });";
var edits = GetMethodEdits(src1, src2);
// no changes to the method were made, only within the outer lambda body:
edits.VerifyEdits();
}
[Fact]
public void Lambdas_Update_ParameterRefness_NoBodyChange()
{
var src1 = @"F((ref int a) => a = 1);";
var src2 = @"F((out int a) => a = 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [ref int a]@5 -> [out int a]@5");
}
[Fact]
public void Lambdas_Insert_Static_Top()
{
var src1 = @"
using System;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var f = new Func<int, int>(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Insert_Static_Nested1()
{
var src1 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
G(a => a);
}
}
";
var src2 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
G(a => G(b => b) + a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Insert_ThisOnly_Top1()
{
var src1 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
G(a => x);
}
}
";
var edits = GetTopEdits(src1, src2);
// TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")]
public void Lambdas_Insert_ThisOnly_Top2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
int y = 1;
{
int x = 2;
var f1 = new Func<int, int>(a => y);
}
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
int y = 1;
{
int x = 2;
var f2 = from a in new[] { 1 } select a + y;
var f3 = from a in new[] { 1 } where x > 0 select a;
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "x", "x"));
}
[Fact]
public void Lambdas_Insert_ThisOnly_Nested1()
{
var src1 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
G(a => a);
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
G(a => G(b => x));
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact]
public void Lambdas_Insert_ThisOnly_Nested2()
{
var src1 = @"
using System;
class C
{
int x = 0;
void F()
{
var f1 = new Func<int, int>(a =>
{
var f2 = new Func<int, int>(b =>
{
return b;
});
return a;
});
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
void F()
{
var f1 = new Func<int, int>(a =>
{
var f2 = new Func<int, int>(b =>
{
return b;
});
var f3 = new Func<int, int>(c =>
{
return c + x;
});
return a;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact]
public void Lambdas_InsertAndDelete_Scopes1()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0, y = 0; // Group #0
void F()
{
int x0 = 0, y0 = 0; // Group #1
{ int x1 = 0, y1 = 0; // Group #2
{ int x2 = 0, y2 = 0; // Group #1
{ int x3 = 0, y3 = 0; // Group #2
G(a => x3 + x1);
G(a => x0 + y0 + x2);
G(a => x);
}
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0, y = 0; // Group #0
void F()
{
int x0 = 0, y0 = 0; // Group #1
{ int x1 = 0, y1 = 0; // Group #2
{ int x2 = 0, y2 = 0; // Group #1
{ int x3 = 0, y3 = 0; // Group #2
G(a => x3 + x1);
G(a => x0 + y0 + x2);
G(a => x);
G(a => x); // OK
G(a => x0 + y0); // OK
G(a => x1 + y0); // error - connecting Group #1 and Group #2
G(a => x3 + x1); // error - multi-scope (conservative)
G(a => x + y0); // error - connecting Group #0 and Group #1
G(a => x + x3); // error - connecting Group #0 and Group #2
}
}
}
}
}
";
var insert = GetTopEdits(src1, src2);
insert.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3"));
var delete = GetTopEdits(src2, src1);
delete.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3"));
}
[Fact]
public void Lambdas_Insert_ForEach1()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
G(a => x0);
G(a => x1);
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
G(a => x0);
G(a => x1);
G(a => x0 + x1); // error: connecting previously disconnected closures
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"));
}
[Fact]
public void Lambdas_Insert_ForEach2()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {}
void F()
{
int x0 = 0; // Group #0
foreach (int x1 in new[] { 1 }) // Group #1
G(a => x0, a => x1, null);
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {}
void F()
{
int x0 = 0; // Group #0
foreach (int x1 in new[] { 1 }) // Group #1
G(a => x0, a => x1, a => x0 + x1); // error: connecting previously disconnected closures
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"));
}
[Fact]
public void Lambdas_Insert_For1()
{
var src1 = @"
using System;
class C
{
bool G(Func<int, int> f) => true;
void F()
{
for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);)
{
int x2 = 0;
G(a => x2);
}
}
}
";
var src2 = @"
using System;
class C
{
bool G(Func<int, int> f) => true;
void F()
{
for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);)
{
int x2 = 0;
G(a => x2);
G(a => x0 + x1); // ok
G(a => x0 + x2); // error: connecting previously disconnected closures
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x2", CSharpFeaturesResources.lambda, "x0", "x2"));
}
[Fact]
public void Lambdas_Insert_Switch1()
{
var src1 = @"
using System;
class C
{
bool G(Func<int> f) => true;
int a = 1;
void F()
{
int x2 = 1;
G(() => x2);
switch (a)
{
case 1:
int x0 = 1;
G(() => x0);
break;
case 2:
int x1 = 1;
G(() => x1);
break;
}
}
}
";
var src2 = @"
using System;
class C
{
bool G(Func<int> f) => true;
int a = 1;
void F()
{
int x2 = 1;
G(() => x2);
switch (a)
{
case 1:
int x0 = 1;
G(() => x0);
goto case 2;
case 2:
int x1 = 1;
G(() => x1);
goto default;
default:
x0 = 1;
x1 = 2;
G(() => x0 + x1); // ok
G(() => x0 + x2); // error
break;
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x2", "x0"));
}
[Fact]
public void Lambdas_Insert_Using1()
{
var src1 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static int F(object a, object b) => 1;
static IDisposable D() => null;
static void F()
{
using (IDisposable x0 = D(), y0 = D())
{
int x1 = 1;
G(() => x0);
G(() => y0);
G(() => x1);
}
}
}
";
var src2 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static int F(object a, object b) => 1;
static IDisposable D() => null;
static void F()
{
using (IDisposable x0 = D(), y0 = D())
{
int x1 = 1;
G(() => x0);
G(() => y0);
G(() => x1);
G(() => F(x0, y0)); // ok
G(() => F(x0, x1)); // error
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"));
}
[Fact]
public void Lambdas_Insert_Catch1()
{
var src1 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static int F(object a, object b) => 1;
static void F()
{
try
{
}
catch (Exception x0)
{
int x1 = 1;
G(() => x0);
G(() => x1);
}
}
}
";
var src2 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static int F(object a, object b) => 1;
static void F()
{
try
{
}
catch (Exception x0)
{
int x1 = 1;
G(() => x0);
G(() => x1);
G(() => x0); //ok
G(() => F(x0, x1)); //error
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"));
}
[Fact, WorkItem(1504, "https://github.com/dotnet/roslyn/issues/1504")]
public void Lambdas_Insert_CatchFilter1()
{
var src1 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static void F()
{
Exception x1 = null;
try
{
G(() => x1);
}
catch (Exception x0) when (G(() => x0))
{
}
}
}
";
var src2 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static void F()
{
Exception x1 = null;
try
{
G(() => x1);
}
catch (Exception x0) when (G(() => x0) &&
G(() => x0) && // ok
G(() => x0 != x1)) // error
{
G(() => x0); // ok
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x1", "x0")
);
}
[Fact]
public void Lambdas_Insert_NotSupported()
{
var src1 = @"
using System;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var f = new Func<int, int>(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
activeStatements: ActiveStatementsDescription.Empty,
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Insert_Second_NotSupported()
{
var src1 = @"
using System;
class C
{
void F()
{
var f = new Func<int, int>(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var f = new Func<int, int>(a => a);
var g = new Func<int, int>(b => b);
}
}
";
var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition;
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
activeStatements: ActiveStatementsDescription.Empty,
capabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Insert_FirstInClass_NotSupported()
{
var src1 = @"
using System;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var g = new Func<int, int>(b => b);
}
}
";
var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition;
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
activeStatements: ActiveStatementsDescription.Empty,
capabilities,
// TODO: https://github.com/dotnet/roslyn/issues/52759
// This is incorrect, there should be no rude edit reported
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_CeaseCapture_This()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
var f = new Func<int, int>(a => a + x);
}
}
";
var src2 = @"
using System;
class C
{
int x;
void F()
{
var f = new Func<int, int>(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this"));
}
[Fact]
public void Lambdas_Update_Signature1()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<long, long> f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<long, long> f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature2()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int, int> f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int, int> f) {}
void F()
{
G2((a, b) => a + b);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature3()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, long> f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, long> f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature_Nullable()
{
var src1 = @"
using System;
class C
{
void G1(Func<string, string> f) {}
void G2(Func<string?, string?> f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<string, string> f) {}
void G2(Func<string?, string?> f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Signature_SyntaxOnly1()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G2((a) => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Signature_ReturnType1()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Action<int> f) {}
void F()
{
G1(a => { return 1; });
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Action<int> f) {}
void F()
{
G2(a => { });
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature_ReturnType2()
{
var src1 = "var x = int (int a) => a;";
var src2 = "var x = long (int a) => a;";
var edits = GetMethodEdits(src1, src2);
GetTopEdits(edits).VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "(int a)", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature_BodySyntaxOnly()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G1(a => { return 1; });
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G2(a => 2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Signature_ParameterName1()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G1(a => 1);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G2(b => 2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Signature_ParameterRefness1()
{
var src1 = @"
using System;
delegate int D1(ref int a);
delegate int D2(int a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1((ref int a) => 1);
}
}
";
var src2 = @"
using System;
delegate int D1(ref int a);
delegate int D2(int a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2((int a) => 2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "(int a)", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature_ParameterRefness2()
{
var src1 = @"
using System;
delegate int D1(ref int a);
delegate int D2(out int a);
class C
{
void G(D1 f) {}
void G(D2 f) {}
void F()
{
G((ref int a) => a = 1);
}
}
";
var src2 = @"
using System;
delegate int D1(ref int a);
delegate int D2(out int a);
class C
{
void G(D1 f) {}
void G(D2 f) {}
void F()
{
G((out int a) => a = 1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "(out int a)", CSharpFeaturesResources.lambda));
}
// Add corresponding test to VB
[Fact(Skip = "TODO")]
public void Lambdas_Update_Signature_CustomModifiers1()
{
var delegateSource = @"
.class public auto ansi sealed D1
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed
{
}
.method public newslot virtual instance int32 [] modopt([mscorlib]System.Int64) Invoke(
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed
{
}
}
.class public auto ansi sealed D2
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed
{
}
.method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke(
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed
{
}
}
.class public auto ansi sealed D3
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed
{
}
.method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke(
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed
{
}
}";
var src1 = @"
using System;
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2(a => a);
}
}
";
MetadataReference delegateDefs;
using (var tempAssembly = IlasmUtilities.CreateTempAssembly(delegateSource))
{
delegateDefs = MetadataReference.CreateFromImage(File.ReadAllBytes(tempAssembly.Path));
}
var edits = GetTopEdits(src1, src2);
// TODO
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Signature_MatchingErrorType()
{
var src1 = @"
using System;
class C
{
void G(Func<Unknown, Unknown> f) {}
void F()
{
G(a => 1);
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<Unknown, Unknown> f) {}
void F()
{
G(a => 2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("F").Single(), preserveLocalVariables: true)
});
}
[Fact]
public void Lambdas_Signature_NonMatchingErrorType()
{
var src1 = @"
using System;
class C
{
void G1(Func<Unknown1, Unknown1> f) {}
void G2(Func<Unknown2, Unknown2> f) {}
void F()
{
G1(a => 1);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<Unknown1, Unknown1> f) {}
void G2(Func<Unknown2, Unknown2> f) {}
void F()
{
G2(a => 2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", "lambda"));
}
[Fact]
public void Lambdas_Update_DelegateType1()
{
var src1 = @"
using System;
delegate int D1(int a);
delegate int D2(int a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
delegate int D1(int a);
delegate int D2(int a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_SourceType1()
{
var src1 = @"
using System;
delegate C D1(C a);
delegate C D2(C a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
delegate C D1(C a);
delegate C D2(C a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_SourceType2()
{
var src1 = @"
using System;
delegate C D1(C a);
delegate B D2(B a);
class B { }
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
delegate C D1(C a);
delegate B D2(B a);
class B { }
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_SourceTypeAndMetadataType1()
{
var src1 = @"
namespace System
{
delegate string D1(string a);
delegate String D2(String a);
class String { }
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1(a => a);
}
}
}
";
var src2 = @"
namespace System
{
delegate string D1(string a);
delegate String D2(String a);
class String { }
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2(a => a);
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Generic1()
{
var src1 = @"
delegate T D1<S, T>(S a, T b);
delegate T D2<S, T>(T a, S b);
class C
{
void G1(D1<int, int> f) {}
void G2(D2<int, int> f) {}
void F()
{
G1((a, b) => a + b);
}
}
";
var src2 = @"
delegate T D1<S, T>(S a, T b);
delegate T D2<S, T>(T a, S b);
class C
{
void G1(D1<int, int> f) {}
void G2(D2<int, int> f) {}
void F()
{
G2((a, b) => a + b);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Generic2()
{
var src1 = @"
delegate int D1<S, T>(S a, T b);
delegate int D2<S, T>(T a, S b);
class C
{
void G1(D1<int, int> f) {}
void G2(D2<int, string> f) {}
void F()
{
G1((a, b) => 1);
}
}
";
var src2 = @"
delegate int D1<S, T>(S a, T b);
delegate int D2<S, T>(T a, S b);
class C
{
void G1(D1<int, int> f) {}
void G2(D2<int, string> f) {}
void F()
{
G2((a, b) => 1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_CapturedParameters1()
{
var src1 = @"
using System;
class C
{
void F(int x1)
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => x1 + a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F(int x1)
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => x1 + a2 + 1);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")]
public void Lambdas_Update_CapturedParameters2()
{
var src1 = @"
using System;
class C
{
void F(int x1)
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => x1 + a2);
return a1;
});
var f3 = new Func<int, int, int>((a1, a2) =>
{
var f4 = new Func<int, int>(a3 => x1 + a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F(int x1)
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => x1 + a2 + 1);
return a1;
});
var f3 = new Func<int, int, int>((a1, a2) =>
{
var f4 = new Func<int, int>(a3 => x1 + a2 + 1);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_CeaseCapture_Closure1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => y + a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a2);
return a1 + y;
});
}
}
";
var edits = GetTopEdits(src1, src2);
// y is no longer captured in f2
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a2", "y", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_CeaseCapture_IndexerParameter1()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2);
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_CeaseCapture_IndexerParameter2()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_CeaseCapture_MethodParameter1()
{
var src1 = @"
using System;
class C
{
void F(int a1, int a2)
{
var f2 = new Func<int, int>(a3 => a1 + a2);
}
}
";
var src2 = @"
using System;
class C
{
void F(int a1, int a2)
{
var f2 = new Func<int, int>(a3 => a1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2"));
}
[Fact]
public void Lambdas_Update_CeaseCapture_MethodParameter2()
{
var src1 = @"
using System;
class C
{
Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2);
}
";
var src2 = @"
using System;
class C
{
Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2"));
}
[Fact]
public void Lambdas_Update_CeaseCapture_LambdaParameter1()
{
var src1 = @"
using System;
class C
{
void F()
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => a1 + a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => a2);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")]
public void Lambdas_Update_CeaseCapture_SetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int D
{
get { return 0; }
set { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var src2 = @"
using System;
class C
{
int D
{
get { return 0; }
set { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value"));
}
[Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")]
public void Lambdas_Update_CeaseCapture_IndexerSetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var src2 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value"));
}
[Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")]
public void Lambdas_Update_CeaseCapture_EventAdderValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { new Action(() => { Console.Write(value); }).Invoke(); }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value"));
}
[Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")]
public void Lambdas_Update_CeaseCapture_EventRemoverValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value"));
}
[Fact]
public void Lambdas_Update_DeleteCapture1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => y + a2);
return y;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{ // error
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a2);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
// y is no longer captured in f2
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y").WithFirstLine("{ // error"));
}
[Fact]
public void Lambdas_Update_Capturing_IndexerGetterParameter1()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2);
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_Capturing_IndexerGetterParameter2()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_Capturing_IndexerSetterParameter1()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a2); } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a1 + a2); } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_Capturing_IndexerSetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { }
}
}
";
var src2 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "set", "value"));
}
[Fact]
public void Lambdas_Update_Capturing_EventAdderValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "remove", "value"));
}
[Fact]
public void Lambdas_Update_Capturing_EventRemoverValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "remove", "value"));
}
[Fact]
public void Lambdas_Update_Capturing_MethodParameter1()
{
var src1 = @"
using System;
class C
{
void F(int a1, int a2)
{
var f2 = new Func<int, int>(a3 => a1);
}
}
";
var src2 = @"
using System;
class C
{
void F(int a1, int a2)
{
var f2 = new Func<int, int>(a3 => a1 + a2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2"));
}
[Fact]
public void Lambdas_Update_Capturing_MethodParameter2()
{
var src1 = @"
using System;
class C
{
Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1);
}
";
var src2 = @"
using System;
class C
{
Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2"));
}
[Fact]
public void Lambdas_Update_Capturing_LambdaParameter1()
{
var src1 = @"
using System;
class C
{
void F()
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => a1 + a2);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_StaticToThisOnly1()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
var f = new Func<int, int>(a => a);
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
var f = new Func<int, int>(a => a + x);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact]
public void Lambdas_Update_StaticToThisOnly_Partial()
{
var src1 = @"
using System;
partial class C
{
int x = 1;
partial void F(); // def
}
partial class C
{
partial void F() // impl
{
var f = new Func<int, int>(a => a);
}
}
";
var src2 = @"
using System;
partial class C
{
int x = 1;
partial void F(); // def
}
partial class C
{
partial void F() // impl
{
var f = new Func<int, int>(a => a + x);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this").WithFirstLine("partial void F() // impl"));
}
[Fact]
public void Lambdas_Update_StaticToThisOnly3()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
var f1 = new Func<int, int>(a1 => a1);
var f2 = new Func<int, int>(a2 => a2 + x);
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
var f1 = new Func<int, int>(a1 => a1 + x);
var f2 = new Func<int, int>(a2 => a2 + x);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a1", "this", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_StaticToClosure1()
{
var src1 = @"
using System;
class C
{
void F()
{
int x = 1;
var f1 = new Func<int, int>(a1 => a1);
var f2 = new Func<int, int>(a2 => a2 + x);
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int x = 1;
var f1 = new Func<int, int>(a1 =>
{
return a1 +
x+ // 1
x; // 2
});
var f2 = new Func<int, int>(a2 => a2 + x);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x+ // 1"),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x; // 2"));
}
[Fact]
public void Lambdas_Update_ThisOnlyToClosure1()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 => a1 + x);
var f2 = new Func<int, int>(a2 => a2 + x + y);
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 => a1 + x + y);
var f2 = new Func<int, int>(a2 => a2 + x + y);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Nested1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a2 + y);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a2 + y);
return a1 + y;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Nested2()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a1 + a2);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
// TODO: better diagnostics - identify a1 that causes the capture vs. a1 that doesn't
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1").WithFirstLine("var f1 = new Func<int, int>(a1 =>"));
}
[Fact]
public void Lambdas_Update_Accessing_Closure1()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
int x0 = 0, y0 = 0;
G(a => x0);
G(a => y0);
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
int x0 = 0, y0 = 0;
G(a => x0);
G(a => y0 + x0);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Accessing_Closure2()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x + x0);
G(a => x0);
G(a => y0);
G(a => x1);
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x); // error: disconnecting previously connected closures
G(a => x0);
G(a => y0);
G(a => x1);
}
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "x0", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Accessing_Closure3()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x);
G(a => x0);
G(a => y0);
G(a => x1);
G(a => y1);
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x);
G(a => x0);
G(a => y0);
G(a => x1);
G(a => y1 + x0); // error: connecting previously disconnected closures
}
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Accessing_Closure4()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x + x0);
G(a => x0);
G(a => y0);
G(a => x1);
G(a => y1);
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x); // error: disconnecting previously connected closures
G(a => x0);
G(a => y0);
G(a => x1);
G(a => y1 + x0); // error: connecting previously disconnected closures
}
}
}
}
";
var edits = GetTopEdits(src1, src2);
// TODO: "a => x + x0" is matched with "a => y1 + x0", hence we report more errors.
// Including statement distance when matching would help.
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y1", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures"),
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures"));
}
[Fact]
public void Lambdas_Update_Accessing_Closure_NestedLambdas()
{
var src1 = @"
using System;
class C
{
void G(Func<int, Func<int, int>> f) {}
void F()
{
{ int x0 = 0; // Group #0
{ int x1 = 0; // Group #1
G(a => b => x0);
G(a => b => x1);
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, Func<int, int>> f) {}
void F()
{
{ int x0 = 0; // Group #0
{ int x1 = 0; // Group #1
G(a => b => x0);
G(a => b => x1);
G(a => b => x0); // ok
G(a => b => x1); // ok
G(a => b => x0 + x1); // error
}
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"));
}
[Fact]
public void Lambdas_RenameCapturedLocal()
{
var src1 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
int x = 1;
Func<int> f = () => x;
}
}";
var src2 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
int X = 1;
Func<int> f = () => X;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X"));
}
[Fact]
public void Lambdas_RenameCapturedParameter()
{
var src1 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main(int x)
{
Func<int> f = () => x;
}
}";
var src2 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main(int X)
{
Func<int> f = () => X;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Lambdas_Parameter_To_Discard1()
{
var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);";
var src2 = "var x = new System.Func<int, int, int>((a, _) => 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [b]@45 -> [_]@45");
GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true));
}
[Fact]
public void Lambdas_Parameter_To_Discard2()
{
var src1 = "var x = new System.Func<int, int, int>((int a, int b) => 1);";
var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@42 -> [_]@42",
"Update [int b]@49 -> [_]@45");
GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true));
}
[Fact]
public void Lambdas_Parameter_To_Discard3()
{
var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);";
var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@42 -> [_]@42",
"Update [b]@45 -> [_]@45");
GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true));
}
#endregion
#region Local Functions
[Fact]
public void LocalFunctions_InExpressionStatement()
{
var src1 = "F(a => a, b => b);";
var src2 = "int x(int a) => a + 1; F(b => b, x);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [a => a]@4 -> [int x(int a) => a + 1;]@2",
"Move [a => a]@4 -> @2",
"Update [F(a => a, b => b);]@2 -> [F(b => b, x);]@25",
"Insert [(int a)]@7",
"Insert [int a]@8",
"Delete [a]@4");
}
[Fact]
public void LocalFunctions_ReorderAndUpdate()
{
var src1 = "int x(int a) => a; int y(int b) => b;";
var src2 = "int y(int b) => b; int x(int a) => a + 1;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int y(int b) => b;]@21 -> @2",
"Update [int x(int a) => a;]@2 -> [int x(int a) => a + 1;]@21");
}
[Fact]
public void LocalFunctions_InWhile()
{
var src1 = "do { /*1*/ } while (F(x));int x(int a) => a + 1;";
var src2 = "while (F(a => a)) { /*1*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [while (F(a => a)) { /*1*/ }]@2",
"Update [int x(int a) => a + 1;]@28 -> [a => a]@11",
"Move [int x(int a) => a + 1;]@28 -> @11",
"Move [{ /*1*/ }]@5 -> @20",
"Insert [a]@11",
"Delete [do { /*1*/ } while (F(x));]@2",
"Delete [(int a)]@33",
"Delete [int a]@34");
}
[Fact]
public void LocalFunctions_InLocalFunction_NoChangeInSignature()
{
var src1 = "int x() { int y(int a) => a; return y(b); }";
var src2 = "int x() { int y() => c; return y(); }";
var edits = GetMethodEdits(src1, src2);
// no changes to the method were made, only within the outer local function body:
edits.VerifyEdits();
}
[Fact]
public void LocalFunctions_InLocalFunction_ChangeInSignature()
{
var src1 = "int x() { int y(int a) => a; return y(b); }";
var src2 = "int x(int z) { int y() => c; return y(); }";
var edits = GetMethodEdits(src1, src2);
// changes were made to the outer local function signature:
edits.VerifyEdits("Insert [int z]@8");
}
[Fact]
public void LocalFunctions_InLambda()
{
var src1 = "F(() => { int y(int a) => a; G(y); });";
var src2 = "F(q => { G(() => y); });";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [() => { int y(int a) => a; G(y); }]@4 -> [q => { G(() => y); }]@4",
"Insert [q]@4",
"Delete [()]@4");
}
[Fact]
public void LocalFunctions_Update_ParameterRefness_NoBodyChange()
{
var src1 = @"void f(ref int a) => a = 1;";
var src2 = @"void f(out int a) => a = 1;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [ref int a]@9 -> [out int a]@9");
}
[Fact]
public void LocalFunctions_Insert_Static_Top()
{
var src1 = @"
using System;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(int a) => a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_Insert_Static_Nested_ExpressionBodies()
{
var src1 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) => a;
G(localF);
}
}
";
var src2 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) => a;
int localG(int a) => G(localF) + a;
G(localG);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_Insert_Static_Nested_BlockBodies()
{
var src1 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) { return a; }
G(localF);
}
}
";
var src2 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) { return a; }
int localG(int a) { return G(localF) + a; }
G(localG);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_LocalFunction_Replace_Lambda()
{
var src1 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
G(a => a);
}
}
";
var src2 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) { return a; }
G(localF);
}
}
";
var edits = GetTopEdits(src1, src2);
// To be removed when we will enable EnC for local functions
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "localF", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Lambda_Replace_LocalFunction()
{
var src1 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) { return a; }
G(localF);
}
}
";
var src2 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
G(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "a", CSharpFeaturesResources.lambda));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_ThisOnly_Top1()
{
var src1 = @"
using System;
class C
{
int x = 0;
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
void F()
{
int G(int a) => x;
}
}
";
var edits = GetTopEdits(src1, src2);
// TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291"), WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_ThisOnly_Top2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
int y = 1;
{
int x = 2;
int f1(int a) => y;
}
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
int y = 1;
{
int x = 2;
var f2 = from a in new[] { 1 } select a + y;
var f3 = from a in new[] { 1 } where x > 0 select a;
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "x", "x"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_ThisOnly_Nested1()
{
var src1 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
int f(int a) => a;
G(f);
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
int f(int a) => x;
int g(int a) => G(f);
G(g);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_ThisOnly_Nested2()
{
var src1 = @"
using System;
class C
{
int x = 0;
void F()
{
int f1(int a)
{
int f2(int b)
{
return b;
};
return a;
};
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
void F()
{
int f1(int a)
{
int f2(int b)
{
return b;
};
int f3(int c)
{
return c + x;
};
return a;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_InsertAndDelete_Scopes1()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0, y = 0; // Group #0
void F()
{
int x0 = 0, y0 = 0; // Group #1
{ int x1 = 0, y1 = 0; // Group #2
{ int x2 = 0, y2 = 0; // Group #1
{ int x3 = 0, y3 = 0; // Group #2
int f1(int a) => x3 + x1;
int f2(int a) => x0 + y0 + x2;
int f3(int a) => x;
}
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0, y = 0; // Group #0
void F()
{
int x0 = 0, y0 = 0; // Group #1
{ int x1 = 0, y1 = 0; // Group #2
{ int x2 = 0, y2 = 0; // Group #1
{ int x3 = 0, y3 = 0; // Group #2
int f1(int a) => x3 + x1;
int f2(int a) => x0 + y0 + x2;
int f3(int a) => x;
int f4(int a) => x; // OK
int f5(int a) => x0 + y0; // OK
int f6(int a) => x1 + y0; // error - connecting Group #1 and Group #2
int f7(int a) => x3 + x1; // error - multi-scope (conservative)
int f8(int a) => x + y0; // error - connecting Group #0 and Group #1
int f9(int a) => x + x3; // error - connecting Group #0 and Group #2
}
}
}
}
}
";
var insert = GetTopEdits(src1, src2);
insert.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3"));
var delete = GetTopEdits(src2, src1);
delete.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_ForEach1()
{
var src1 = @"
using System;
class C
{
void F()
{
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
int f0(int a) => x0;
int f1(int a) => x1;
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
int f0(int a) => x0;
int f1(int a) => x1;
int f2(int a) => x0 + x1; // error: connecting previously disconnected closures
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_Switch1()
{
var src1 = @"
using System;
class C
{
bool G(Func<int> f) => true;
int a = 1;
void F()
{
int x2 = 1;
int f2() => x2;
switch (a)
{
case 1:
int x0 = 1;
int f0() => x0;
break;
case 2:
int x1 = 1;
int f1() => x1;
break;
}
}
}
";
var src2 = @"
using System;
class C
{
bool G(Func<int> f) => true;
int a = 1;
void F()
{
int x2 = 1;
int f2() => x2;
switch (a)
{
case 1:
int x0 = 1;
int f0() => x0;
goto case 2;
case 2:
int x1 = 1;
int f1() => x1;
goto default;
default:
x0 = 1;
x1 = 2;
int f01() => x0 + x1; // ok
int f02() => x0 + x2; // error
break;
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.local_function, "x2", "x0"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_Catch1()
{
var src1 = @"
using System;
class C
{
static void F()
{
try
{
}
catch (Exception x0)
{
int x1 = 1;
int f0() => x0;
int f1() => x1;
}
}
}
";
var src2 = @"
using System;
class C
{
static void F()
{
try
{
}
catch (Exception x0)
{
int x1 = 1;
int f0() => x0;
int f1() => x1;
int f00() => x0; //ok
int f01() => F(x0, x1); //error
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1"));
}
[Fact]
public void LocalFunctions_Insert_NotSupported()
{
var src1 = @"
using System;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
void M()
{
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
activeStatements: ActiveStatementsDescription.Empty,
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "M", FeaturesResources.local_function));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_This()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
int f(int a) => a + x;
}
}
";
var src2 = @"
using System;
class C
{
int x;
void F()
{
int f(int a) => a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this"));
}
[Fact]
public void LocalFunctions_Update_Signature1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
long f(long a) => a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature2()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(int a, int b) => a + b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature3()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
long f(int a) => a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature_ReturnType1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) { return 1; }
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
void f(int a) { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature_BodySyntaxOnly()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
int f(int a) { return a; }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_Update_Signature_ParameterName1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) => 1;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(int b) => 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_Update_Signature_ParameterRefness1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(ref int a) => 1;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(int a) => 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature_ParameterRefness2()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(out int a) => 1;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(ref int a) => 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature_ParameterRefness3()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(ref int a) => 1;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(out int a) => 1;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Signature_SemanticErrors()
{
var src1 = @"
using System;
class C
{
void F()
{
Unknown f(Unknown a) => 1;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
Unknown f(Unknown a) => 2;
}
}
";
var edits = GetTopEdits(src1, src2);
// There are semantics errors in the case. The errors are captured during the emit execution.
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_Update_CapturedParameters1()
{
var src1 = @"
using System;
class C
{
void F(int x1)
{
int f1(int a1, int a2)
{
int f2(int a3) => x1 + a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F(int x1)
{
int f1(int a1, int a2)
{
int f2(int a3) => x1 + a2 + 1;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")]
public void LocalFunctions_Update_CapturedParameters2()
{
var src1 = @"
using System;
class C
{
void F(int x1)
{
int f1(int a1, int a2)
{
int f2(int a3) => x1 + a2;
return a1;
};
int f3(int a1, int a2)
{
int f4(int a3) => x1 + a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F(int x1)
{
int f1(int a1, int a2)
{
int f2(int a3) => x1 + a2 + 1;
return a1;
};
int f3(int a1, int a2)
{
int f4(int a3) => x1 + a2 + 1;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_Closure1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => y + a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => a2;
return a1 + y;
};
}
}
";
var edits = GetTopEdits(src1, src2);
// y is no longer captured in f2
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "f2", "y", CSharpFeaturesResources.local_function));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_IndexerParameter()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_MethodParameter1()
{
var src1 = @"
using System;
class C
{
void F(int a1, int a2)
{
int f2(int a3) => a1 + a2;
}
}
";
var src2 = @"
using System;
class C
{
void F(int a1, int a2)
{
int f2(int a3) => a1;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_LambdaParameter1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f1(int a1, int a2)
{
int f2(int a3) => a1 + a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f1(int a1, int a2)
{
int f2(int a3) => a2;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "int f1(int a1, int a2)\r\n {\r\n int f2(int a3) => a2;\r\n return a1;\r\n };\r\n ", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_SetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int D
{
get { return 0; }
set { void f() { Console.Write(value); } f(); }
}
}
";
var src2 = @"
using System;
class C
{
int D
{
get { return 0; }
set { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_IndexerSetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { void f() { Console.Write(value); } f(); }
}
}
";
var src2 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_EventAdderValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { void f() { Console.Write(value); } f(); }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_EventRemoverValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { void f() { Console.Write(value); } f(); }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_DeleteCapture1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => y + a2;
return y;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{ // error
int f1(int a1)
{
int f2(int a2) => a2;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_IndexerGetterParameter2()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_IndexerSetterParameter1()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a2; } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a1 + a2; } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_IndexerSetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { }
}
}
";
var src2 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { void f() { Console.Write(value); } f(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "set", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_EventAdderValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { void f() { Console.Write(value); } f(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "remove", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_EventRemoverValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { void f() { Console.Write(value); } f(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "remove", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_MethodParameter1()
{
var src1 = @"
using System;
class C
{
void F(int a1, int a2)
{
int f2(int a3) => a1;
}
}
";
var src2 = @"
using System;
class C
{
void F(int a1, int a2)
{
int f2(int a3) => a1 + a2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_LambdaParameter1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f1(int a1, int a2)
{
int f2(int a3) => a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f1(int a1, int a2)
{
int f2(int a3) => a1 + a2;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_StaticToThisOnly1()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
int f(int a) => a + x;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_StaticToThisOnly_Partial()
{
var src1 = @"
using System;
partial class C
{
int x = 1;
partial void F(); // def
}
partial class C
{
partial void F() // impl
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
partial class C
{
int x = 1;
partial void F(); // def
}
partial class C
{
partial void F() // impl
{
int f(int a) => a + x;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_StaticToThisOnly3()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
int f1(int a1) => a1;
int f2(int a2) => a2 + x;
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
int f1(int a1) => a1 + x;
int f2(int a2) => a2 + x;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "f1", "this", CSharpFeaturesResources.local_function));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_StaticToClosure1()
{
var src1 = @"
using System;
class C
{
void F()
{
int x = 1;
int f1(int a1) => a1;
int f2(int a2) => a2 + x;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int x = 1;
int f1(int a1)
{
return a1 +
x+ // 1
x; // 2
};
int f2(int a2) => a2 + x;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_ThisOnlyToClosure1()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
int y = 1;
int f1(int a1) => a1 + x;
int f2(int a2) => a2 + x + y;
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
int y = 1;
int f1(int a1) => a1 + x + y;
int f2(int a2) => a2 + x + y;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Nested1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => a2 + y;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => a2 + y;
return a1 + y;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Nested2()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => a1 + a2;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_RenameCapturedLocal()
{
var src1 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
int x = 1;
int f() => x;
}
}";
var src2 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
int X = 1;
int f() => X;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X"));
}
[Fact]
public void LocalFunctions_RenameCapturedParameter()
{
var src1 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main(int x)
{
int f() => x;
}
}";
var src2 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main(int X)
{
int f() => X;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void LocalFunction_In_Parameter_InsertWhole()
{
var src1 = @"class Test { void M() { } }";
var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { }]@13 -> [void M() { void local(in int b) { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_In_Parameter_InsertParameter()
{
var src1 = @"class Test { void M() { void local() { throw null; } } }";
var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { void local() { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunction_In_Parameter_Update()
{
var src1 = @"class Test { void M() { void local(int b) { throw null; } } }";
var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { void local(int b) { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ReadOnlyRef_ReturnType_Insert()
{
var src1 = @"class Test { void M() { } }";
var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_ReadOnlyRef_ReturnType_Update()
{
var src1 = @"class Test { void M() { int local() { throw null; } } }";
var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { int local() { throw null; } }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "local", CSharpFeaturesResources.local_function));
}
[WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")]
[Fact]
public void LocalFunction_AddToInterfaceMethod()
{
var src1 = @"
using System;
interface I
{
static int X = M(() => 1);
static int M() => 1;
static void F()
{
void g() { }
}
}
";
var src2 = @"
using System;
interface I
{
static int X = M(() => { void f3() {} return 2; });
static int M() => 1;
static void F()
{
int f1() => 1;
f1();
void g() { void f2() {} f2(); }
var l = new Func<int>(() => 1);
l();
}
}
";
var edits = GetTopEdits(src1, src2);
// lambdas are ok as they are emitted to a nested type
edits.VerifySemanticDiagnostics(
targetFrameworks: new[] { TargetFramework.NetCoreApp },
expectedDiagnostics: new[]
{
Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f1"),
Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f2"),
Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f3")
});
}
[Fact]
public void LocalFunction_AddStatic()
{
var src1 = @"class Test { void M() { int local() { throw null; } } }";
var src2 = @"class Test { void M() { static int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { int local() { throw null; } }]@13 -> [void M() { static int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_RemoveStatic()
{
var src1 = @"class Test { void M() { static int local() { throw null; } } }";
var src2 = @"class Test { void M() { int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { static int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_AddUnsafe()
{
var src1 = @"class Test { void M() { int local() { throw null; } } }";
var src2 = @"class Test { void M() { unsafe int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { int local() { throw null; } }]@13 -> [void M() { unsafe int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_RemoveUnsafe()
{
var src1 = @"class Test { void M() { unsafe int local() { throw null; } } }";
var src2 = @"class Test { void M() { int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { unsafe int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
[WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")]
public void LocalFunction_AddAsync()
{
var src1 = @"class Test { void M() { Task<int> local() => throw null; } }";
var src2 = @"class Test { void M() { async Task<int> local() => throw null; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
[WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")]
public void LocalFunction_RemoveAsync()
{
var src1 = @"class Test { void M() { async int local() { throw null; } } }";
var src2 = @"class Test { void M() { int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "local", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_AddAttribute()
{
var src1 = "void L() { }";
var src2 = "[A]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [void L() { }]@2 -> [[A]void L() { }]@2");
// Get top edits so we can validate rude edits
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_RemoveAttribute()
{
var src1 = "[A]void L() { }";
var src2 = "void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]void L() { }]@2 -> [void L() { }]@2");
// Get top edits so we can validate rude edits
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ReorderAttribute()
{
var src1 = "[A, B]void L() { }";
var src2 = "[B, A]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[A, B]void L() { }]@2 -> [[B, A]void L() { }]@2");
// Get top edits so we can validate rude edits
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_CombineAttributeLists()
{
var src1 = "[A][B]void L() { }";
var src2 = "[A, B]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[A][B]void L() { }]@2 -> [[A, B]void L() { }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_SplitAttributeLists()
{
var src1 = "[A, B]void L() { }";
var src2 = "[A][B]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[A, B]void L() { }]@2 -> [[A][B]void L() { }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_ChangeAttributeListTarget1()
{
var src1 = "[return: A]void L() { }";
var src2 = "[A]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[return: A]void L() { }]@2 -> [[A]void L() { }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ChangeAttributeListTarget2()
{
var src1 = "[A]void L() { }";
var src2 = "[return: A]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[A]void L() { }]@2 -> [[return: A]void L() { }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ReturnType_AddAttribute()
{
var src1 = "int L() { return 1; }";
var src2 = "[return: A]int L() { return 1; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [int L() { return 1; }]@2 -> [[return: A]int L() { return 1; }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ReturnType_RemoveAttribute()
{
var src1 = "[return: A]int L() { return 1; }";
var src2 = "int L() { return 1; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[return: A]int L() { return 1; }]@2 -> [int L() { return 1; }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ReturnType_ReorderAttribute()
{
var src1 = "[return: A, B]int L() { return 1; }";
var src2 = "[return: B, A]int L() { return 1; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[return: A, B]int L() { return 1; }]@2 -> [[return: B, A]int L() { return 1; }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_Parameter_AddAttribute()
{
var src1 = "void L(int i) { }";
var src2 = "void L([A]int i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [int i]@9 -> [[A]int i]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter));
}
[Fact]
public void LocalFunction_Parameter_RemoveAttribute()
{
var src1 = "void L([A]int i) { }";
var src2 = "void L(int i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]int i]@9 -> [int i]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter));
}
[Fact]
public void LocalFunction_Parameter_ReorderAttribute()
{
var src1 = "void L([A, B]int i) { }";
var src2 = "void L([B, A]int i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[A, B]int i]@9 -> [[B, A]int i]@9");
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_TypeParameter_AddAttribute()
{
var src1 = "void L<T>(T i) { }";
var src2 = "void L<[A] T>(T i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@9 -> [[A] T]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter));
}
[Fact]
public void LocalFunction_TypeParameter_RemoveAttribute()
{
var src1 = "void L<[A] T>(T i) { }";
var src2 = "void L<T>(T i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[A] T]@9 -> [T]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter));
}
[Fact]
public void LocalFunction_TypeParameter_ReorderAttribute()
{
var src1 = "void L<[A, B] T>(T i) { }";
var src2 = "void L<[B, A] T>(T i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[A, B] T]@9 -> [[B, A] T]@9");
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunctions_TypeParameter_Insert1()
{
var src1 = @"void L() {}";
var src2 = @"void L<A>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [<A>]@8",
"Insert [A]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Insert2()
{
var src1 = @"void L<A>() {}";
var src2 = @"void L<A,B>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [<A>]@8 -> [<A,B>]@8",
"Insert [B]@11");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Delete1()
{
var src1 = @"void L<A>() {}";
var src2 = @"void L() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [<A>]@8",
"Delete [A]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Delete2()
{
var src1 = @"void L<A,B>() {}";
var src2 = @"void L<B>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [<A,B>]@8 -> [<B>]@8",
"Delete [A]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Update()
{
var src1 = @"void L<A>() {}";
var src2 = @"void L<B>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [A]@9 -> [B]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Theory]
[InlineData("Enum", "Delegate")]
[InlineData("IDisposable", "IDisposable, new()")]
public void LocalFunctions_TypeParameter_Constraint_Clause_Update(string oldConstraint, string newConstraint)
{
var src1 = "void L<A>() where A : " + oldConstraint + " {}";
var src2 = "void L<A>() where A : " + newConstraint + " {}";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [where A : " + oldConstraint + "]@14 -> [where A : " + newConstraint + "]@14");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Theory]
[InlineData("nonnull")]
[InlineData("struct")]
[InlineData("class")]
[InlineData("new()")]
[InlineData("unmanaged")]
[InlineData("System.IDisposable")]
[InlineData("System.Delegate")]
public void LocalFunctions_TypeParameter_Constraint_Clause_Delete(string oldConstraint)
{
var src1 = "void L<A>() where A : " + oldConstraint + " {}";
var src2 = "void L<A>() {}";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [where A : " + oldConstraint + "]@14");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Constraint_Clause_Add()
{
var src1 = "void L<A,B>() where A : new() {}";
var src2 = "void L<A,B>() where A : new() where B : System.IDisposable {}";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [where B : System.IDisposable]@32");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Reorder()
{
var src1 = @"void L<A,B>() {}";
var src2 = @"void L<B,A>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@11 -> @9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_ReorderAndUpdate()
{
var src1 = @"void L<A,B>() {}";
var src2 = @"void L<B,C>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@11 -> @9",
"Update [A]@9 -> [C]@11");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
#endregion
#region Queries
[Fact]
public void Queries_Update_Signature_Select1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1.0} select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause));
}
[Fact]
public void Queries_Update_Signature_Select2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} select a.ToString();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause));
}
[Fact]
public void Queries_Update_Signature_From1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} from b in new[] {2} select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from long a in new[] {1} from b in new[] {2} select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "from", CSharpFeaturesResources.from_clause));
}
[Fact]
public void Queries_Update_Signature_From2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from System.Int64 a in new[] {1} from b in new[] {2} select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from long a in new[] {1} from b in new[] {2} select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_Update_Signature_From3()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} from b in new[] {2} select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new List<int>() from b in new List<int>() select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_Update_Signature_Let1()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} let b = 1 select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} let b = 1.0 select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "let", CSharpFeaturesResources.let_clause));
}
[Fact]
public void Queries_Update_Signature_OrderBy1()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} orderby a + 1.0 descending, a + 2 ascending select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 1.0 descending", CSharpFeaturesResources.orderby_clause));
}
[Fact]
public void Queries_Update_Signature_OrderBy2()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} orderby a + 1 descending, a + 2.0 ascending select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 2.0 ascending", CSharpFeaturesResources.orderby_clause));
}
[Fact]
public void Queries_Update_Signature_Join1()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a equals b select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1.0} on a equals b select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause));
}
[Fact]
public void Queries_Update_Signature_Join2()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a equals b select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join byte b in new[] {1} on a equals b select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause));
}
[Fact]
public void Queries_Update_Signature_Join3()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a + 1 equals b select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a + 1.0 equals b select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause));
}
[Fact]
public void Queries_Update_Signature_Join4()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a equals b + 1 select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a equals b + 1.0 select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause));
}
[Fact]
public void Queries_Update_Signature_GroupBy1()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1 by a into z select z;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1.0 by a into z select z;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause));
}
[Fact]
public void Queries_Update_Signature_GroupBy2()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} group a by a into z select z;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} group a by a + 1.0 into z select z;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause));
}
[Fact]
public void Queries_Update_Signature_GroupBy_MatchingErrorTypes()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
Unknown G1(int a) => null;
Unknown G2(int a) => null;
void F()
{
var result = from a in new[] {1} group G1(a) by a into z select z;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
Unknown G1(int a) => null;
Unknown G2(int a) => null;
void F()
{
var result = from a in new[] {1} group G2(a) by a into z select z;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_Update_Signature_GroupBy_NonMatchingErrorTypes()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
Unknown1 G1(int a) => null;
Unknown2 G2(int a) => null;
void F()
{
var result = from a in new[] {1} group G1(a) by a into z select z;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
Unknown1 G1(int a) => null;
Unknown2 G2(int a) => null;
void F()
{
var result = from a in new[] {1} group G2(a) by a into z select z;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause));
}
[Fact]
public void Queries_FromSelect_Update1()
{
var src1 = "F(from a in b from x in y select c);";
var src2 = "F(from a in c from x in z select c + 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [from a in b]@4 -> [from a in c]@4",
"Update [from x in y]@16 -> [from x in z]@16",
"Update [select c]@28 -> [select c + 1]@28");
}
[Fact]
public void Queries_FromSelect_Update2()
{
var src1 = "F(from a in b from x in y select c);";
var src2 = "F(from a in b from x in z select c);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [from x in y]@16 -> [from x in z]@16");
}
[Fact]
public void Queries_FromSelect_Update3()
{
var src1 = "F(from a in await b from x in y select c);";
var src2 = "F(from a in await c from x in y select c);";
var edits = GetMethodEdits(src1, src2, MethodKind.Async);
edits.VerifyEdits(
"Update [await b]@34 -> [await c]@34");
}
[Fact]
public void Queries_Select_Reduced1()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} where a > 0 select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} where a > 0 select a + 1;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_Select_Reduced2()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} where a > 0 select a + 1;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} where a > 0 select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_FromSelect_Delete()
{
var src1 = "F(from a in b from c in d select a + c);";
var src2 = "F(from a in b select c + 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [select a + c]@28 -> [select c + 1]@16",
"Delete [from c in d]@16");
}
[Fact]
public void Queries_JoinInto_Update()
{
var src1 = "F(from a in b join b in c on a equals b into g1 select g1);";
var src2 = "F(from a in b join b in c on a equals b into g2 select g2);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [select g1]@50 -> [select g2]@50",
"Update [into g1]@42 -> [into g2]@42");
}
[Fact]
public void Queries_JoinIn_Update()
{
var src1 = "F(from a in b join b in await A(1) on a equals b select g);";
var src2 = "F(from a in b join b in await A(2) on a equals b select g);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [await A(1)]@26 -> [await A(2)]@26");
}
[Fact]
public void Queries_GroupBy_Update()
{
var src1 = "F(from a in b group a by a.x into g select g);";
var src2 = "F(from a in b group z by z.y into h select h);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [group a by a.x]@17 -> [group z by z.y]@17",
"Update [into g select g]@32 -> [into h select h]@32",
"Update [select g]@40 -> [select h]@40");
}
[Fact]
public void Queries_OrderBy_Reorder()
{
var src1 = "F(from a in b orderby a.x, a.b descending, a.c ascending select a.d);";
var src2 = "F(from a in b orderby a.x, a.c ascending, a.b descending select a.d);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [a.c ascending]@46 -> @30");
}
[Fact]
public void Queries_GroupBy_Reduced1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a by a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1.0 by a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause));
}
[Fact]
public void Queries_GroupBy_Reduced2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a by a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1 by a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_GroupBy_Reduced3()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1.0 by a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a by a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause));
}
[Fact]
public void Queries_GroupBy_Reduced4()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1 by a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a by a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_OrderBy_Continuation_Update()
{
var src1 = "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);";
var src2 = "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);";
var edits = GetMethodEdits(src1, src2);
var actual = ToMatchingPairs(edits.Match);
var expected = new MatchingPairs
{
{ "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);", "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);" },
{ "from a in b", "from a in b" },
{ "orderby a.x, a.b descending select a.d into z orderby a.c ascending select z", "orderby a.x, a.c ascending select a.d into z orderby a.b descending select z" },
{ "orderby a.x, a.b descending", "orderby a.x, a.c ascending" },
{ "a.x", "a.x" },
{ "a.b descending", "a.c ascending" },
{ "select a.d", "select a.d" },
{ "into z orderby a.c ascending select z", "into z orderby a.b descending select z" },
{ "orderby a.c ascending select z", "orderby a.b descending select z" },
{ "orderby a.c ascending", "orderby a.b descending" },
{ "a.c ascending", "a.b descending" },
{ "select z", "select z" }
};
expected.AssertEqual(actual);
edits.VerifyEdits(
"Update [a.b descending]@30 -> [a.c ascending]@30",
"Update [a.c ascending]@74 -> [a.b descending]@73");
}
[Fact]
public void Queries_CapturedTransparentIdentifiers_FromClause1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a) > 0
where Z(() => b) > 0
where Z(() => a) > 0
where Z(() => b) > 0
select a;
}
}";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a) > 1 // update
where Z(() => b) > 2 // update
where Z(() => a) > 3 // update
where Z(() => b) > 4 // update
select a;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_CapturedTransparentIdentifiers_LetClause1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
let b = Z(() => a)
select a + b;
}
}";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
let b = Z(() => a + 1)
select a - b;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_CapturedTransparentIdentifiers_JoinClause1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g
select Z(() => g.First());
}
}";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g
select Z(() => g.Last());
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_CeaseCapturingTransparentIdentifiers1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a + b) > 0
select a;
}
}";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a + 1) > 0
select a;
}
}";
var edits = GetTopEdits(src1, src2);
// TODO: better location (the variable, not the from clause)
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "from b in new[] { 2 }", "b"));
}
[Fact]
public void Queries_CapturingTransparentIdentifiers1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a + 1) > 0
select a;
}
}";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a + b) > 0
select a;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "b", "b"));
}
[Fact]
public void Queries_AccessingCapturedTransparentIdentifier1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select 1;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_AccessingCapturedTransparentIdentifier2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 1 }
where Z(() => a) > 0
select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 1 }
where Z(() => a) > 0
select a + b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause));
}
[Fact]
public void Queries_AccessingCapturedTransparentIdentifier3()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select Z(() => 1);
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select Z(() => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Queries_NotAccessingCapturedTransparentIdentifier1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 1 }
where Z(() => a) > 0
select a + b;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 1 }
where Z(() => a) > 0
select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "select", "a", CSharpFeaturesResources.select_clause));
}
[Fact]
public void Queries_NotAccessingCapturedTransparentIdentifier2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select Z(() => 1);
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select Z(() => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Queries_Insert1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] { 1 } select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
#endregion
#region Yield
[Fact]
public void Yield_Update1()
{
var src1 = @"
class C
{
static IEnumerable<int> F()
{
yield return 1;
yield return 2;
yield break;
}
}
";
var src2 = @"
class C
{
static IEnumerable<int> F()
{
yield return 3;
yield break;
yield return 4;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield break;", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.yield_break_statement),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 4;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement));
}
[Fact]
public void Yield_Delete1()
{
var src1 = @"
yield return 1;
yield return 2;
yield return 3;
";
var src2 = @"
yield return 1;
yield return 3;
";
var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator);
bodyEdits.VerifyEdits(
"Delete [yield return 2;]@42");
}
[Fact]
public void Yield_Delete2()
{
var src1 = @"
class C
{
static IEnumerable<int> F()
{
yield return 1;
yield return 2;
yield return 3;
}
}
";
var src2 = @"
class C
{
static IEnumerable<int> F()
{
yield return 1;
yield return 3;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.yield_return_statement));
}
[Fact]
public void Yield_Insert1()
{
var src1 = @"
yield return 1;
yield return 3;
";
var src2 = @"
yield return 1;
yield return 2;
yield return 3;
yield return 4;
";
var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator);
bodyEdits.VerifyEdits(
"Insert [yield return 2;]@42",
"Insert [yield return 4;]@76");
}
[Fact]
public void Yield_Insert2()
{
var src1 = @"
class C
{
static IEnumerable<int> F()
{
yield return 1;
yield return 3;
}
}
";
var src2 = @"
class C
{
static IEnumerable<int> F()
{
yield return 1;
yield return 2;
yield return 3;
yield return 4;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "yield return 4;", CSharpFeaturesResources.yield_return_statement),
Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement));
}
[Fact]
public void MissingIteratorStateMachineAttribute()
{
var src1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 1;
}
}
";
var src2 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore },
Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static IEnumerable<int> F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute"));
}
[Fact]
public void MissingIteratorStateMachineAttribute2()
{
var src1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
return null;
}
}
";
var src2 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore });
}
#endregion
#region Await
/// <summary>
/// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>.
/// </summary>
[Fact]
public void AwaitSpilling_OK()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await F(1);
if (await F(1)) { Console.WriteLine(1); }
if (await F(1)) { Console.WriteLine(1); }
if (F(1, await F(1))) { Console.WriteLine(1); }
if (await F(1)) { Console.WriteLine(1); }
do { Console.WriteLine(1); } while (await F(1));
for (var x = await F(1); await G(1); await H(1)) { Console.WriteLine(1); }
foreach (var x in await F(1)) { Console.WriteLine(1); }
using (var x = await F(1)) { Console.WriteLine(1); }
lock (await F(1)) { Console.WriteLine(1); }
lock (a = await F(1)) { Console.WriteLine(1); }
var a = await F(1), b = await G(1);
a = await F(1);
switch (await F(2)) { case 1: return b = await F(1); }
return await F(1);
}
static async Task<int> G() => await F(1);
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await F(2);
if (await F(1)) { Console.WriteLine(2); }
if (await F(2)) { Console.WriteLine(1); }
if (F(1, await F(1))) { Console.WriteLine(2); }
while (await F(1)) { Console.WriteLine(1); }
do { Console.WriteLine(2); } while (await F(2));
for (var x = await F(2); await G(2); await H(2)) { Console.WriteLine(2); }
foreach (var x in await F(2)) { Console.WriteLine(2); }
using (var x = await F(2)) { Console.WriteLine(1); }
lock (await F(2)) { Console.WriteLine(2); }
lock (a = await F(2)) { Console.WriteLine(2); }
var a = await F(2), b = await G(2);
b = await F(2);
switch (await F(2)) { case 1: return b = await F(2); }
return await F(2);
}
static async Task<int> G() => await F(2);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
/// <summary>
/// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>.
/// </summary>
[Fact]
public void AwaitSpilling_Errors()
{
var src1 = @"
class C
{
static async Task<int> F()
{
F(1, await F(1));
F(1, await F(1));
F(await F(1));
await F(await F(1));
if (F(1, await F(1))) { Console.WriteLine(1); }
var a = F(1, await F(1)), b = F(1, await G(1));
b = F(1, await F(1));
b += await F(1);
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
F(2, await F(1));
F(1, await F(2));
F(await F(2));
await F(await F(2));
if (F(2, await F(1))) { Console.WriteLine(1); }
var a = F(1, await F(2)), b = F(1, await G(2));
b = F(1, await F(2));
b += await F(2);
}
}
";
var edits = GetTopEdits(src1, src2);
// consider: these edits can be allowed if we get more sophisticated
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(1, await F(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(await F(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "await F(await F(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1))"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "b = F(1, await F(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "b += await F(2);"));
}
[Fact]
public void Await_Delete1()
{
var src1 = @"
await F(1);
await F(2);
await F(3);
";
var src2 = @"
await F(1);
await F(3);
";
var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async);
bodyEdits.VerifyEdits(
"Delete [await F(2);]@37",
"Delete [await F(2)]@37");
}
[Fact]
public void Await_Delete2()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await F(1);
{
await F(2);
}
await F(3);
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await F(1);
{
F(2);
}
await F(3);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "F(2);", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Delete3()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await F(await F(1));
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await F(1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "await F(1);", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Delete4()
{
var src1 = @"
class C
{
static async Task<int> F() => await F(await F(1));
}
";
var src2 = @"
class C
{
static async Task<int> F() => await F(1);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Delete5()
{
var src1 = @"
class C
{
static async Task<int> F() => await F(1);
}
";
var src2 = @"
class C
{
static async Task<int> F() => F(1);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression));
}
[Fact]
public void AwaitForEach_Delete1()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await foreach (var x in G()) { }
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
foreach (var x in G()) { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var x in G())", CSharpFeaturesResources.foreach_statement));
}
[Fact]
public void AwaitForEach_Delete2()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await foreach (var (x, y) in G()) { }
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
foreach (var (x, y) in G()) { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var (x, y) in G())", CSharpFeaturesResources.foreach_statement));
}
[Fact]
public void AwaitForEach_Delete3()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await foreach (var x in G()) { }
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_foreach_statement));
}
[Fact]
public void AwaitUsing_Delete1()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await using D x = new D(), y = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await using D x = new D();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration));
}
[Fact]
public void AwaitUsing_Delete2()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await using D x = new D(), y = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await using D y = new D();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration));
}
[Fact]
public void AwaitUsing_Delete3()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await using D x = new D(), y = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration),
Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration));
}
[Fact]
public void AwaitUsing_Delete4()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await using D x = new D(), y = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
using D x = new D(), y = new D();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration),
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration));
}
[Fact]
public void Await_Insert1()
{
var src1 = @"
await F(1);
await F(3);
";
var src2 = @"
await F(1);
await F(2);
await F(3);
await F(4);
";
var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async);
bodyEdits.VerifyEdits(
"Insert [await F(2);]@37",
"Insert [await F(4);]@63",
"Insert [await F(2)]@37",
"Insert [await F(4)]@63");
}
[Fact]
public void Await_Insert2()
{
var src1 = @"
class C
{
static async IEnumerable<int> F()
{
await F(1);
await F(3);
}
}
";
var src2 = @"
class C
{
static async IEnumerable<int> F()
{
await F(1);
await F(2);
await F(3);
await F(4);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Insert3()
{
var src1 = @"
class C
{
static async IEnumerable<int> F()
{
await F(1);
await F(3);
}
}
";
var src2 = @"
class C
{
static async IEnumerable<int> F()
{
await F(await F(1));
await F(await F(2));
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "await", CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Insert4()
{
var src1 = @"
class C
{
static async Task<int> F() => await F(1);
}
";
var src2 = @"
class C
{
static async Task<int> F() => await F(await F(1));
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Insert5()
{
var src1 = @"
class C
{
static Task<int> F() => F(1);
}
";
var src2 = @"
class C
{
static async Task<int> F() => await F(1);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void AwaitForEach_Insert_Ok()
{
var src1 = @"
class C
{
static async Task<int> F()
{
foreach (var x in G()) { }
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await foreach (var x in G()) { }
}
}
";
var edits = GetTopEdits(src1, src2);
// ok to add awaits if there were none before and no active statements
edits.VerifyRudeDiagnostics();
}
[Fact]
public void AwaitForEach_Insert()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await Task.FromResult(1);
foreach (var x in G()) { }
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await Task.FromResult(1);
await foreach (var x in G()) { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "await", "await"));
}
[Fact]
public void AwaitUsing_Insert1()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await using D x = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await using D x = new D(), y = new D();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "y = new D()", CSharpFeaturesResources.asynchronous_using_declaration));
}
[Fact]
public void AwaitUsing_Insert2()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await G();
using D x = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await G();
await using D x = new D();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "await", "await"));
}
[Fact]
public void Await_Update()
{
var src1 = @"
class C
{
static async IAsyncEnumerable<int> F()
{
await foreach (var x in G()) { }
await Task.FromResult(1);
await Task.FromResult(1);
await Task.FromResult(1);
yield return 1;
yield break;
yield break;
}
}
";
var src2 = @"
class C
{
static async IAsyncEnumerable<int> F()
{
await foreach (var (x,y) in G()) { }
await foreach (var x in G()) { }
await using D x = new D(), y = new D();
await Task.FromResult(1);
await Task.FromResult(1);
yield return 1;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingStateMachineShape, "await foreach (var x in G()) { }", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_foreach_statement),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "x = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "y = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 1;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement));
}
[Fact]
public void MissingAsyncStateMachineAttribute1()
{
var src1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await new Task();
return 1;
}
}
";
var src2 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await new Task();
return 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
targetFrameworks: new[] { TargetFramework.MinimalAsync },
expectedDiagnostics: new[]
{
Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static async Task<int> F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute")
});
}
[Fact]
public void MissingAsyncStateMachineAttribute2()
{
var src1 = @"
using System.Threading.Tasks;
class C
{
static Task<int> F()
{
return null;
}
}
";
var src2 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await new Task();
return 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
targetFrameworks: new[] { TargetFramework.MinimalAsync });
}
[Fact]
public void SemanticError_AwaitInPropertyAccessor()
{
var src1 = @"
using System.Threading.Tasks;
class C
{
public Task<int> P
{
get
{
await Task.Delay(1);
return 1;
}
}
}
";
var src2 = @"
using System.Threading.Tasks;
class C
{
public Task<int> P
{
get
{
await Task.Delay(2);
return 1;
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
#endregion
#region Out Var
[Fact]
public void OutVarType_Update()
{
var src1 = @"
M(out var y);
";
var src2 = @"
M(out int y);
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [M(out var y);]@4 -> [M(out int y);]@4");
}
[Fact]
public void OutVarNameAndType_Update()
{
var src1 = @"
M(out var y);
";
var src2 = @"
M(out int z);
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [M(out var y);]@4 -> [M(out int z);]@4",
"Update [y]@14 -> [z]@14");
}
[Fact]
public void OutVar_Insert()
{
var src1 = @"
M();
";
var src2 = @"
M(out int y);
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [M();]@4 -> [M(out int y);]@4",
"Insert [y]@14");
}
[Fact]
public void OutVar_Delete()
{
var src1 = @"
M(out int y);
";
var src2 = @"
M();
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [M(out int y);]@4 -> [M();]@4",
"Delete [y]@14");
}
#endregion
#region Pattern
[Fact]
public void ConstantPattern_Update()
{
var src1 = @"
if ((o is null) && (y == 7)) return 3;
if (a is 7) return 5;
";
var src2 = @"
if ((o1 is null) && (y == 7)) return 3;
if (a is 77) return 5;
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if ((o is null) && (y == 7)) return 3;]@4 -> [if ((o1 is null) && (y == 7)) return 3;]@4",
"Update [if (a is 7) return 5;]@44 -> [if (a is 77) return 5;]@45");
}
[Fact]
public void DeclarationPattern_Update()
{
var src1 = @"
if (!(o is int i) && (y == 7)) return;
if (!(a is string s)) return;
if (!(b is string t)) return;
if (!(c is int j)) return;
";
var src2 = @"
if (!(o1 is int i) && (y == 7)) return;
if (!(a is int s)) return;
if (!(b is string t1)) return;
if (!(c is int)) return;
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if (!(o is int i) && (y == 7)) return;]@4 -> [if (!(o1 is int i) && (y == 7)) return;]@4",
"Update [if (!(a is string s)) return;]@44 -> [if (!(a is int s)) return;]@45",
"Update [if (!(c is int j)) return;]@106 -> [if (!(c is int)) return;]@105",
"Update [t]@93 -> [t1]@91",
"Delete [j]@121");
}
[Fact]
public void DeclarationPattern_Reorder()
{
var src1 = @"if ((a is int i) && (b is int j)) { A(); }";
var src2 = @"if ((b is int j) && (a is int i)) { A(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if ((a is int i) && (b is int j)) { A(); }]@2 -> [if ((b is int j) && (a is int i)) { A(); }]@2",
"Reorder [j]@32 -> @16");
}
[Fact]
public void VarPattern_Update()
{
var src1 = @"
if (o is (var x, var y)) return;
if (o4 is (string a, var (b, c))) return;
if (o2 is var (e, f, g)) return;
if (o3 is var (k, l, m)) return;
";
var src2 = @"
if (o is (int x, int y1)) return;
if (o1 is (var a, (var b, string c1))) return;
if (o7 is var (g, e, f)) return;
if (o3 is (string k, int l2, int m)) return;
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if (o is (var x, var y)) return;]@4 -> [if (o is (int x, int y1)) return;]@4",
"Update [if (o4 is (string a, var (b, c))) return;]@38 -> [if (o1 is (var a, (var b, string c1))) return;]@39",
"Update [if (o2 is var (e, f, g)) return;]@81 -> [if (o7 is var (g, e, f)) return;]@87",
"Reorder [g]@102 -> @102",
"Update [if (o3 is var (k, l, m)) return;]@115 -> [if (o3 is (string k, int l2, int m)) return;]@121",
"Update [y]@25 -> [y1]@25",
"Update [c]@67 -> [c1]@72",
"Update [l]@133 -> [l2]@146");
}
[Fact]
public void PositionalPattern_Update1()
{
var src1 = @"var r = (x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 };";
var src2 = @"var r = ((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 }]@10 -> [((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 }]@10",
"Update [(0, var b, int c) when c > 1 => 2]@29 -> [(_, int b1, double c1) when c1 > 2 => c1]@31",
"Reorder [c]@44 -> @39",
"Update [c]@44 -> [b1]@39",
"Update [b]@37 -> [c1]@50",
"Update [when c > 1]@47 -> [when c1 > 2]@54");
}
[Fact]
public void PositionalPattern_Update2()
{
var src1 = @"var r = (x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 };";
var src2 = @"var r = ((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 }]@10 -> [((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 }]@10",
"Update [(var a, 3, 4) => a]@29 -> [(var a1, 3, 4) => a1 * 2]@31",
"Update [(1, 1, Point { X: 0 } p) => 3]@49 -> [(1, 1, Point { Y: 0 } p1) => 3]@57",
"Update [a]@34 -> [a1]@36",
"Update [p]@71 -> [p1]@79");
}
[Fact]
public void PositionalPattern_Reorder()
{
var src1 = @"var r = (x, y, z) switch {
(1, 2, 3) => 0,
(var a, 3, 4) => a,
(0, var b, int c) when c > 1 => 2,
(1, 1, Point { X: 0 } p) => 3,
_ => 4
};
";
var src2 = @"var r = ((x, y, z)) switch {
(1, 1, Point { X: 0 } p) => 3,
(0, var b, int c) when c > 1 => 2,
(var a, 3, 4) => a,
(1, 2, 3) => 0,
_ => 4
};
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
@"Update [(x, y, z) switch {
(1, 2, 3) => 0,
(var a, 3, 4) => a,
(0, var b, int c) when c > 1 => 2,
(1, 1, Point { X: 0 } p) => 3,
_ => 4
}]@10 -> [((x, y, z)) switch {
(1, 1, Point { X: 0 } p) => 3,
(0, var b, int c) when c > 1 => 2,
(var a, 3, 4) => a,
(1, 2, 3) => 0,
_ => 4
}]@10",
"Reorder [(var a, 3, 4) => a]@47 -> @100",
"Reorder [(0, var b, int c) when c > 1 => 2]@68 -> @64",
"Reorder [(1, 1, Point { X: 0 } p) => 3]@104 -> @32");
}
[Fact]
public void PropertyPattern_Update()
{
var src1 = @"
if (address is { State: ""WA"" }) return 1;
if (obj is { Color: Color.Purple }) return 2;
if (o is string { Length: 5 } s) return 3;
";
var src2 = @"
if (address is { ZipCode: 98052 }) return 4;
if (obj is { Size: Size.M }) return 2;
if (o is string { Length: 7 } s7) return 5;
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if (address is { State: \"WA\" }) return 1;]@4 -> [if (address is { ZipCode: 98052 }) return 4;]@4",
"Update [if (obj is { Color: Color.Purple }) return 2;]@47 -> [if (obj is { Size: Size.M }) return 2;]@50",
"Update [if (o is string { Length: 5 } s) return 3;]@94 -> [if (o is string { Length: 7 } s7) return 5;]@90",
"Update [return 1;]@36 -> [return 4;]@39",
"Update [s]@124 -> [s7]@120",
"Update [return 3;]@127 -> [return 5;]@124");
}
[Fact]
public void RecursivePatterns_Reorder()
{
var src1 = @"var r = obj switch
{
string s when s.Length > 0 => (s, obj1) switch
{
(""a"", int i) => i,
_ => 0
},
int i => i * i,
_ => -1
};
";
var src2 = @"var r = obj switch
{
int i => i * i,
string s when s.Length > 0 => (s, obj1) switch
{
(""a"", int i) => i,
_ => 0
},
_ => -1
};
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int i => i * i]@140 -> @29",
"Move [i]@102 -> @33",
"Move [i]@144 -> @123");
}
[Fact]
public void CasePattern_UpdateInsert()
{
var src1 = @"
switch(shape)
{
case Circle c: return 1;
default: return 4;
}
";
var src2 = @"
switch(shape)
{
case Circle c1: return 1;
case Point p: return 0;
default: return 4;
}
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case Circle c: return 1;]@26 -> [case Circle c1: return 1;]@26",
"Insert [case Point p: return 0;]@57",
"Insert [case Point p:]@57",
"Insert [return 0;]@71",
"Update [c]@38 -> [c1]@38",
"Insert [p]@68");
}
[Fact]
public void CasePattern_UpdateDelete()
{
var src1 = @"
switch(shape)
{
case Point p: return 0;
case Circle c: A(c); break;
default: return 4;
}
";
var src2 = @"
switch(shape)
{
case Circle c1: A(c1); break;
default: return 4;
}
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case Circle c: A(c); break;]@55 -> [case Circle c1: A(c1); break;]@26",
"Update [A(c);]@70 -> [A(c1);]@42",
"Update [c]@67 -> [c1]@38",
"Delete [case Point p: return 0;]@26",
"Delete [case Point p:]@26",
"Delete [p]@37",
"Delete [return 0;]@40");
}
[Fact]
public void WhenCondition_Update()
{
var src1 = @"
switch(shape)
{
case Circle c when (c < 10): return 1;
case Circle c when (c > 100): return 2;
}
";
var src2 = @"
switch(shape)
{
case Circle c when (c < 5): return 1;
case Circle c2 when (c2 > 100): return 2;
}
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case Circle c when (c < 10): return 1;]@26 -> [case Circle c when (c < 5): return 1;]@26",
"Update [case Circle c when (c > 100): return 2;]@70 -> [case Circle c2 when (c2 > 100): return 2;]@69",
"Update [when (c < 10)]@40 -> [when (c < 5)]@40",
"Update [c]@82 -> [c2]@81",
"Update [when (c > 100)]@84 -> [when (c2 > 100)]@84");
}
[Fact]
public void CasePatternWithWhenCondition_UpdateReorder()
{
var src1 = @"
switch(shape)
{
case Rectangle r: return 0;
case Circle c when (c.Radius < 10): return 1;
case Circle c when (c.Radius > 100): return 2;
}
";
var src2 = @"
switch(shape)
{
case Circle c when (c.Radius > 99): return 2;
case Circle c when (c.Radius < 10): return 1;
case Rectangle r: return 0;
}
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [case Circle c when (c.Radius < 10): return 1;]@59 -> @77",
"Reorder [case Circle c when (c.Radius > 100): return 2;]@110 -> @26",
"Update [case Circle c when (c.Radius > 100): return 2;]@110 -> [case Circle c when (c.Radius > 99): return 2;]@26",
"Move [c]@71 -> @38",
"Update [when (c.Radius > 100)]@124 -> [when (c.Radius > 99)]@40",
"Move [c]@122 -> @89");
}
#endregion
#region Ref
[Fact]
public void Ref_Update()
{
var src1 = @"
ref int a = ref G(new int[] { 1, 2 });
ref int G(int[] p) { return ref p[1]; }
";
var src2 = @"
ref int32 a = ref G1(new int[] { 1, 2 });
ref int G1(int[] p) { return ref p[2]; }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [ref int G1(int[] p) { return ref p[2]; }]@47",
"Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4",
"Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = ref G1(new int[] { 1, 2 })]@14");
}
[Fact]
public void Ref_Insert()
{
var src1 = @"
int a = G(new int[] { 1, 2 });
int G(int[] p) { return p[1]; }
";
var src2 = @"
ref int32 a = ref G1(new int[] { 1, 2 });
ref int G1(int[] p) { return ref p[2]; }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [int G(int[] p) { return p[1]; }]@36 -> [ref int G1(int[] p) { return ref p[2]; }]@47",
"Update [int a = G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4",
"Update [a = G(new int[] { 1, 2 })]@8 -> [a = ref G1(new int[] { 1, 2 })]@14");
}
[Fact]
public void Ref_Delete()
{
var src1 = @"
ref int a = ref G(new int[] { 1, 2 });
ref int G(int[] p) { return ref p[1]; }
";
var src2 = @"
int32 a = G1(new int[] { 1, 2 });
int G1(int[] p) { return p[2]; }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [int G1(int[] p) { return p[2]; }]@39",
"Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [int32 a = G1(new int[] { 1, 2 })]@4",
"Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = G1(new int[] { 1, 2 })]@10");
}
#endregion
#region Tuples
[Fact]
public void TupleType_LocalVariables()
{
var src1 = @"
(int a, string c) x = (a, string2);
(int a, int b) y = (3, 4);
(int a, int b, int c) z = (5, 6, 7);
";
var src2 = @"
(int a, int b) x = (a, string2);
(int a, int b, string c) z1 = (5, 6, 7);
(int a, int b) y2 = (3, 4);
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [(int a, int b, int c) z = (5, 6, 7);]@69 -> @39",
"Update [(int a, string c) x = (a, string2)]@4 -> [(int a, int b) x = (a, string2)]@4",
"Update [(int a, int b, int c) z = (5, 6, 7)]@69 -> [(int a, int b, string c) z1 = (5, 6, 7)]@39",
"Update [z = (5, 6, 7)]@91 -> [z1 = (5, 6, 7)]@64",
"Update [y = (3, 4)]@56 -> [y2 = (3, 4)]@96");
}
[Fact]
public void TupleElementName()
{
var src1 = @"class C { (int a, int b) F(); }";
var src2 = @"class C { (int x, int b) F(); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int a, int b) F();]@10 -> [(int x, int b) F();]@10");
}
[Fact]
public void TupleInField()
{
var src1 = @"class C { private (int, int) _x = (1, 2); }";
var src2 = @"class C { private (int, string) _y = (1, 2); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int, int) _x = (1, 2)]@18 -> [(int, string) _y = (1, 2)]@18",
"Update [_x = (1, 2)]@29 -> [_y = (1, 2)]@32");
}
[Fact]
public void TupleInProperty()
{
var src1 = @"class C { public (int, int) Property1 { get { return (1, 2); } } }";
var src2 = @"class C { public (int, string) Property2 { get { return (1, string.Empty); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public (int, int) Property1 { get { return (1, 2); } }]@10 -> [public (int, string) Property2 { get { return (1, string.Empty); } }]@10",
"Update [get { return (1, 2); }]@40 -> [get { return (1, string.Empty); }]@43");
}
[Fact]
public void TupleInDelegate()
{
var src1 = @"public delegate void EventHandler1((int, int) x);";
var src2 = @"public delegate void EventHandler2((int, int) y);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate void EventHandler1((int, int) x);]@0 -> [public delegate void EventHandler2((int, int) y);]@0",
"Update [(int, int) x]@35 -> [(int, int) y]@35");
}
#endregion
#region With Expressions
[Fact]
public void WithExpression_PropertyAdd()
{
var src1 = @"var x = y with { X = 1 };";
var src2 = @"var x = y with { X = 1, Y = 2 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6");
}
[Fact]
public void WithExpression_PropertyDelete()
{
var src1 = @"var x = y with { X = 1, Y = 2 };";
var src2 = @"var x = y with { X = 1 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 2 }]@6 -> [x = y with { X = 1 }]@6");
}
[Fact]
public void WithExpression_PropertyChange()
{
var src1 = @"var x = y with { X = 1 };";
var src2 = @"var x = y with { Y = 1 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { Y = 1 }]@6");
}
[Fact]
public void WithExpression_PropertyValueChange()
{
var src1 = @"var x = y with { X = 1, Y = 1 };";
var src2 = @"var x = y with { X = 1, Y = 2 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6");
}
[Fact]
public void WithExpression_PropertyValueReorder()
{
var src1 = @"var x = y with { X = 1, Y = 1 };";
var src2 = @"var x = y with { Y = 1, X = 1 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { Y = 1, X = 1 }]@6");
}
#endregion
#region Top Level Statements
[Fact]
public void TopLevelStatement_CaptureArgs()
{
var src1 = @"
using System;
var x = new Func<string>(() => ""Hello"");
Console.WriteLine(x());
";
var src2 = @"
using System;
var x = new Func<string>(() => ""Hello"" + args[0]);
Console.WriteLine(x());
";
var edits = GetTopEdits(src1, src2);
// TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "using System;\r\n\r\nvar x = new Func<string>(() => \"Hello\" + args[0]);\r\n\r\nConsole.WriteLine(x());\r\n", "args"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void TopLevelStatement_InsertMultiScopeCapture()
{
var src1 = @"
using System;
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
int f0(int a) => x0;
int f1(int a) => x1;
}
";
var src2 = @"
using System;
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
int f0(int a) => x0;
int f1(int a) => x1;
int f2(int a) => x0 + x1; // error: connecting previously disconnected closures
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1"));
}
#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.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditAndContinue;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
[UseExportProvider]
public class StatementEditingTests : EditingTestBase
{
#region Strings
[Fact]
public void StringLiteral_update()
{
var src1 = @"
var x = ""Hello1"";
";
var src2 = @"
var x = ""Hello2"";
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [x = \"Hello1\"]@8 -> [x = \"Hello2\"]@8");
}
[Fact]
public void InterpolatedStringText_update()
{
var src1 = @"
var x = $""Hello1"";
";
var src2 = @"
var x = $""Hello2"";
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [x = $\"Hello1\"]@8 -> [x = $\"Hello2\"]@8");
}
[Fact]
public void Interpolation_update()
{
var src1 = @"
var x = $""Hello{123}"";
";
var src2 = @"
var x = $""Hello{124}"";
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [x = $\"Hello{123}\"]@8 -> [x = $\"Hello{124}\"]@8");
}
[Fact]
public void InterpolationFormatClause_update()
{
var src1 = @"
var x = $""Hello{123:N1}"";
";
var src2 = @"
var x = $""Hello{123:N2}"";
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [x = $\"Hello{123:N1}\"]@8 -> [x = $\"Hello{123:N2}\"]@8");
}
#endregion
#region Variable Declaration
[Fact]
public void VariableDeclaration_Insert()
{
var src1 = "if (x == 1) { x++; }";
var src2 = "var x = 1; if (x == 1) { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [var x = 1;]@2",
"Insert [var x = 1]@2",
"Insert [x = 1]@6");
}
[Fact]
public void VariableDeclaration_Update()
{
var src1 = "int x = F(1), y = G(2);";
var src2 = "int x = F(3), y = G(4);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [x = F(1)]@6 -> [x = F(3)]@6",
"Update [y = G(2)]@16 -> [y = G(4)]@16");
}
[Fact]
public void ParenthesizedVariableDeclaration_Update()
{
var src1 = @"
var (x1, (x2, x3)) = (1, (2, true));
var (a1, a2) = (1, () => { return 7; });
";
var src2 = @"
var (x1, (x2, x4)) = (1, (2, true));
var (a1, a3) = (1, () => { return 8; });
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [x3]@18 -> [x4]@18",
"Update [a2]@51 -> [a3]@51");
}
[Fact]
public void ParenthesizedVariableDeclaration_Insert()
{
var src1 = @"var (z1, z2) = (1, 2);";
var src2 = @"var (z1, z2, z3) = (1, 2, 5);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var (z1, z2) = (1, 2);]@2 -> [var (z1, z2, z3) = (1, 2, 5);]@2",
"Insert [z3]@15");
}
[Fact]
public void ParenthesizedVariableDeclaration_Delete()
{
var src1 = @"var (y1, y2, y3) = (1, 2, 7);";
var src2 = @"var (y1, y2) = (1, 4);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var (y1, y2, y3) = (1, 2, 7);]@2 -> [var (y1, y2) = (1, 4);]@2",
"Delete [y3]@15");
}
[Fact]
public void ParenthesizedVariableDeclaration_Insert_Mixed1()
{
var src1 = @"int a; (var z1, a) = (1, 2);";
var src2 = @"int a; (var z1, a, var z3) = (1, 2, 5);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(var z1, a) = (1, 2);]@9 -> [(var z1, a, var z3) = (1, 2, 5);]@9",
"Insert [z3]@25");
}
[Fact]
public void ParenthesizedVariableDeclaration_Insert_Mixed2()
{
var src1 = @"int a; (var z1, var z2) = (1, 2);";
var src2 = @"int a; (var z1, var z2, a) = (1, 2, 5);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(var z1, var z2) = (1, 2);]@9 -> [(var z1, var z2, a) = (1, 2, 5);]@9");
}
[Fact]
public void ParenthesizedVariableDeclaration_Delete_Mixed1()
{
var src1 = @"int a; (var y1, var y2, a) = (1, 2, 7);";
var src2 = @"int a; (var y1, var y2) = (1, 4);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(var y1, var y2, a) = (1, 2, 7);]@9 -> [(var y1, var y2) = (1, 4);]@9");
}
[Fact]
public void ParenthesizedVariableDeclaration_Delete_Mixed2()
{
var src1 = @"int a; (var y1, a, var y3) = (1, 2, 7);";
var src2 = @"int a; (var y1, a) = (1, 4);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(var y1, a, var y3) = (1, 2, 7);]@9 -> [(var y1, a) = (1, 4);]@9",
"Delete [y3]@25");
}
[Fact]
public void VariableDeclaraions_Reorder()
{
var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);";
var src2 = @"var (c, d) = (3, 4); var (a, b) = (1, 2);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [var (c, d) = (3, 4);]@23 -> @2");
}
[Fact]
public void VariableDeclaraions_Reorder_Mixed()
{
var src1 = @"int a; (a, int b) = (1, 2); (int c, int d) = (3, 4);";
var src2 = @"int a; (int c, int d) = (3, 4); (a, int b) = (1, 2);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [(int c, int d) = (3, 4);]@30 -> @9");
}
[Fact]
public void VariableNames_Reorder()
{
var src1 = @"var (a, b) = (1, 2);";
var src2 = @"var (b, a) = (2, 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var (a, b) = (1, 2);]@2 -> [var (b, a) = (2, 1);]@2",
"Reorder [b]@10 -> @7");
}
[Fact]
public void VariableNames_Reorder_Mixed()
{
var src1 = @"int a; (a, int b) = (1, 2);";
var src2 = @"int a; (int b, a) = (2, 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(a, int b) = (1, 2);]@9 -> [(int b, a) = (2, 1);]@9");
}
[Fact]
public void VariableNamesAndDeclaraions_Reorder()
{
var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);";
var src2 = @"var (d, c) = (3, 4); var (a, b) = (1, 2);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [var (c, d) = (3, 4);]@23 -> @2",
"Reorder [d]@31 -> @7");
}
[Fact]
public void ParenthesizedVariableDeclaration_Reorder()
{
var src1 = @"var (a, (b, c)) = (1, (2, 3));";
var src2 = @"var ((b, c), a) = ((2, 3), 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((b, c), a) = ((2, 3), 1);]@2",
"Reorder [a]@7 -> @15");
}
[Fact]
public void ParenthesizedVariableDeclaration_DoubleReorder()
{
var src1 = @"var (a, (b, c)) = (1, (2, 3));";
var src2 = @"var ((c, b), a) = ((2, 3), 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = ((2, 3), 1);]@2",
"Reorder [b]@11 -> @11",
"Reorder [c]@14 -> @8");
}
[Fact]
public void ParenthesizedVariableDeclaration_ComplexReorder()
{
var src1 = @"var (a, (b, c)) = (1, (2, 3)); var (x, (y, z)) = (4, (5, 6));";
var src2 = @"var (x, (y, z)) = (4, (5, 6)); var ((c, b), a) = (1, (2, 3)); ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [var (x, (y, z)) = (4, (5, 6));]@33 -> @2",
"Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = (1, (2, 3));]@33",
"Reorder [b]@11 -> @42",
"Reorder [c]@14 -> @39");
}
#endregion
#region Switch Statement
[Fact]
public void Switch1()
{
var src1 = "switch (a) { case 1: f(); break; } switch (b) { case 2: g(); break; }";
var src2 = "switch (b) { case 2: f(); break; } switch (a) { case 1: g(); break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [switch (b) { case 2: g(); break; }]@37 -> @2",
"Update [case 1: f(); break;]@15 -> [case 2: f(); break;]@15",
"Move [case 1: f(); break;]@15 -> @15",
"Update [case 2: g(); break;]@50 -> [case 1: g(); break;]@50",
"Move [case 2: g(); break;]@50 -> @50");
}
[Fact]
public void Switch_Case_Reorder()
{
var src1 = "switch (expr) { case 1: f(); break; case 2: case 3: case 4: g(); break; }";
var src2 = "switch (expr) { case 2: case 3: case 4: g(); break; case 1: f(); break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [case 2: case 3: case 4: g(); break;]@40 -> @18");
}
[Fact]
public void Switch_Case_Update()
{
var src1 = "switch (expr) { case 1: f(); break; }";
var src2 = "switch (expr) { case 2: f(); break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case 1: f(); break;]@18 -> [case 2: f(); break;]@18");
}
[Fact]
public void CasePatternLabel_UpdateDelete()
{
var src1 = @"
switch(shape)
{
case Point p: return 0;
case Circle c: return 1;
}
";
var src2 = @"
switch(shape)
{
case Circle circle: return 1;
}
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case Circle c: return 1;]@55 -> [case Circle circle: return 1;]@26",
"Update [c]@67 -> [circle]@38",
"Delete [case Point p: return 0;]@26",
"Delete [case Point p:]@26",
"Delete [p]@37",
"Delete [return 0;]@40");
}
#endregion
#region Switch Expression
[Fact]
public void MethodUpdate_UpdateSwitchExpression1()
{
var src1 = @"
class C
{
static int F(int a) => a switch { 0 => 0, _ => 1 };
}";
var src2 = @"
class C
{
static int F(int a) => a switch { 0 => 0, _ => 2 };
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, _ => 2 };]@18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateSwitchExpression2()
{
var src1 = @"
class C
{
static int F(int a) => a switch { 0 => 0, _ => 1 };
}";
var src2 = @"
class C
{
static int F(int a) => a switch { 1 => 0, _ => 2 };
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 1 => 0, _ => 2 };]@18");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void MethodUpdate_UpdateSwitchExpression3()
{
var src1 = @"
class C
{
static int F(int a) => a switch { 0 => 0, _ => 1 };
}";
var src2 = @"
class C
{
static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 };
}";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 };]@18");
edits.VerifyRudeDiagnostics();
}
#endregion
#region Try Catch Finally
[Fact]
public void TryInsert1()
{
var src1 = "x++;";
var src2 = "try { x++; } catch { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [try { x++; } catch { }]@2",
"Insert [{ x++; }]@6",
"Insert [catch { }]@15",
"Move [x++;]@2 -> @8",
"Insert [{ }]@21");
}
[Fact]
public void TryInsert2()
{
var src1 = "{ x++; }";
var src2 = "try { x++; } catch { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [try { x++; } catch { }]@2",
"Move [{ x++; }]@2 -> @6",
"Insert [catch { }]@15",
"Insert [{ }]@21");
}
[Fact]
public void TryDelete1()
{
var src1 = "try { x++; } catch { }";
var src2 = "x++;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [x++;]@8 -> @2",
"Delete [try { x++; } catch { }]@2",
"Delete [{ x++; }]@6",
"Delete [catch { }]@15",
"Delete [{ }]@21");
}
[Fact]
public void TryDelete2()
{
var src1 = "try { x++; } catch { }";
var src2 = "{ x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ x++; }]@6 -> @2",
"Delete [try { x++; } catch { }]@2",
"Delete [catch { }]@15",
"Delete [{ }]@21");
}
[Fact]
public void TryReorder()
{
var src1 = "try { x++; } catch { /*1*/ } try { y++; } catch { /*2*/ }";
var src2 = "try { y++; } catch { /*2*/ } try { x++; } catch { /*1*/ } ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [try { y++; } catch { /*2*/ }]@31 -> @2");
}
[Fact]
public void Finally_DeleteHeader()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ /*3*/ }]@47 -> @39",
"Delete [finally { /*3*/ }]@39");
}
[Fact]
public void Finally_InsertHeader()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [finally { /*3*/ }]@39",
"Move [{ /*3*/ }]@39 -> @47");
}
[Fact]
public void CatchUpdate()
{
var src1 = "try { } catch (Exception e) { }";
var src2 = "try { } catch (IOException e) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(Exception e)]@16 -> [(IOException e)]@16");
}
[Fact]
public void CatchInsert()
{
var src1 = "try { /*1*/ } catch (Exception e) { /*2*/ } ";
var src2 = "try { /*1*/ } catch (IOException e) { /*3*/ } catch (Exception e) { /*2*/ } ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [catch (IOException e) { /*3*/ }]@16",
"Insert [(IOException e)]@22",
"Insert [{ /*3*/ }]@38");
}
[Fact]
public void CatchBodyUpdate()
{
var src1 = "try { } catch (E e) { x++; }";
var src2 = "try { } catch (E e) { y++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [x++;]@24 -> [y++;]@24");
}
[Fact]
public void CatchDelete()
{
var src1 = "try { } catch (IOException e) { } catch (Exception e) { } ";
var src2 = "try { } catch (IOException e) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [catch (Exception e) { }]@36",
"Delete [(Exception e)]@42",
"Delete [{ }]@56");
}
[Fact]
public void CatchReorder1()
{
var src1 = "try { } catch (IOException e) { } catch (Exception e) { } ";
var src2 = "try { } catch (Exception e) { } catch (IOException e) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [catch (Exception e) { }]@36 -> @10");
}
[Fact]
public void CatchReorder2()
{
var src1 = "try { } catch (IOException e) { } catch (Exception e) { } catch { }";
var src2 = "try { } catch (A e) { } catch (Exception e) { } catch (IOException e) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [catch (Exception e) { }]@36 -> @26",
"Reorder [catch { }]@60 -> @10",
"Insert [(A e)]@16");
}
[Fact]
public void CatchFilterReorder2()
{
var src1 = "try { } catch (Exception e) when (e != null) { } catch (Exception e) { } catch { }";
var src2 = "try { } catch when (s == 1) { } catch (Exception e) { } catch (Exception e) when (e != null) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [catch (Exception e) { }]@51 -> @34",
"Reorder [catch { }]@75 -> @10",
"Insert [when (s == 1)]@16");
}
[Fact]
public void CatchInsertDelete()
{
var src1 = @"
try { x++; } catch (E e) { /*1*/ } catch (Exception e) { /*2*/ }
try { Console.WriteLine(); } finally { /*3*/ }";
var src2 = @"
try { x++; } catch (Exception e) { /*2*/ }
try { Console.WriteLine(); } catch (E e) { /*1*/ } finally { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [catch (E e) { /*1*/ }]@79",
"Insert [(E e)]@85",
"Move [{ /*1*/ }]@29 -> @91",
"Delete [catch (E e) { /*1*/ }]@17",
"Delete [(E e)]@23");
}
[Fact]
public void Catch_DeleteHeader1()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ /*3*/ }]@52 -> @39",
"Delete [catch (E2 e) { /*3*/ }]@39",
"Delete [(E2 e)]@45");
}
[Fact]
public void Catch_InsertHeader1()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [catch (E2 e) { /*3*/ }]@39",
"Insert [(E2 e)]@45",
"Move [{ /*3*/ }]@39 -> @52");
}
[Fact]
public void Catch_DeleteHeader2()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ /*3*/ }]@45 -> @39",
"Delete [catch { /*3*/ }]@39");
}
[Fact]
public void Catch_InsertHeader2()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [catch { /*3*/ }]@39",
"Move [{ /*3*/ }]@39 -> @45");
}
[Fact]
public void Catch_InsertFilter1()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }";
var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [when (e == null)]@29");
}
[Fact]
public void Catch_InsertFilter2()
{
var src1 = "try { /*1*/ } catch when (e == null) { /*2*/ }";
var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [(E1 e)]@22");
}
[Fact]
public void Catch_InsertFilter3()
{
var src1 = "try { /*1*/ } catch { /*2*/ }";
var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [(E1 e)]@22",
"Insert [when (e == null)]@29");
}
[Fact]
public void Catch_DeleteDeclaration1()
{
var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }";
var src2 = "try { /*1*/ } catch { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [(E1 e)]@22");
}
[Fact]
public void Catch_DeleteFilter1()
{
var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [when (e == null)]@29");
}
[Fact]
public void Catch_DeleteFilter2()
{
var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var src2 = "try { /*1*/ } catch when (e == null) { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [(E1 e)]@22");
}
[Fact]
public void Catch_DeleteFilter3()
{
var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }";
var src2 = "try { /*1*/ } catch { /*2*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [(E1 e)]@22",
"Delete [when (e == null)]@29");
}
[Fact]
public void TryCatchFinally_DeleteHeader()
{
var src1 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }";
var src2 = "{ /*1*/ } { /*2*/ } { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ /*1*/ }]@6 -> @2",
"Move [{ /*2*/ }]@22 -> @12",
"Move [{ /*3*/ }]@40 -> @22",
"Delete [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2",
"Delete [catch { /*2*/ }]@16",
"Delete [finally { /*3*/ }]@32");
}
[Fact]
public void TryCatchFinally_InsertHeader()
{
var src1 = "{ /*1*/ } { /*2*/ } { /*3*/ }";
var src2 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2",
"Move [{ /*1*/ }]@2 -> @6",
"Insert [catch { /*2*/ }]@16",
"Insert [finally { /*3*/ }]@32",
"Move [{ /*2*/ }]@12 -> @22",
"Move [{ /*3*/ }]@22 -> @40");
}
[Fact]
public void TryFilterFinally_InsertHeader()
{
var src1 = "{ /*1*/ } if (a == 1) { /*2*/ } { /*3*/ }";
var src2 = "try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }]@2",
"Move [{ /*1*/ }]@2 -> @6",
"Insert [catch when (a == 1) { /*2*/ }]@16",
"Insert [finally { /*3*/ }]@46",
"Insert [when (a == 1)]@22",
"Move [{ /*2*/ }]@24 -> @36",
"Move [{ /*3*/ }]@34 -> @54",
"Delete [if (a == 1) { /*2*/ }]@12");
}
#endregion
#region Blocks
[Fact]
public void Block_Insert()
{
var src1 = "";
var src2 = "{ x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [{ x++; }]@2",
"Insert [x++;]@4");
}
[Fact]
public void Block_Delete()
{
var src1 = "{ x++; }";
var src2 = "";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [{ x++; }]@2",
"Delete [x++;]@4");
}
[Fact]
public void Block_Reorder()
{
var src1 = "{ x++; } { y++; }";
var src2 = "{ y++; } { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [{ y++; }]@11 -> @2");
}
[Fact]
public void Block_AddLine()
{
var src1 = "{ x++; }";
var src2 = @"{ //
x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits();
}
#endregion
#region Checked/Unchecked
[Fact]
public void Checked_Insert()
{
var src1 = "";
var src2 = "checked { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [checked { x++; }]@2",
"Insert [{ x++; }]@10",
"Insert [x++;]@12");
}
[Fact]
public void Checked_Delete()
{
var src1 = "checked { x++; }";
var src2 = "";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [checked { x++; }]@2",
"Delete [{ x++; }]@10",
"Delete [x++;]@12");
}
[Fact]
public void Checked_Update()
{
var src1 = "checked { x++; }";
var src2 = "unchecked { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [checked { x++; }]@2 -> [unchecked { x++; }]@2");
}
[Fact]
public void Checked_DeleteHeader()
{
var src1 = "checked { x++; }";
var src2 = "{ x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ x++; }]@10 -> @2",
"Delete [checked { x++; }]@2");
}
[Fact]
public void Checked_InsertHeader()
{
var src1 = "{ x++; }";
var src2 = "checked { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [checked { x++; }]@2",
"Move [{ x++; }]@2 -> @10");
}
[Fact]
public void Unchecked_InsertHeader()
{
var src1 = "{ x++; }";
var src2 = "unchecked { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [unchecked { x++; }]@2",
"Move [{ x++; }]@2 -> @12");
}
#endregion
#region Unsafe
[Fact]
public void Unsafe_Insert()
{
var src1 = "";
var src2 = "unsafe { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [unsafe { x++; }]@2",
"Insert [{ x++; }]@9",
"Insert [x++;]@11");
}
[Fact]
public void Unsafe_Delete()
{
var src1 = "unsafe { x++; }";
var src2 = "";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [unsafe { x++; }]@2",
"Delete [{ x++; }]@9",
"Delete [x++;]@11");
}
[Fact]
public void Unsafe_DeleteHeader()
{
var src1 = "unsafe { x++; }";
var src2 = "{ x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ x++; }]@9 -> @2",
"Delete [unsafe { x++; }]@2");
}
[Fact]
public void Unsafe_InsertHeader()
{
var src1 = "{ x++; }";
var src2 = "unsafe { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [unsafe { x++; }]@2",
"Move [{ x++; }]@2 -> @9");
}
#endregion
#region Using Statement
[Fact]
public void Using1()
{
var src1 = @"using (a) { using (b) { Goo(); } }";
var src2 = @"using (a) { using (c) { using (b) { Goo(); } } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [using (c) { using (b) { Goo(); } }]@14",
"Insert [{ using (b) { Goo(); } }]@24",
"Move [using (b) { Goo(); }]@14 -> @26");
}
[Fact]
public void Using_DeleteHeader()
{
var src1 = @"using (a) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@12 -> @2",
"Delete [using (a) { Goo(); }]@2");
}
[Fact]
public void Using_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"using (a) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [using (a) { Goo(); }]@2",
"Move [{ Goo(); }]@2 -> @12");
}
#endregion
#region Lock Statement
[Fact]
public void Lock1()
{
var src1 = @"lock (a) { lock (b) { Goo(); } }";
var src2 = @"lock (a) { lock (c) { lock (b) { Goo(); } } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [lock (c) { lock (b) { Goo(); } }]@13",
"Insert [{ lock (b) { Goo(); } }]@22",
"Move [lock (b) { Goo(); }]@13 -> @24");
}
[Fact]
public void Lock_DeleteHeader()
{
var src1 = @"lock (a) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@11 -> @2",
"Delete [lock (a) { Goo(); }]@2");
}
[Fact]
public void Lock_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"lock (a) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [lock (a) { Goo(); }]@2",
"Move [{ Goo(); }]@2 -> @11");
}
#endregion
#region ForEach Statement
[Fact]
public void ForEach1()
{
var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }";
var src2 = @"foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [foreach (var c in g) { foreach (var b in f) { Goo(); } }]@25",
"Insert [{ foreach (var b in f) { Goo(); } }]@46",
"Move [foreach (var b in f) { Goo(); }]@25 -> @48");
var actual = ToMatchingPairs(edits.Match);
var expected = new MatchingPairs
{
{ "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }" },
{ "{ foreach (var b in f) { Goo(); } }", "{ foreach (var c in g) { foreach (var b in f) { Goo(); } } }" },
{ "foreach (var b in f) { Goo(); }", "foreach (var b in f) { Goo(); }" },
{ "{ Goo(); }", "{ Goo(); }" },
{ "Goo();", "Goo();" }
};
expected.AssertEqual(actual);
}
[Fact]
public void ForEach_Swap1()
{
var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }";
var src2 = @"foreach (var b in f) { foreach (var a in e) { Goo(); } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [foreach (var b in f) { Goo(); }]@25 -> @2",
"Move [foreach (var a in e) { foreach (var b in f) { Goo(); } }]@2 -> @25",
"Move [Goo();]@48 -> @48");
var actual = ToMatchingPairs(edits.Match);
var expected = new MatchingPairs
{
{ "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { Goo(); }" },
{ "{ foreach (var b in f) { Goo(); } }", "{ Goo(); }" },
{ "foreach (var b in f) { Goo(); }", "foreach (var b in f) { foreach (var a in e) { Goo(); } }" },
{ "{ Goo(); }", "{ foreach (var a in e) { Goo(); } }" },
{ "Goo();", "Goo();" }
};
expected.AssertEqual(actual);
}
[Fact]
public void Foreach_DeleteHeader()
{
var src1 = @"foreach (var a in b) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@23 -> @2",
"Delete [foreach (var a in b) { Goo(); }]@2");
}
[Fact]
public void Foreach_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"foreach (var a in b) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [foreach (var a in b) { Goo(); }]@2",
"Move [{ Goo(); }]@2 -> @23");
}
[Fact]
public void ForeachVariable_Update1()
{
var src1 = @"
foreach (var (a1, a2) in e) { }
foreach ((var b1, var b2) in e) { }
foreach (var a in e1) { }
";
var src2 = @"
foreach (var (a1, a3) in e) { }
foreach ((var b3, int b2) in e) { }
foreach (_ in e1) { }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [foreach ((var b1, var b2) in e) { }]@37 -> [foreach ((var b3, int b2) in e) { }]@37",
"Update [foreach (var a in e1) { }]@74 -> [foreach (_ in e1) { }]@74",
"Update [a2]@22 -> [a3]@22",
"Update [b1]@51 -> [b3]@51");
}
[Fact]
public void ForeachVariable_Update2()
{
var src1 = @"
foreach (_ in e2) { }
foreach (_ in e3) { A(); }
";
var src2 = @"
foreach (var b in e2) { }
foreach (_ in e4) { A(); }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [foreach (_ in e2) { }]@4 -> [foreach (var b in e2) { }]@4",
"Update [foreach (_ in e3) { A(); }]@27 -> [foreach (_ in e4) { A(); }]@31");
}
[Fact]
public void ForeachVariable_Insert()
{
var src1 = @"
foreach (var (a3, a4) in e) { }
foreach ((var b4, var b5) in e) { }
";
var src2 = @"
foreach (var (a3, a5, a4) in e) { }
foreach ((var b6, var b4, var b5) in e) { }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [foreach (var (a3, a4) in e) { }]@4 -> [foreach (var (a3, a5, a4) in e) { }]@4",
"Update [foreach ((var b4, var b5) in e) { }]@37 -> [foreach ((var b6, var b4, var b5) in e) { }]@41",
"Insert [a5]@22",
"Insert [b6]@55");
}
[Fact]
public void ForeachVariable_Delete()
{
var src1 = @"
foreach (var (a11, a12, a13) in e) { F(); }
foreach ((var b7, var b8, var b9) in e) { G(); }
";
var src2 = @"
foreach (var (a12, a13) in e1) { F(); }
foreach ((var b7, var b9) in e) { G(); }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [foreach (var (a11, a12, a13) in e) { F(); }]@4 -> [foreach (var (a12, a13) in e1) { F(); }]@4",
"Update [foreach ((var b7, var b8, var b9) in e) { G(); }]@49 -> [foreach ((var b7, var b9) in e) { G(); }]@45",
"Delete [a11]@18",
"Delete [b8]@71");
}
[Fact]
public void ForeachVariable_Reorder()
{
var src1 = @"
foreach (var (a, b) in e1) { }
foreach ((var x, var y) in e2) { }
";
var src2 = @"
foreach ((var x, var y) in e2) { }
foreach (var (a, b) in e1) { }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [foreach ((var x, var y) in e2) { }]@36 -> @4");
}
[Fact]
public void ForeachVariableEmbedded_Reorder()
{
var src1 = @"
foreach (var (a, b) in e1) {
foreach ((var x, var y) in e2) { }
}
";
var src2 = @"
foreach ((var x, var y) in e2) { }
foreach (var (a, b) in e1) { }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [foreach ((var x, var y) in e2) { }]@39 -> @4");
}
#endregion
#region For Statement
[Fact]
public void For1()
{
var src1 = @"for (int a = 0; a < 10; a++) { for (int a = 0; a < 20; a++) { Goo(); } }";
var src2 = @"for (int a = 0; a < 10; a++) { for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } }]@33",
"Insert [int b = 0]@38",
"Insert [b < 10]@49",
"Insert [b++]@57",
"Insert [{ for (int a = 0; a < 20; a++) { Goo(); } }]@62",
"Insert [b = 0]@42",
"Move [for (int a = 0; a < 20; a++) { Goo(); }]@33 -> @64");
}
[Fact]
public void For_DeleteHeader()
{
var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@43 -> @2",
"Delete [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2",
"Delete [int i = 10, j = 0]@7",
"Delete [i = 10]@11",
"Delete [j = 0]@19",
"Delete [i > j]@26",
"Delete [i--]@33",
"Delete [j++]@38");
}
[Fact]
public void For_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2",
"Insert [int i = 10, j = 0]@7",
"Insert [i > j]@26",
"Insert [i--]@33",
"Insert [j++]@38",
"Move [{ Goo(); }]@2 -> @43",
"Insert [i = 10]@11",
"Insert [j = 0]@19");
}
[Fact]
public void For_DeclaratorsToInitializers()
{
var src1 = @"for (var i = 10; i < 10; i++) { }";
var src2 = @"for (i = 10; i < 10; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [i = 10]@7",
"Delete [var i = 10]@7",
"Delete [i = 10]@11");
}
[Fact]
public void For_InitializersToDeclarators()
{
var src1 = @"for (i = 10, j = 0; i < 10; i++) { }";
var src2 = @"for (var i = 10, j = 0; i < 10; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [var i = 10, j = 0]@7",
"Insert [i = 10]@11",
"Insert [j = 0]@19",
"Delete [i = 10]@7",
"Delete [j = 0]@15");
}
[Fact]
public void For_Declarations_Reorder()
{
var src1 = @"for (var i = 10, j = 0; i > j; i++, j++) { }";
var src2 = @"for (var j = 0, i = 10; i > j; i++, j++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Reorder [j = 0]@19 -> @11");
}
[Fact]
public void For_Declarations_Insert()
{
var src1 = @"for (var i = 0, j = 1; i > j; i++, j++) { }";
var src2 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var i = 0, j = 1]@7 -> [var i = 0, j = 1, k = 2]@7",
"Insert [k = 2]@25");
}
[Fact]
public void For_Declarations_Delete()
{
var src1 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }";
var src2 = @"for (var i = 0, j = 1; i > j; i++, j++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [var i = 0, j = 1, k = 2]@7 -> [var i = 0, j = 1]@7",
"Delete [k = 2]@25");
}
[Fact]
public void For_Initializers_Reorder()
{
var src1 = @"for (i = 10, j = 0; i > j; i++, j++) { }";
var src2 = @"for (j = 0, i = 10; i > j; i++, j++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Reorder [j = 0]@15 -> @7");
}
[Fact]
public void For_Initializers_Insert()
{
var src1 = @"for (i = 10; i < 10; i++) { }";
var src2 = @"for (i = 10, j = 0; i < 10; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Insert [j = 0]@15");
}
[Fact]
public void For_Initializers_Delete()
{
var src1 = @"for (i = 10, j = 0; i < 10; i++) { }";
var src2 = @"for (i = 10; i < 10; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Delete [j = 0]@15");
}
[Fact]
public void For_Initializers_Update()
{
var src1 = @"for (i = 1; i < 10; i++) { }";
var src2 = @"for (i = 2; i < 10; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [i = 1]@7 -> [i = 2]@7");
}
[Fact]
public void For_Initializers_Update_Lambda()
{
var src1 = @"for (int i = 10, j = F(() => 1); i > j; i++) { }";
var src2 = @"for (int i = 10, j = F(() => 2); i > j; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [() => 1]@25 -> [() => 2]@25");
}
[Fact]
public void For_Condition_Update()
{
var src1 = @"for (int i = 0; i < 10; i++) { }";
var src2 = @"for (int i = 0; i < 20; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [i < 10]@18 -> [i < 20]@18");
}
[Fact]
public void For_Condition_Lambda()
{
var src1 = @"for (int i = 0; F(() => 1); i++) { }";
var src2 = @"for (int i = 0; F(() => 2); i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [() => 1]@20 -> [() => 2]@20");
}
[Fact]
public void For_Incrementors_Reorder()
{
var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { }";
var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Reorder [j++]@38 -> @33");
}
[Fact]
public void For_Incrementors_Insert()
{
var src1 = @"for (int i = 10, j = 0; i > j; i--) { }";
var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Insert [j++]@33");
}
[Fact]
public void For_Incrementors_Delete()
{
var src1 = @"for (int i = 10, j = 0; i > j; j++, i--) { }";
var src2 = @"for (int i = 10, j = 0; i > j; j++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Delete [i--]@38");
}
[Fact]
public void For_Incrementors_Update()
{
var src1 = @"for (int i = 10, j = 0; i > j; j++) { }";
var src2 = @"for (int i = 10, j = 0; i > j; i++) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [j++]@33 -> [i++]@33");
}
[Fact]
public void For_Incrementors_Update_Lambda()
{
var src1 = @"for (int i = 10, j = 0; i > j; F(() => 1)) { }";
var src2 = @"for (int i = 10, j = 0; i > j; F(() => 2)) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [() => 1]@35 -> [() => 2]@35");
}
#endregion
#region While Statement
[Fact]
public void While1()
{
var src1 = @"while (a) { while (b) { Goo(); } }";
var src2 = @"while (a) { while (c) { while (b) { Goo(); } } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [while (c) { while (b) { Goo(); } }]@14",
"Insert [{ while (b) { Goo(); } }]@24",
"Move [while (b) { Goo(); }]@14 -> @26");
}
[Fact]
public void While_DeleteHeader()
{
var src1 = @"while (a) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@12 -> @2",
"Delete [while (a) { Goo(); }]@2");
}
[Fact]
public void While_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"while (a) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [while (a) { Goo(); }]@2",
"Move [{ Goo(); }]@2 -> @12");
}
#endregion
#region Do Statement
[Fact]
public void Do1()
{
var src1 = @"do { do { Goo(); } while (b); } while (a);";
var src2 = @"do { do { do { Goo(); } while(b); } while(c); } while(a);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [do { do { Goo(); } while(b); } while(c);]@7",
"Insert [{ do { Goo(); } while(b); }]@10",
"Move [do { Goo(); } while (b);]@7 -> @12");
}
[Fact]
public void Do_DeleteHeader()
{
var src1 = @"do { Goo(); } while (a);";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@5 -> @2",
"Delete [do { Goo(); } while (a);]@2");
}
[Fact]
public void Do_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"do { Goo(); } while (a);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [do { Goo(); } while (a);]@2",
"Move [{ Goo(); }]@2 -> @5");
}
#endregion
#region If Statement
[Fact]
public void IfStatement_TestExpression_Update()
{
var src1 = "var x = 1; if (x == 1) { x++; }";
var src2 = "var x = 1; if (x == 2) { x++; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if (x == 1) { x++; }]@13 -> [if (x == 2) { x++; }]@13");
}
[Fact]
public void ElseClause_Insert()
{
var src1 = "if (x == 1) x++; ";
var src2 = "if (x == 1) x++; else y++;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [else y++;]@19",
"Insert [y++;]@24");
}
[Fact]
public void ElseClause_InsertMove()
{
var src1 = "if (x == 1) x++; else y++;";
var src2 = "if (x == 1) x++; else if (x == 2) y++;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [if (x == 2) y++;]@24",
"Move [y++;]@24 -> @36");
}
[Fact]
public void If1()
{
var src1 = @"if (a) if (b) Goo();";
var src2 = @"if (a) if (c) if (b) Goo();";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [if (c) if (b) Goo();]@9",
"Move [if (b) Goo();]@9 -> @16");
}
[Fact]
public void If_DeleteHeader()
{
var src1 = @"if (a) { Goo(); }";
var src2 = @"{ Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(); }]@9 -> @2",
"Delete [if (a) { Goo(); }]@2");
}
[Fact]
public void If_InsertHeader()
{
var src1 = @"{ Goo(); }";
var src2 = @"if (a) { Goo(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [if (a) { Goo(); }]@2",
"Move [{ Goo(); }]@2 -> @9");
}
[Fact]
public void Else_DeleteHeader()
{
var src1 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }";
var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(/*2*/); }]@30 -> @25",
"Delete [else { Goo(/*2*/); }]@25");
}
[Fact]
public void Else_InsertHeader()
{
var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }";
var src2 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [else { Goo(/*2*/); }]@25",
"Move [{ Goo(/*2*/); }]@25 -> @30");
}
[Fact]
public void ElseIf_DeleteHeader()
{
var src1 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }";
var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ Goo(/*2*/); }]@37 -> @25",
"Delete [else if (b) { Goo(/*2*/); }]@25",
"Delete [if (b) { Goo(/*2*/); }]@30");
}
[Fact]
public void ElseIf_InsertHeader()
{
var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }";
var src2 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [else if (b) { Goo(/*2*/); }]@25",
"Insert [if (b) { Goo(/*2*/); }]@30",
"Move [{ Goo(/*2*/); }]@25 -> @37");
}
[Fact]
public void IfElseElseIf_InsertHeader()
{
var src1 = @"{ /*1*/ } { /*2*/ } { /*3*/ }";
var src2 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2",
"Move [{ /*1*/ }]@2 -> @9",
"Insert [else if (b) { /*2*/ } else { /*3*/ }]@19",
"Insert [if (b) { /*2*/ } else { /*3*/ }]@24",
"Move [{ /*2*/ }]@12 -> @31",
"Insert [else { /*3*/ }]@41",
"Move [{ /*3*/ }]@22 -> @46");
}
[Fact]
public void IfElseElseIf_DeleteHeader()
{
var src1 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }";
var src2 = @"{ /*1*/ } { /*2*/ } { /*3*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Move [{ /*1*/ }]@9 -> @2",
"Move [{ /*2*/ }]@31 -> @12",
"Move [{ /*3*/ }]@46 -> @22",
"Delete [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2",
"Delete [else if (b) { /*2*/ } else { /*3*/ }]@19",
"Delete [if (b) { /*2*/ } else { /*3*/ }]@24",
"Delete [else { /*3*/ }]@41");
}
#endregion
#region Switch Statement
[Fact]
public void SwitchStatement_Update_Expression()
{
var src1 = "var x = 1; switch (x + 1) { case 1: break; }";
var src2 = "var x = 1; switch (x + 2) { case 1: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [switch (x + 1) { case 1: break; }]@13 -> [switch (x + 2) { case 1: break; }]@13");
}
[Fact]
public void SwitchStatement_Update_SectionLabel()
{
var src1 = "var x = 1; switch (x) { case 1: break; }";
var src2 = "var x = 1; switch (x) { case 2: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case 1: break;]@26 -> [case 2: break;]@26");
}
[Fact]
public void SwitchStatement_Update_AddSectionLabel()
{
var src1 = "var x = 1; switch (x) { case 1: break; }";
var src2 = "var x = 1; switch (x) { case 1: case 2: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case 1: break;]@26 -> [case 1: case 2: break;]@26");
}
[Fact]
public void SwitchStatement_Update_DeleteSectionLabel()
{
var src1 = "var x = 1; switch (x) { case 1: case 2: break; }";
var src2 = "var x = 1; switch (x) { case 1: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case 1: case 2: break;]@26 -> [case 1: break;]@26");
}
[Fact]
public void SwitchStatement_Update_BlockInSection()
{
var src1 = "var x = 1; switch (x) { case 1: { x++; break; } }";
var src2 = "var x = 1; switch (x) { case 1: { x--; break; } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [x++;]@36 -> [x--;]@36");
}
[Fact]
public void SwitchStatement_Update_BlockInDefaultSection()
{
var src1 = "var x = 1; switch (x) { default: { x++; break; } }";
var src2 = "var x = 1; switch (x) { default: { x--; break; } }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [x++;]@37 -> [x--;]@37");
}
[Fact]
public void SwitchStatement_Insert_Section()
{
var src1 = "var x = 1; switch (x) { case 1: break; }";
var src2 = "var x = 1; switch (x) { case 1: break; case 2: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [case 2: break;]@41",
"Insert [break;]@49");
}
[Fact]
public void SwitchStatement_Delete_Section()
{
var src1 = "var x = 1; switch (x) { case 1: break; case 2: break; }";
var src2 = "var x = 1; switch (x) { case 1: break; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [case 2: break;]@41",
"Delete [break;]@49");
}
#endregion
#region Lambdas
[Fact]
public void Lambdas_AddAttribute()
{
var src1 = "Func<int, int> x = (a) => a;";
var src2 = "Func<int, int> x = [A][return:A]([A]a) => a;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(a) => a]@21 -> [[A][return:A]([A]a) => a]@21",
"Update [a]@22 -> [[A]a]@35");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.method),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.method),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.parameter));
GetTopEdits(edits).VerifySemantics(
ActiveStatementsDescription.Empty,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true) },
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Lambdas_InVariableDeclarator()
{
var src1 = "Action x = a => a, y = b => b;";
var src2 = "Action x = (a) => a, y = b => b + 1;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [a => a]@13 -> [(a) => a]@13",
"Update [b => b]@25 -> [b => b + 1]@27",
"Insert [(a)]@13",
"Insert [a]@14",
"Delete [a]@13");
}
[Fact]
public void Lambdas_InExpressionStatement()
{
var src1 = "F(a => a, b => b);";
var src2 = "F(b => b, a => a+1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [b => b]@12 -> @4",
"Update [a => a]@4 -> [a => a+1]@12");
}
[Fact]
public void Lambdas_ReorderArguments()
{
var src1 = "F(G(a => {}), G(b => {}));";
var src2 = "F(G(b => {}), G(a => {}));";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [b => {}]@18 -> @6");
}
[Fact]
public void Lambdas_InWhile()
{
var src1 = "while (F(a => a)) { /*1*/ }";
var src2 = "do { /*1*/ } while (F(a => a));";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [do { /*1*/ } while (F(a => a));]@2",
"Move [{ /*1*/ }]@20 -> @5",
"Move [a => a]@11 -> @24",
"Delete [while (F(a => a)) { /*1*/ }]@2");
}
[Fact]
public void Lambdas_InLambda_ChangeInLambdaSignature()
{
var src1 = "F(() => { G(x => y); });";
var src2 = "F(q => { G(() => y); });";
var edits = GetMethodEdits(src1, src2);
// changes were made to the outer lambda signature:
edits.VerifyEdits(
"Update [() => { G(x => y); }]@4 -> [q => { G(() => y); }]@4",
"Insert [q]@4",
"Delete [()]@4");
}
[Fact]
public void Lambdas_InLambda_ChangeOnlyInLambdaBody()
{
var src1 = "F(() => { G(x => y); });";
var src2 = "F(() => { G(() => y); });";
var edits = GetMethodEdits(src1, src2);
// no changes to the method were made, only within the outer lambda body:
edits.VerifyEdits();
}
[Fact]
public void Lambdas_Update_ParameterRefness_NoBodyChange()
{
var src1 = @"F((ref int a) => a = 1);";
var src2 = @"F((out int a) => a = 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [ref int a]@5 -> [out int a]@5");
}
[Fact]
public void Lambdas_Insert_Static_Top()
{
var src1 = @"
using System;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var f = new Func<int, int>(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Insert_Static_Nested1()
{
var src1 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
G(a => a);
}
}
";
var src2 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
G(a => G(b => b) + a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Insert_ThisOnly_Top1()
{
var src1 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
G(a => x);
}
}
";
var edits = GetTopEdits(src1, src2);
// TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")]
public void Lambdas_Insert_ThisOnly_Top2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
int y = 1;
{
int x = 2;
var f1 = new Func<int, int>(a => y);
}
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
int y = 1;
{
int x = 2;
var f2 = from a in new[] { 1 } select a + y;
var f3 = from a in new[] { 1 } where x > 0 select a;
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "x", "x"));
}
[Fact]
public void Lambdas_Insert_ThisOnly_Nested1()
{
var src1 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
G(a => a);
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
G(a => G(b => x));
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact]
public void Lambdas_Insert_ThisOnly_Nested2()
{
var src1 = @"
using System;
class C
{
int x = 0;
void F()
{
var f1 = new Func<int, int>(a =>
{
var f2 = new Func<int, int>(b =>
{
return b;
});
return a;
});
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
void F()
{
var f1 = new Func<int, int>(a =>
{
var f2 = new Func<int, int>(b =>
{
return b;
});
var f3 = new Func<int, int>(c =>
{
return c + x;
});
return a;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact]
public void Lambdas_InsertAndDelete_Scopes1()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0, y = 0; // Group #0
void F()
{
int x0 = 0, y0 = 0; // Group #1
{ int x1 = 0, y1 = 0; // Group #2
{ int x2 = 0, y2 = 0; // Group #1
{ int x3 = 0, y3 = 0; // Group #2
G(a => x3 + x1);
G(a => x0 + y0 + x2);
G(a => x);
}
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0, y = 0; // Group #0
void F()
{
int x0 = 0, y0 = 0; // Group #1
{ int x1 = 0, y1 = 0; // Group #2
{ int x2 = 0, y2 = 0; // Group #1
{ int x3 = 0, y3 = 0; // Group #2
G(a => x3 + x1);
G(a => x0 + y0 + x2);
G(a => x);
G(a => x); // OK
G(a => x0 + y0); // OK
G(a => x1 + y0); // error - connecting Group #1 and Group #2
G(a => x3 + x1); // error - multi-scope (conservative)
G(a => x + y0); // error - connecting Group #0 and Group #1
G(a => x + x3); // error - connecting Group #0 and Group #2
}
}
}
}
}
";
var insert = GetTopEdits(src1, src2);
insert.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3"));
var delete = GetTopEdits(src2, src1);
delete.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3"));
}
[Fact]
public void Lambdas_Insert_ForEach1()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
G(a => x0);
G(a => x1);
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
G(a => x0);
G(a => x1);
G(a => x0 + x1); // error: connecting previously disconnected closures
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"));
}
[Fact]
public void Lambdas_Insert_ForEach2()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {}
void F()
{
int x0 = 0; // Group #0
foreach (int x1 in new[] { 1 }) // Group #1
G(a => x0, a => x1, null);
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {}
void F()
{
int x0 = 0; // Group #0
foreach (int x1 in new[] { 1 }) // Group #1
G(a => x0, a => x1, a => x0 + x1); // error: connecting previously disconnected closures
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"));
}
[Fact]
public void Lambdas_Insert_For1()
{
var src1 = @"
using System;
class C
{
bool G(Func<int, int> f) => true;
void F()
{
for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);)
{
int x2 = 0;
G(a => x2);
}
}
}
";
var src2 = @"
using System;
class C
{
bool G(Func<int, int> f) => true;
void F()
{
for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);)
{
int x2 = 0;
G(a => x2);
G(a => x0 + x1); // ok
G(a => x0 + x2); // error: connecting previously disconnected closures
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x2", CSharpFeaturesResources.lambda, "x0", "x2"));
}
[Fact]
public void Lambdas_Insert_Switch1()
{
var src1 = @"
using System;
class C
{
bool G(Func<int> f) => true;
int a = 1;
void F()
{
int x2 = 1;
G(() => x2);
switch (a)
{
case 1:
int x0 = 1;
G(() => x0);
break;
case 2:
int x1 = 1;
G(() => x1);
break;
}
}
}
";
var src2 = @"
using System;
class C
{
bool G(Func<int> f) => true;
int a = 1;
void F()
{
int x2 = 1;
G(() => x2);
switch (a)
{
case 1:
int x0 = 1;
G(() => x0);
goto case 2;
case 2:
int x1 = 1;
G(() => x1);
goto default;
default:
x0 = 1;
x1 = 2;
G(() => x0 + x1); // ok
G(() => x0 + x2); // error
break;
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x2", "x0"));
}
[Fact]
public void Lambdas_Insert_Using1()
{
var src1 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static int F(object a, object b) => 1;
static IDisposable D() => null;
static void F()
{
using (IDisposable x0 = D(), y0 = D())
{
int x1 = 1;
G(() => x0);
G(() => y0);
G(() => x1);
}
}
}
";
var src2 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static int F(object a, object b) => 1;
static IDisposable D() => null;
static void F()
{
using (IDisposable x0 = D(), y0 = D())
{
int x1 = 1;
G(() => x0);
G(() => y0);
G(() => x1);
G(() => F(x0, y0)); // ok
G(() => F(x0, x1)); // error
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"));
}
[Fact]
public void Lambdas_Insert_Catch1()
{
var src1 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static int F(object a, object b) => 1;
static void F()
{
try
{
}
catch (Exception x0)
{
int x1 = 1;
G(() => x0);
G(() => x1);
}
}
}
";
var src2 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static int F(object a, object b) => 1;
static void F()
{
try
{
}
catch (Exception x0)
{
int x1 = 1;
G(() => x0);
G(() => x1);
G(() => x0); //ok
G(() => F(x0, x1)); //error
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"));
}
[Fact, WorkItem(1504, "https://github.com/dotnet/roslyn/issues/1504")]
public void Lambdas_Insert_CatchFilter1()
{
var src1 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static void F()
{
Exception x1 = null;
try
{
G(() => x1);
}
catch (Exception x0) when (G(() => x0))
{
}
}
}
";
var src2 = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static void F()
{
Exception x1 = null;
try
{
G(() => x1);
}
catch (Exception x0) when (G(() => x0) &&
G(() => x0) && // ok
G(() => x0 != x1)) // error
{
G(() => x0); // ok
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x1", "x0")
);
}
[Fact]
public void Lambdas_Insert_NotSupported()
{
var src1 = @"
using System;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var f = new Func<int, int>(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
activeStatements: ActiveStatementsDescription.Empty,
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Insert_Second_NotSupported()
{
var src1 = @"
using System;
class C
{
void F()
{
var f = new Func<int, int>(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var f = new Func<int, int>(a => a);
var g = new Func<int, int>(b => b);
}
}
";
var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition;
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
activeStatements: ActiveStatementsDescription.Empty,
capabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Insert_FirstInClass_NotSupported()
{
var src1 = @"
using System;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var g = new Func<int, int>(b => b);
}
}
";
var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition;
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
activeStatements: ActiveStatementsDescription.Empty,
capabilities,
// TODO: https://github.com/dotnet/roslyn/issues/52759
// This is incorrect, there should be no rude edit reported
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_CeaseCapture_This()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
var f = new Func<int, int>(a => a + x);
}
}
";
var src2 = @"
using System;
class C
{
int x;
void F()
{
var f = new Func<int, int>(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this"));
}
[Fact]
public void Lambdas_Update_Signature1()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<long, long> f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<long, long> f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature2()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int, int> f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int, int> f) {}
void F()
{
G2((a, b) => a + b);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature3()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, long> f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, long> f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature_Nullable()
{
var src1 = @"
using System;
class C
{
void G1(Func<string, string> f) {}
void G2(Func<string?, string?> f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<string, string> f) {}
void G2(Func<string?, string?> f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Signature_SyntaxOnly1()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G2((a) => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Signature_ReturnType1()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Action<int> f) {}
void F()
{
G1(a => { return 1; });
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Action<int> f) {}
void F()
{
G2(a => { });
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature_ReturnType2()
{
var src1 = "var x = int (int a) => a;";
var src2 = "var x = long (int a) => a;";
var edits = GetMethodEdits(src1, src2);
GetTopEdits(edits).VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "(int a)", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature_BodySyntaxOnly()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G1(a => { return 1; });
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G2(a => 2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Signature_ParameterName1()
{
var src1 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G1(a => 1);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
G2(b => 2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Signature_ParameterRefness1()
{
var src1 = @"
using System;
delegate int D1(ref int a);
delegate int D2(int a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1((ref int a) => 1);
}
}
";
var src2 = @"
using System;
delegate int D1(ref int a);
delegate int D2(int a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2((int a) => 2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "(int a)", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Signature_ParameterRefness2()
{
var src1 = @"
using System;
delegate int D1(ref int a);
delegate int D2(out int a);
class C
{
void G(D1 f) {}
void G(D2 f) {}
void F()
{
G((ref int a) => a = 1);
}
}
";
var src2 = @"
using System;
delegate int D1(ref int a);
delegate int D2(out int a);
class C
{
void G(D1 f) {}
void G(D2 f) {}
void F()
{
G((out int a) => a = 1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "(out int a)", CSharpFeaturesResources.lambda));
}
// Add corresponding test to VB
[Fact(Skip = "TODO")]
public void Lambdas_Update_Signature_CustomModifiers1()
{
var delegateSource = @"
.class public auto ansi sealed D1
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed
{
}
.method public newslot virtual instance int32 [] modopt([mscorlib]System.Int64) Invoke(
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed
{
}
}
.class public auto ansi sealed D2
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed
{
}
.method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke(
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed
{
}
}
.class public auto ansi sealed D3
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed
{
}
.method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke(
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed
{
}
}";
var src1 = @"
using System;
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2(a => a);
}
}
";
MetadataReference delegateDefs;
using (var tempAssembly = IlasmUtilities.CreateTempAssembly(delegateSource))
{
delegateDefs = MetadataReference.CreateFromImage(File.ReadAllBytes(tempAssembly.Path));
}
var edits = GetTopEdits(src1, src2);
// TODO
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Signature_MatchingErrorType()
{
var src1 = @"
using System;
class C
{
void G(Func<Unknown, Unknown> f) {}
void F()
{
G(a => 1);
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<Unknown, Unknown> f) {}
void F()
{
G(a => 2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("F").Single(), preserveLocalVariables: true)
});
}
[Fact]
public void Lambdas_Signature_NonMatchingErrorType()
{
var src1 = @"
using System;
class C
{
void G1(Func<Unknown1, Unknown1> f) {}
void G2(Func<Unknown2, Unknown2> f) {}
void F()
{
G1(a => 1);
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<Unknown1, Unknown1> f) {}
void G2(Func<Unknown2, Unknown2> f) {}
void F()
{
G2(a => 2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", "lambda"));
}
[Fact]
public void Lambdas_Update_DelegateType1()
{
var src1 = @"
using System;
delegate int D1(int a);
delegate int D2(int a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
delegate int D1(int a);
delegate int D2(int a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_SourceType1()
{
var src1 = @"
using System;
delegate C D1(C a);
delegate C D2(C a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
delegate C D1(C a);
delegate C D2(C a);
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_SourceType2()
{
var src1 = @"
using System;
delegate C D1(C a);
delegate B D2(B a);
class B { }
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1(a => a);
}
}
";
var src2 = @"
using System;
delegate C D1(C a);
delegate B D2(B a);
class B { }
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_SourceTypeAndMetadataType1()
{
var src1 = @"
namespace System
{
delegate string D1(string a);
delegate String D2(String a);
class String { }
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G1(a => a);
}
}
}
";
var src2 = @"
namespace System
{
delegate string D1(string a);
delegate String D2(String a);
class String { }
class C
{
void G1(D1 f) {}
void G2(D2 f) {}
void F()
{
G2(a => a);
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Generic1()
{
var src1 = @"
delegate T D1<S, T>(S a, T b);
delegate T D2<S, T>(T a, S b);
class C
{
void G1(D1<int, int> f) {}
void G2(D2<int, int> f) {}
void F()
{
G1((a, b) => a + b);
}
}
";
var src2 = @"
delegate T D1<S, T>(S a, T b);
delegate T D2<S, T>(T a, S b);
class C
{
void G1(D1<int, int> f) {}
void G2(D2<int, int> f) {}
void F()
{
G2((a, b) => a + b);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Generic2()
{
var src1 = @"
delegate int D1<S, T>(S a, T b);
delegate int D2<S, T>(T a, S b);
class C
{
void G1(D1<int, int> f) {}
void G2(D2<int, string> f) {}
void F()
{
G1((a, b) => 1);
}
}
";
var src2 = @"
delegate int D1<S, T>(S a, T b);
delegate int D2<S, T>(T a, S b);
class C
{
void G1(D1<int, int> f) {}
void G2(D2<int, string> f) {}
void F()
{
G2((a, b) => 1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_CapturedParameters1()
{
var src1 = @"
using System;
class C
{
void F(int x1)
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => x1 + a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F(int x1)
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => x1 + a2 + 1);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")]
public void Lambdas_Update_CapturedParameters2()
{
var src1 = @"
using System;
class C
{
void F(int x1)
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => x1 + a2);
return a1;
});
var f3 = new Func<int, int, int>((a1, a2) =>
{
var f4 = new Func<int, int>(a3 => x1 + a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F(int x1)
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => x1 + a2 + 1);
return a1;
});
var f3 = new Func<int, int, int>((a1, a2) =>
{
var f4 = new Func<int, int>(a3 => x1 + a2 + 1);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_CeaseCapture_Closure1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => y + a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a2);
return a1 + y;
});
}
}
";
var edits = GetTopEdits(src1, src2);
// y is no longer captured in f2
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a2", "y", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_CeaseCapture_IndexerParameter1()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2);
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_CeaseCapture_IndexerParameter2()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_CeaseCapture_MethodParameter1()
{
var src1 = @"
using System;
class C
{
void F(int a1, int a2)
{
var f2 = new Func<int, int>(a3 => a1 + a2);
}
}
";
var src2 = @"
using System;
class C
{
void F(int a1, int a2)
{
var f2 = new Func<int, int>(a3 => a1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2"));
}
[Fact]
public void Lambdas_Update_CeaseCapture_MethodParameter2()
{
var src1 = @"
using System;
class C
{
Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2);
}
";
var src2 = @"
using System;
class C
{
Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2"));
}
[Fact]
public void Lambdas_Update_CeaseCapture_LambdaParameter1()
{
var src1 = @"
using System;
class C
{
void F()
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => a1 + a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => a2);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")]
public void Lambdas_Update_CeaseCapture_SetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int D
{
get { return 0; }
set { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var src2 = @"
using System;
class C
{
int D
{
get { return 0; }
set { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value"));
}
[Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")]
public void Lambdas_Update_CeaseCapture_IndexerSetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var src2 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value"));
}
[Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")]
public void Lambdas_Update_CeaseCapture_EventAdderValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { new Action(() => { Console.Write(value); }).Invoke(); }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value"));
}
[Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")]
public void Lambdas_Update_CeaseCapture_EventRemoverValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value"));
}
[Fact]
public void Lambdas_Update_DeleteCapture1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => y + a2);
return y;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{ // error
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a2);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
// y is no longer captured in f2
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y").WithFirstLine("{ // error"));
}
[Fact]
public void Lambdas_Update_Capturing_IndexerGetterParameter1()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2);
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_Capturing_IndexerGetterParameter2()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_Capturing_IndexerSetterParameter1()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a2); } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a1 + a2); } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_Capturing_IndexerSetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { }
}
}
";
var src2 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "set", "value"));
}
[Fact]
public void Lambdas_Update_Capturing_EventAdderValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "remove", "value"));
}
[Fact]
public void Lambdas_Update_Capturing_EventRemoverValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { new Action(() => { Console.Write(value); }).Invoke(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "remove", "value"));
}
[Fact]
public void Lambdas_Update_Capturing_MethodParameter1()
{
var src1 = @"
using System;
class C
{
void F(int a1, int a2)
{
var f2 = new Func<int, int>(a3 => a1);
}
}
";
var src2 = @"
using System;
class C
{
void F(int a1, int a2)
{
var f2 = new Func<int, int>(a3 => a1 + a2);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2"));
}
[Fact]
public void Lambdas_Update_Capturing_MethodParameter2()
{
var src1 = @"
using System;
class C
{
Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1);
}
";
var src2 = @"
using System;
class C
{
Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2"));
}
[Fact]
public void Lambdas_Update_Capturing_LambdaParameter1()
{
var src1 = @"
using System;
class C
{
void F()
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
var f1 = new Func<int, int, int>((a1, a2) =>
{
var f2 = new Func<int, int>(a3 => a1 + a2);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact]
public void Lambdas_Update_StaticToThisOnly1()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
var f = new Func<int, int>(a => a);
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
var f = new Func<int, int>(a => a + x);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact]
public void Lambdas_Update_StaticToThisOnly_Partial()
{
var src1 = @"
using System;
partial class C
{
int x = 1;
partial void F(); // def
}
partial class C
{
partial void F() // impl
{
var f = new Func<int, int>(a => a);
}
}
";
var src2 = @"
using System;
partial class C
{
int x = 1;
partial void F(); // def
}
partial class C
{
partial void F() // impl
{
var f = new Func<int, int>(a => a + x);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this").WithFirstLine("partial void F() // impl"));
}
[Fact]
public void Lambdas_Update_StaticToThisOnly3()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
var f1 = new Func<int, int>(a1 => a1);
var f2 = new Func<int, int>(a2 => a2 + x);
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
var f1 = new Func<int, int>(a1 => a1 + x);
var f2 = new Func<int, int>(a2 => a2 + x);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a1", "this", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_StaticToClosure1()
{
var src1 = @"
using System;
class C
{
void F()
{
int x = 1;
var f1 = new Func<int, int>(a1 => a1);
var f2 = new Func<int, int>(a2 => a2 + x);
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int x = 1;
var f1 = new Func<int, int>(a1 =>
{
return a1 +
x+ // 1
x; // 2
});
var f2 = new Func<int, int>(a2 => a2 + x);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x+ // 1"),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x; // 2"));
}
[Fact]
public void Lambdas_Update_ThisOnlyToClosure1()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 => a1 + x);
var f2 = new Func<int, int>(a2 => a2 + x + y);
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 => a1 + x + y);
var f2 = new Func<int, int>(a2 => a2 + x + y);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Nested1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a2 + y);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a2 + y);
return a1 + y;
});
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Lambdas_Update_Nested2()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a2);
return a1;
});
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
var f1 = new Func<int, int>(a1 =>
{
var f2 = new Func<int, int>(a2 => a1 + a2);
return a1;
});
}
}
";
var edits = GetTopEdits(src1, src2);
// TODO: better diagnostics - identify a1 that causes the capture vs. a1 that doesn't
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1").WithFirstLine("var f1 = new Func<int, int>(a1 =>"));
}
[Fact]
public void Lambdas_Update_Accessing_Closure1()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
int x0 = 0, y0 = 0;
G(a => x0);
G(a => y0);
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
int x0 = 0, y0 = 0;
G(a => x0);
G(a => y0 + x0);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Accessing_Closure2()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x + x0);
G(a => x0);
G(a => y0);
G(a => x1);
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x); // error: disconnecting previously connected closures
G(a => x0);
G(a => y0);
G(a => x1);
}
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "x0", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Accessing_Closure3()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x);
G(a => x0);
G(a => y0);
G(a => x1);
G(a => y1);
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x);
G(a => x0);
G(a => y0);
G(a => x1);
G(a => y1 + x0); // error: connecting previously disconnected closures
}
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda));
}
[Fact]
public void Lambdas_Update_Accessing_Closure4()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x + x0);
G(a => x0);
G(a => y0);
G(a => x1);
G(a => y1);
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0; // Group #0
void F()
{
{ int x0 = 0, y0 = 0; // Group #0
{ int x1 = 0, y1 = 0; // Group #1
G(a => x); // error: disconnecting previously connected closures
G(a => x0);
G(a => y0);
G(a => x1);
G(a => y1 + x0); // error: connecting previously disconnected closures
}
}
}
}
";
var edits = GetTopEdits(src1, src2);
// TODO: "a => x + x0" is matched with "a => y1 + x0", hence we report more errors.
// Including statement distance when matching would help.
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y1", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures"),
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures"));
}
[Fact]
public void Lambdas_Update_Accessing_Closure_NestedLambdas()
{
var src1 = @"
using System;
class C
{
void G(Func<int, Func<int, int>> f) {}
void F()
{
{ int x0 = 0; // Group #0
{ int x1 = 0; // Group #1
G(a => b => x0);
G(a => b => x1);
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, Func<int, int>> f) {}
void F()
{
{ int x0 = 0; // Group #0
{ int x1 = 0; // Group #1
G(a => b => x0);
G(a => b => x1);
G(a => b => x0); // ok
G(a => b => x1); // ok
G(a => b => x0 + x1); // error
}
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"));
}
[Fact]
public void Lambdas_RenameCapturedLocal()
{
var src1 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
int x = 1;
Func<int> f = () => x;
}
}";
var src2 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
int X = 1;
Func<int> f = () => X;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X"));
}
[Fact]
public void Lambdas_RenameCapturedParameter()
{
var src1 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main(int x)
{
Func<int> f = () => x;
}
}";
var src2 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main(int X)
{
Func<int> f = () => X;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void Lambdas_Parameter_To_Discard1()
{
var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);";
var src2 = "var x = new System.Func<int, int, int>((a, _) => 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [b]@45 -> [_]@45");
GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true));
}
[Fact]
public void Lambdas_Parameter_To_Discard2()
{
var src1 = "var x = new System.Func<int, int, int>((int a, int b) => 1);";
var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [int a]@42 -> [_]@42",
"Update [int b]@49 -> [_]@45");
GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true));
}
[Fact]
public void Lambdas_Parameter_To_Discard3()
{
var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);";
var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [a]@42 -> [_]@42",
"Update [b]@45 -> [_]@45");
GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true));
}
#endregion
#region Local Functions
[Fact]
public void LocalFunctions_InExpressionStatement()
{
var src1 = "F(a => a, b => b);";
var src2 = "int x(int a) => a + 1; F(b => b, x);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [a => a]@4 -> [int x(int a) => a + 1;]@2",
"Move [a => a]@4 -> @2",
"Update [F(a => a, b => b);]@2 -> [F(b => b, x);]@25",
"Insert [(int a)]@7",
"Insert [int a]@8",
"Delete [a]@4");
}
[Fact]
public void LocalFunctions_ReorderAndUpdate()
{
var src1 = "int x(int a) => a; int y(int b) => b;";
var src2 = "int y(int b) => b; int x(int a) => a + 1;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int y(int b) => b;]@21 -> @2",
"Update [int x(int a) => a;]@2 -> [int x(int a) => a + 1;]@21");
}
[Fact]
public void LocalFunctions_InWhile()
{
var src1 = "do { /*1*/ } while (F(x));int x(int a) => a + 1;";
var src2 = "while (F(a => a)) { /*1*/ }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [while (F(a => a)) { /*1*/ }]@2",
"Update [int x(int a) => a + 1;]@28 -> [a => a]@11",
"Move [int x(int a) => a + 1;]@28 -> @11",
"Move [{ /*1*/ }]@5 -> @20",
"Insert [a]@11",
"Delete [do { /*1*/ } while (F(x));]@2",
"Delete [(int a)]@33",
"Delete [int a]@34");
}
[Fact]
public void LocalFunctions_InLocalFunction_NoChangeInSignature()
{
var src1 = "int x() { int y(int a) => a; return y(b); }";
var src2 = "int x() { int y() => c; return y(); }";
var edits = GetMethodEdits(src1, src2);
// no changes to the method were made, only within the outer local function body:
edits.VerifyEdits();
}
[Fact]
public void LocalFunctions_InLocalFunction_ChangeInSignature()
{
var src1 = "int x() { int y(int a) => a; return y(b); }";
var src2 = "int x(int z) { int y() => c; return y(); }";
var edits = GetMethodEdits(src1, src2);
// changes were made to the outer local function signature:
edits.VerifyEdits("Insert [int z]@8");
}
[Fact]
public void LocalFunctions_InLambda()
{
var src1 = "F(() => { int y(int a) => a; G(y); });";
var src2 = "F(q => { G(() => y); });";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [() => { int y(int a) => a; G(y); }]@4 -> [q => { G(() => y); }]@4",
"Insert [q]@4",
"Delete [()]@4");
}
[Fact]
public void LocalFunctions_Update_ParameterRefness_NoBodyChange()
{
var src1 = @"void f(ref int a) => a = 1;";
var src2 = @"void f(out int a) => a = 1;";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [ref int a]@9 -> [out int a]@9");
}
[Fact]
public void LocalFunctions_Insert_Static_Top()
{
var src1 = @"
using System;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(int a) => a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_Insert_Static_Nested_ExpressionBodies()
{
var src1 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) => a;
G(localF);
}
}
";
var src2 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) => a;
int localG(int a) => G(localF) + a;
G(localG);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_Insert_Static_Nested_BlockBodies()
{
var src1 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) { return a; }
G(localF);
}
}
";
var src2 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) { return a; }
int localG(int a) { return G(localF) + a; }
G(localG);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_LocalFunction_Replace_Lambda()
{
var src1 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
G(a => a);
}
}
";
var src2 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) { return a; }
G(localF);
}
}
";
var edits = GetTopEdits(src1, src2);
// To be removed when we will enable EnC for local functions
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "localF", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Lambda_Replace_LocalFunction()
{
var src1 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
int localF(int a) { return a; }
G(localF);
}
}
";
var src2 = @"
using System;
class C
{
static int G(Func<int, int> f) => 0;
void F()
{
G(a => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "a", CSharpFeaturesResources.lambda));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_ThisOnly_Top1()
{
var src1 = @"
using System;
class C
{
int x = 0;
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
void F()
{
int G(int a) => x;
}
}
";
var edits = GetTopEdits(src1, src2);
// TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291"), WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_ThisOnly_Top2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
int y = 1;
{
int x = 2;
int f1(int a) => y;
}
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
int y = 1;
{
int x = 2;
var f2 = from a in new[] { 1 } select a + y;
var f3 = from a in new[] { 1 } where x > 0 select a;
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "x", "x"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_ThisOnly_Nested1()
{
var src1 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
int f(int a) => a;
G(f);
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
int G(Func<int, int> f) => 0;
void F()
{
int f(int a) => x;
int g(int a) => G(f);
G(g);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_ThisOnly_Nested2()
{
var src1 = @"
using System;
class C
{
int x = 0;
void F()
{
int f1(int a)
{
int f2(int b)
{
return b;
};
return a;
};
}
}
";
var src2 = @"
using System;
class C
{
int x = 0;
void F()
{
int f1(int a)
{
int f2(int b)
{
return b;
};
int f3(int c)
{
return c + x;
};
return a;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_InsertAndDelete_Scopes1()
{
var src1 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0, y = 0; // Group #0
void F()
{
int x0 = 0, y0 = 0; // Group #1
{ int x1 = 0, y1 = 0; // Group #2
{ int x2 = 0, y2 = 0; // Group #1
{ int x3 = 0, y3 = 0; // Group #2
int f1(int a) => x3 + x1;
int f2(int a) => x0 + y0 + x2;
int f3(int a) => x;
}
}
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
int x = 0, y = 0; // Group #0
void F()
{
int x0 = 0, y0 = 0; // Group #1
{ int x1 = 0, y1 = 0; // Group #2
{ int x2 = 0, y2 = 0; // Group #1
{ int x3 = 0, y3 = 0; // Group #2
int f1(int a) => x3 + x1;
int f2(int a) => x0 + y0 + x2;
int f3(int a) => x;
int f4(int a) => x; // OK
int f5(int a) => x0 + y0; // OK
int f6(int a) => x1 + y0; // error - connecting Group #1 and Group #2
int f7(int a) => x3 + x1; // error - multi-scope (conservative)
int f8(int a) => x + y0; // error - connecting Group #0 and Group #1
int f9(int a) => x + x3; // error - connecting Group #0 and Group #2
}
}
}
}
}
";
var insert = GetTopEdits(src1, src2);
insert.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"),
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3"));
var delete = GetTopEdits(src2, src1);
delete.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"),
Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_ForEach1()
{
var src1 = @"
using System;
class C
{
void F()
{
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
int f0(int a) => x0;
int f1(int a) => x1;
}
}
}
";
var src2 = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
int f0(int a) => x0;
int f1(int a) => x1;
int f2(int a) => x0 + x1; // error: connecting previously disconnected closures
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_Switch1()
{
var src1 = @"
using System;
class C
{
bool G(Func<int> f) => true;
int a = 1;
void F()
{
int x2 = 1;
int f2() => x2;
switch (a)
{
case 1:
int x0 = 1;
int f0() => x0;
break;
case 2:
int x1 = 1;
int f1() => x1;
break;
}
}
}
";
var src2 = @"
using System;
class C
{
bool G(Func<int> f) => true;
int a = 1;
void F()
{
int x2 = 1;
int f2() => x2;
switch (a)
{
case 1:
int x0 = 1;
int f0() => x0;
goto case 2;
case 2:
int x1 = 1;
int f1() => x1;
goto default;
default:
x0 = 1;
x1 = 2;
int f01() => x0 + x1; // ok
int f02() => x0 + x2; // error
break;
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.local_function, "x2", "x0"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Insert_Catch1()
{
var src1 = @"
using System;
class C
{
static void F()
{
try
{
}
catch (Exception x0)
{
int x1 = 1;
int f0() => x0;
int f1() => x1;
}
}
}
";
var src2 = @"
using System;
class C
{
static void F()
{
try
{
}
catch (Exception x0)
{
int x1 = 1;
int f0() => x0;
int f1() => x1;
int f00() => x0; //ok
int f01() => F(x0, x1); //error
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1"));
}
[Fact]
public void LocalFunctions_Insert_NotSupported()
{
var src1 = @"
using System;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
void M()
{
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
activeStatements: ActiveStatementsDescription.Empty,
capabilities: EditAndContinueTestHelpers.BaselineCapabilities,
Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "M", FeaturesResources.local_function));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_This()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
int f(int a) => a + x;
}
}
";
var src2 = @"
using System;
class C
{
int x;
void F()
{
int f(int a) => a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this"));
}
[Fact]
public void LocalFunctions_Update_Signature1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
long f(long a) => a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature2()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(int a, int b) => a + b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature3()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
long f(int a) => a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature_ReturnType1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) { return 1; }
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
void f(int a) { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature_BodySyntaxOnly()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
class C
{
void G1(Func<int, int> f) {}
void G2(Func<int, int> f) {}
void F()
{
int f(int a) { return a; }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_Update_Signature_ParameterName1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(int a) => 1;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(int b) => 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_Update_Signature_ParameterRefness1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(ref int a) => 1;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(int a) => 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature_ParameterRefness2()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(out int a) => 1;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(ref int a) => 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Signature_ParameterRefness3()
{
var src1 = @"
using System;
class C
{
void F()
{
int f(ref int a) => 1;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f(out int a) => 1;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Signature_SemanticErrors()
{
var src1 = @"
using System;
class C
{
void F()
{
Unknown f(Unknown a) => 1;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
Unknown f(Unknown a) => 2;
}
}
";
var edits = GetTopEdits(src1, src2);
// There are semantics errors in the case. The errors are captured during the emit execution.
edits.VerifySemanticDiagnostics();
}
[Fact]
public void LocalFunctions_Update_CapturedParameters1()
{
var src1 = @"
using System;
class C
{
void F(int x1)
{
int f1(int a1, int a2)
{
int f2(int a3) => x1 + a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F(int x1)
{
int f1(int a1, int a2)
{
int f2(int a3) => x1 + a2 + 1;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")]
public void LocalFunctions_Update_CapturedParameters2()
{
var src1 = @"
using System;
class C
{
void F(int x1)
{
int f1(int a1, int a2)
{
int f2(int a3) => x1 + a2;
return a1;
};
int f3(int a1, int a2)
{
int f4(int a3) => x1 + a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F(int x1)
{
int f1(int a1, int a2)
{
int f2(int a3) => x1 + a2 + 1;
return a1;
};
int f3(int a1, int a2)
{
int f4(int a3) => x1 + a2 + 1;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_Closure1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => y + a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => a2;
return a1 + y;
};
}
}
";
var edits = GetTopEdits(src1, src2);
// y is no longer captured in f2
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "f2", "y", CSharpFeaturesResources.local_function));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_IndexerParameter()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_MethodParameter1()
{
var src1 = @"
using System;
class C
{
void F(int a1, int a2)
{
int f2(int a3) => a1 + a2;
}
}
";
var src2 = @"
using System;
class C
{
void F(int a1, int a2)
{
int f2(int a3) => a1;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_LambdaParameter1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f1(int a1, int a2)
{
int f2(int a3) => a1 + a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f1(int a1, int a2)
{
int f2(int a3) => a2;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "int f1(int a1, int a2)\r\n {\r\n int f2(int a3) => a2;\r\n return a1;\r\n };\r\n ", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_SetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int D
{
get { return 0; }
set { void f() { Console.Write(value); } f(); }
}
}
";
var src2 = @"
using System;
class C
{
int D
{
get { return 0; }
set { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_IndexerSetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { void f() { Console.Write(value); } f(); }
}
}
";
var src2 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_EventAdderValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { void f() { Console.Write(value); } f(); }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_CeaseCapture_EventRemoverValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { void f() { Console.Write(value); } f(); }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_DeleteCapture1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => y + a2;
return y;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{ // error
int f1(int a1)
{
int f2(int a2) => a2;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_IndexerGetterParameter2()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_IndexerSetterParameter1()
{
var src1 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a2; } }
}
";
var src2 = @"
using System;
class C
{
Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a1 + a2; } }
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_IndexerSetterValueParameter1()
{
var src1 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { }
}
}
";
var src2 = @"
using System;
class C
{
int this[int a1, int a2]
{
get { return 0; }
set { void f() { Console.Write(value); } f(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "set", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_EventAdderValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { void f() { Console.Write(value); } f(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "remove", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_EventRemoverValueParameter1()
{
var src1 = @"
using System;
class C
{
event Action D
{
add { }
remove { }
}
}
";
var src2 = @"
using System;
class C
{
event Action D
{
add { }
remove { void f() { Console.Write(value); } f(); }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "remove", "value"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_MethodParameter1()
{
var src1 = @"
using System;
class C
{
void F(int a1, int a2)
{
int f2(int a3) => a1;
}
}
";
var src2 = @"
using System;
class C
{
void F(int a1, int a2)
{
int f2(int a3) => a1 + a2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Capturing_LambdaParameter1()
{
var src1 = @"
using System;
class C
{
void F()
{
int f1(int a1, int a2)
{
int f2(int a3) => a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int f1(int a1, int a2)
{
int f2(int a3) => a1 + a2;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_StaticToThisOnly1()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
int f(int a) => a + x;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_StaticToThisOnly_Partial()
{
var src1 = @"
using System;
partial class C
{
int x = 1;
partial void F(); // def
}
partial class C
{
partial void F() // impl
{
int f(int a) => a;
}
}
";
var src2 = @"
using System;
partial class C
{
int x = 1;
partial void F(); // def
}
partial class C
{
partial void F() // impl
{
int f(int a) => a + x;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "F", "this"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_StaticToThisOnly3()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
int f1(int a1) => a1;
int f2(int a2) => a2 + x;
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
int f1(int a1) => a1 + x;
int f2(int a2) => a2 + x;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "f1", "this", CSharpFeaturesResources.local_function));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_StaticToClosure1()
{
var src1 = @"
using System;
class C
{
void F()
{
int x = 1;
int f1(int a1) => a1;
int f2(int a2) => a2 + x;
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int x = 1;
int f1(int a1)
{
return a1 +
x+ // 1
x; // 2
};
int f2(int a2) => a2 + x;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_ThisOnlyToClosure1()
{
var src1 = @"
using System;
class C
{
int x = 1;
void F()
{
int y = 1;
int f1(int a1) => a1 + x;
int f2(int a2) => a2 + x + y;
}
}
";
var src2 = @"
using System;
class C
{
int x = 1;
void F()
{
int y = 1;
int f1(int a1) => a1 + x + y;
int f2(int a2) => a2 + x + y;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_Update_Nested1()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => a2 + y;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => a2 + y;
return a1 + y;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_Update_Nested2()
{
var src1 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => a2;
return a1;
};
}
}
";
var src2 = @"
using System;
class C
{
void F()
{
int y = 1;
int f1(int a1)
{
int f2(int a2) => a1 + a2;
return a1;
};
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void LocalFunctions_RenameCapturedLocal()
{
var src1 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
int x = 1;
int f() => x;
}
}";
var src2 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
int X = 1;
int f() => X;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X"));
}
[Fact]
public void LocalFunctions_RenameCapturedParameter()
{
var src1 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main(int x)
{
int f() => x;
}
}";
var src2 = @"
using System;
using System.Diagnostics;
class Program
{
static void Main(int X)
{
int f() => X;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemantics(
ActiveStatementsDescription.Empty,
new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true)
},
capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities);
}
[Fact]
public void LocalFunction_In_Parameter_InsertWhole()
{
var src1 = @"class Test { void M() { } }";
var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { }]@13 -> [void M() { void local(in int b) { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_In_Parameter_InsertParameter()
{
var src1 = @"class Test { void M() { void local() { throw null; } } }";
var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { void local() { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunction_In_Parameter_Update()
{
var src1 = @"class Test { void M() { void local(int b) { throw null; } } }";
var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { void local(int b) { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ReadOnlyRef_ReturnType_Insert()
{
var src1 = @"class Test { void M() { } }";
var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_ReadOnlyRef_ReturnType_Update()
{
var src1 = @"class Test { void M() { int local() { throw null; } } }";
var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { int local() { throw null; } }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingLambdaReturnType, "local", CSharpFeaturesResources.local_function));
}
[WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")]
[Fact]
public void LocalFunction_AddToInterfaceMethod()
{
var src1 = @"
using System;
interface I
{
static int X = M(() => 1);
static int M() => 1;
static void F()
{
void g() { }
}
}
";
var src2 = @"
using System;
interface I
{
static int X = M(() => { void f3() {} return 2; });
static int M() => 1;
static void F()
{
int f1() => 1;
f1();
void g() { void f2() {} f2(); }
var l = new Func<int>(() => 1);
l();
}
}
";
var edits = GetTopEdits(src1, src2);
// lambdas are ok as they are emitted to a nested type
edits.VerifySemanticDiagnostics(
targetFrameworks: new[] { TargetFramework.NetCoreApp },
expectedDiagnostics: new[]
{
Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f1"),
Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f2"),
Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f3")
});
}
[Fact]
public void LocalFunction_AddStatic()
{
var src1 = @"class Test { void M() { int local() { throw null; } } }";
var src2 = @"class Test { void M() { static int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { int local() { throw null; } }]@13 -> [void M() { static int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_RemoveStatic()
{
var src1 = @"class Test { void M() { static int local() { throw null; } } }";
var src2 = @"class Test { void M() { int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { static int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_AddUnsafe()
{
var src1 = @"class Test { void M() { int local() { throw null; } } }";
var src2 = @"class Test { void M() { unsafe int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { int local() { throw null; } }]@13 -> [void M() { unsafe int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_RemoveUnsafe()
{
var src1 = @"class Test { void M() { unsafe int local() { throw null; } } }";
var src2 = @"class Test { void M() { int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [void M() { unsafe int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13");
edits.VerifyRudeDiagnostics();
}
[Fact]
[WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")]
public void LocalFunction_AddAsync()
{
var src1 = @"class Test { void M() { Task<int> local() => throw null; } }";
var src2 = @"class Test { void M() { async Task<int> local() => throw null; } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
[WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")]
public void LocalFunction_RemoveAsync()
{
var src1 = @"class Test { void M() { async int local() { throw null; } } }";
var src2 = @"class Test { void M() { int local() { throw null; } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "local", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_AddAttribute()
{
var src1 = "void L() { }";
var src2 = "[A]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [void L() { }]@2 -> [[A]void L() { }]@2");
// Get top edits so we can validate rude edits
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_RemoveAttribute()
{
var src1 = "[A]void L() { }";
var src2 = "void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]void L() { }]@2 -> [void L() { }]@2");
// Get top edits so we can validate rude edits
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ReorderAttribute()
{
var src1 = "[A, B]void L() { }";
var src2 = "[B, A]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[A, B]void L() { }]@2 -> [[B, A]void L() { }]@2");
// Get top edits so we can validate rude edits
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_CombineAttributeLists()
{
var src1 = "[A][B]void L() { }";
var src2 = "[A, B]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[A][B]void L() { }]@2 -> [[A, B]void L() { }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_SplitAttributeLists()
{
var src1 = "[A, B]void L() { }";
var src2 = "[A][B]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[A, B]void L() { }]@2 -> [[A][B]void L() { }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_ChangeAttributeListTarget1()
{
var src1 = "[return: A]void L() { }";
var src2 = "[A]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[return: A]void L() { }]@2 -> [[A]void L() { }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ChangeAttributeListTarget2()
{
var src1 = "[A]void L() { }";
var src2 = "[return: A]void L() { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[A]void L() { }]@2 -> [[return: A]void L() { }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function),
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ReturnType_AddAttribute()
{
var src1 = "int L() { return 1; }";
var src2 = "[return: A]int L() { return 1; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [int L() { return 1; }]@2 -> [[return: A]int L() { return 1; }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ReturnType_RemoveAttribute()
{
var src1 = "[return: A]int L() { return 1; }";
var src2 = "int L() { return 1; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[return: A]int L() { return 1; }]@2 -> [int L() { return 1; }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunction_ReturnType_ReorderAttribute()
{
var src1 = "[return: A, B]int L() { return 1; }";
var src2 = "[return: B, A]int L() { return 1; }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[return: A, B]int L() { return 1; }]@2 -> [[return: B, A]int L() { return 1; }]@2");
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_Parameter_AddAttribute()
{
var src1 = "void L(int i) { }";
var src2 = "void L([A]int i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [int i]@9 -> [[A]int i]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter));
}
[Fact]
public void LocalFunction_Parameter_RemoveAttribute()
{
var src1 = "void L([A]int i) { }";
var src2 = "void L(int i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[A]int i]@9 -> [int i]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter));
}
[Fact]
public void LocalFunction_Parameter_ReorderAttribute()
{
var src1 = "void L([A, B]int i) { }";
var src2 = "void L([B, A]int i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[A, B]int i]@9 -> [[B, A]int i]@9");
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunction_TypeParameter_AddAttribute()
{
var src1 = "void L<T>(T i) { }";
var src2 = "void L<[A] T>(T i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [T]@9 -> [[A] T]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter));
}
[Fact]
public void LocalFunction_TypeParameter_RemoveAttribute()
{
var src1 = "void L<[A] T>(T i) { }";
var src2 = "void L<T>(T i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [[A] T]@9 -> [T]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter));
}
[Fact]
public void LocalFunction_TypeParameter_ReorderAttribute()
{
var src1 = "void L<[A, B] T>(T i) { }";
var src2 = "void L<[B, A] T>(T i) { }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits("Update [[A, B] T]@9 -> [[B, A] T]@9");
GetTopEdits(edits).VerifyRudeDiagnostics();
}
[Fact]
public void LocalFunctions_TypeParameter_Insert1()
{
var src1 = @"void L() {}";
var src2 = @"void L<A>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [<A>]@8",
"Insert [A]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Insert2()
{
var src1 = @"void L<A>() {}";
var src2 = @"void L<A,B>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [<A>]@8 -> [<A,B>]@8",
"Insert [B]@11");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Delete1()
{
var src1 = @"void L<A>() {}";
var src2 = @"void L() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [<A>]@8",
"Delete [A]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Delete2()
{
var src1 = @"void L<A,B>() {}";
var src2 = @"void L<B>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [<A,B>]@8 -> [<B>]@8",
"Delete [A]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Update()
{
var src1 = @"void L<A>() {}";
var src2 = @"void L<B>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [A]@9 -> [B]@9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Theory]
[InlineData("Enum", "Delegate")]
[InlineData("IDisposable", "IDisposable, new()")]
public void LocalFunctions_TypeParameter_Constraint_Clause_Update(string oldConstraint, string newConstraint)
{
var src1 = "void L<A>() where A : " + oldConstraint + " {}";
var src2 = "void L<A>() where A : " + newConstraint + " {}";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [where A : " + oldConstraint + "]@14 -> [where A : " + newConstraint + "]@14");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Theory]
[InlineData("nonnull")]
[InlineData("struct")]
[InlineData("class")]
[InlineData("new()")]
[InlineData("unmanaged")]
[InlineData("System.IDisposable")]
[InlineData("System.Delegate")]
public void LocalFunctions_TypeParameter_Constraint_Clause_Delete(string oldConstraint)
{
var src1 = "void L<A>() where A : " + oldConstraint + " {}";
var src2 = "void L<A>() {}";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Delete [where A : " + oldConstraint + "]@14");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Constraint_Clause_Add()
{
var src1 = "void L<A,B>() where A : new() {}";
var src2 = "void L<A,B>() where A : new() where B : System.IDisposable {}";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Insert [where B : System.IDisposable]@32");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_Reorder()
{
var src1 = @"void L<A,B>() {}";
var src2 = @"void L<B,A>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@11 -> @9");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
[Fact]
public void LocalFunctions_TypeParameter_ReorderAndUpdate()
{
var src1 = @"void L<A,B>() {}";
var src2 = @"void L<B,C>() {} ";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [B]@11 -> @9",
"Update [A]@9 -> [C]@11");
GetTopEdits(edits).VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter),
Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function));
}
#endregion
#region Queries
[Fact]
public void Queries_Update_Signature_Select1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1.0} select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause));
}
[Fact]
public void Queries_Update_Signature_Select2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} select a.ToString();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause));
}
[Fact]
public void Queries_Update_Signature_From1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} from b in new[] {2} select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from long a in new[] {1} from b in new[] {2} select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "from", CSharpFeaturesResources.from_clause));
}
[Fact]
public void Queries_Update_Signature_From2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from System.Int64 a in new[] {1} from b in new[] {2} select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from long a in new[] {1} from b in new[] {2} select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_Update_Signature_From3()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} from b in new[] {2} select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new List<int>() from b in new List<int>() select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_Update_Signature_Let1()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} let b = 1 select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} let b = 1.0 select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "let", CSharpFeaturesResources.let_clause));
}
[Fact]
public void Queries_Update_Signature_OrderBy1()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} orderby a + 1.0 descending, a + 2 ascending select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 1.0 descending", CSharpFeaturesResources.orderby_clause));
}
[Fact]
public void Queries_Update_Signature_OrderBy2()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} orderby a + 1 descending, a + 2.0 ascending select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 2.0 ascending", CSharpFeaturesResources.orderby_clause));
}
[Fact]
public void Queries_Update_Signature_Join1()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a equals b select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1.0} on a equals b select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause));
}
[Fact]
public void Queries_Update_Signature_Join2()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a equals b select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join byte b in new[] {1} on a equals b select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause));
}
[Fact]
public void Queries_Update_Signature_Join3()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a + 1 equals b select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a + 1.0 equals b select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause));
}
[Fact]
public void Queries_Update_Signature_Join4()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a equals b + 1 select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} join b in new[] {1} on a equals b + 1.0 select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause));
}
[Fact]
public void Queries_Update_Signature_GroupBy1()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1 by a into z select z;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1.0 by a into z select z;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause));
}
[Fact]
public void Queries_Update_Signature_GroupBy2()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} group a by a into z select z;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} group a by a + 1.0 into z select z;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause));
}
[Fact]
public void Queries_Update_Signature_GroupBy_MatchingErrorTypes()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
Unknown G1(int a) => null;
Unknown G2(int a) => null;
void F()
{
var result = from a in new[] {1} group G1(a) by a into z select z;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
Unknown G1(int a) => null;
Unknown G2(int a) => null;
void F()
{
var result = from a in new[] {1} group G2(a) by a into z select z;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_Update_Signature_GroupBy_NonMatchingErrorTypes()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
Unknown1 G1(int a) => null;
Unknown2 G2(int a) => null;
void F()
{
var result = from a in new[] {1} group G1(a) by a into z select z;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
Unknown1 G1(int a) => null;
Unknown2 G2(int a) => null;
void F()
{
var result = from a in new[] {1} group G2(a) by a into z select z;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause));
}
[Fact]
public void Queries_FromSelect_Update1()
{
var src1 = "F(from a in b from x in y select c);";
var src2 = "F(from a in c from x in z select c + 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [from a in b]@4 -> [from a in c]@4",
"Update [from x in y]@16 -> [from x in z]@16",
"Update [select c]@28 -> [select c + 1]@28");
}
[Fact]
public void Queries_FromSelect_Update2()
{
var src1 = "F(from a in b from x in y select c);";
var src2 = "F(from a in b from x in z select c);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [from x in y]@16 -> [from x in z]@16");
}
[Fact]
public void Queries_FromSelect_Update3()
{
var src1 = "F(from a in await b from x in y select c);";
var src2 = "F(from a in await c from x in y select c);";
var edits = GetMethodEdits(src1, src2, MethodKind.Async);
edits.VerifyEdits(
"Update [await b]@34 -> [await c]@34");
}
[Fact]
public void Queries_Select_Reduced1()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} where a > 0 select a;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} where a > 0 select a + 1;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_Select_Reduced2()
{
var src1 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} where a > 0 select a + 1;
}
}
";
var src2 = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var result = from a in new[] {1} where a > 0 select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_FromSelect_Delete()
{
var src1 = "F(from a in b from c in d select a + c);";
var src2 = "F(from a in b select c + 1);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [select a + c]@28 -> [select c + 1]@16",
"Delete [from c in d]@16");
}
[Fact]
public void Queries_JoinInto_Update()
{
var src1 = "F(from a in b join b in c on a equals b into g1 select g1);";
var src2 = "F(from a in b join b in c on a equals b into g2 select g2);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [select g1]@50 -> [select g2]@50",
"Update [into g1]@42 -> [into g2]@42");
}
[Fact]
public void Queries_JoinIn_Update()
{
var src1 = "F(from a in b join b in await A(1) on a equals b select g);";
var src2 = "F(from a in b join b in await A(2) on a equals b select g);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [await A(1)]@26 -> [await A(2)]@26");
}
[Fact]
public void Queries_GroupBy_Update()
{
var src1 = "F(from a in b group a by a.x into g select g);";
var src2 = "F(from a in b group z by z.y into h select h);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [group a by a.x]@17 -> [group z by z.y]@17",
"Update [into g select g]@32 -> [into h select h]@32",
"Update [select g]@40 -> [select h]@40");
}
[Fact]
public void Queries_OrderBy_Reorder()
{
var src1 = "F(from a in b orderby a.x, a.b descending, a.c ascending select a.d);";
var src2 = "F(from a in b orderby a.x, a.c ascending, a.b descending select a.d);";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [a.c ascending]@46 -> @30");
}
[Fact]
public void Queries_GroupBy_Reduced1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a by a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1.0 by a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause));
}
[Fact]
public void Queries_GroupBy_Reduced2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a by a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1 by a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_GroupBy_Reduced3()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1.0 by a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a by a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause));
}
[Fact]
public void Queries_GroupBy_Reduced4()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a + 1 by a;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] {1} group a by a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_OrderBy_Continuation_Update()
{
var src1 = "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);";
var src2 = "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);";
var edits = GetMethodEdits(src1, src2);
var actual = ToMatchingPairs(edits.Match);
var expected = new MatchingPairs
{
{ "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);", "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);" },
{ "from a in b", "from a in b" },
{ "orderby a.x, a.b descending select a.d into z orderby a.c ascending select z", "orderby a.x, a.c ascending select a.d into z orderby a.b descending select z" },
{ "orderby a.x, a.b descending", "orderby a.x, a.c ascending" },
{ "a.x", "a.x" },
{ "a.b descending", "a.c ascending" },
{ "select a.d", "select a.d" },
{ "into z orderby a.c ascending select z", "into z orderby a.b descending select z" },
{ "orderby a.c ascending select z", "orderby a.b descending select z" },
{ "orderby a.c ascending", "orderby a.b descending" },
{ "a.c ascending", "a.b descending" },
{ "select z", "select z" }
};
expected.AssertEqual(actual);
edits.VerifyEdits(
"Update [a.b descending]@30 -> [a.c ascending]@30",
"Update [a.c ascending]@74 -> [a.b descending]@73");
}
[Fact]
public void Queries_CapturedTransparentIdentifiers_FromClause1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a) > 0
where Z(() => b) > 0
where Z(() => a) > 0
where Z(() => b) > 0
select a;
}
}";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a) > 1 // update
where Z(() => b) > 2 // update
where Z(() => a) > 3 // update
where Z(() => b) > 4 // update
select a;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_CapturedTransparentIdentifiers_LetClause1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
let b = Z(() => a)
select a + b;
}
}";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
let b = Z(() => a + 1)
select a - b;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_CapturedTransparentIdentifiers_JoinClause1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g
select Z(() => g.First());
}
}";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g
select Z(() => g.Last());
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_CeaseCapturingTransparentIdentifiers1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a + b) > 0
select a;
}
}";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a + 1) > 0
select a;
}
}";
var edits = GetTopEdits(src1, src2);
// TODO: better location (the variable, not the from clause)
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotCapturingVariable, "from b in new[] { 2 }", "b"));
}
[Fact]
public void Queries_CapturingTransparentIdentifiers1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a + 1) > 0
select a;
}
}";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 2 }
where Z(() => a + b) > 0
select a;
}
}";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "b", "b"));
}
[Fact]
public void Queries_AccessingCapturedTransparentIdentifier1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select 1;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
[Fact]
public void Queries_AccessingCapturedTransparentIdentifier2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 1 }
where Z(() => a) > 0
select b;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 1 }
where Z(() => a) > 0
select a + b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause));
}
[Fact]
public void Queries_AccessingCapturedTransparentIdentifier3()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select Z(() => 1);
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select Z(() => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Queries_NotAccessingCapturedTransparentIdentifier1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 1 }
where Z(() => a) > 0
select a + b;
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
from b in new[] { 1 }
where Z(() => a) > 0
select b;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "select", "a", CSharpFeaturesResources.select_clause));
}
[Fact]
public void Queries_NotAccessingCapturedTransparentIdentifier2()
{
var src1 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select Z(() => 1);
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
int Z(Func<int> f) => 1;
void F()
{
var result = from a in new[] { 1 }
where Z(() => a) > 0
select Z(() => a);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause),
Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda));
}
[Fact]
public void Queries_Insert1()
{
var src1 = @"
using System;
using System.Linq;
class C
{
void F()
{
}
}
";
var src2 = @"
using System;
using System.Linq;
class C
{
void F()
{
var result = from a in new[] { 1 } select a;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
#endregion
#region Yield
[Fact]
public void Yield_Update1()
{
var src1 = @"
class C
{
static IEnumerable<int> F()
{
yield return 1;
yield return 2;
yield break;
}
}
";
var src2 = @"
class C
{
static IEnumerable<int> F()
{
yield return 3;
yield break;
yield return 4;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield break;", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.yield_break_statement),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 4;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement));
}
[Fact]
public void Yield_Delete1()
{
var src1 = @"
yield return 1;
yield return 2;
yield return 3;
";
var src2 = @"
yield return 1;
yield return 3;
";
var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator);
bodyEdits.VerifyEdits(
"Delete [yield return 2;]@42");
}
[Fact]
public void Yield_Delete2()
{
var src1 = @"
class C
{
static IEnumerable<int> F()
{
yield return 1;
yield return 2;
yield return 3;
}
}
";
var src2 = @"
class C
{
static IEnumerable<int> F()
{
yield return 1;
yield return 3;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.yield_return_statement));
}
[Fact]
public void Yield_Insert1()
{
var src1 = @"
yield return 1;
yield return 3;
";
var src2 = @"
yield return 1;
yield return 2;
yield return 3;
yield return 4;
";
var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator);
bodyEdits.VerifyEdits(
"Insert [yield return 2;]@42",
"Insert [yield return 4;]@76");
}
[Fact]
public void Yield_Insert2()
{
var src1 = @"
class C
{
static IEnumerable<int> F()
{
yield return 1;
yield return 3;
}
}
";
var src2 = @"
class C
{
static IEnumerable<int> F()
{
yield return 1;
yield return 2;
yield return 3;
yield return 4;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "yield return 4;", CSharpFeaturesResources.yield_return_statement),
Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement));
}
[Fact]
public void MissingIteratorStateMachineAttribute()
{
var src1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 1;
}
}
";
var src2 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore },
Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static IEnumerable<int> F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute"));
}
[Fact]
public void MissingIteratorStateMachineAttribute2()
{
var src1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
return null;
}
}
";
var src2 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore });
}
#endregion
#region Await
/// <summary>
/// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>.
/// </summary>
[Fact]
public void AwaitSpilling_OK()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await F(1);
if (await F(1)) { Console.WriteLine(1); }
if (await F(1)) { Console.WriteLine(1); }
if (F(1, await F(1))) { Console.WriteLine(1); }
if (await F(1)) { Console.WriteLine(1); }
do { Console.WriteLine(1); } while (await F(1));
for (var x = await F(1); await G(1); await H(1)) { Console.WriteLine(1); }
foreach (var x in await F(1)) { Console.WriteLine(1); }
using (var x = await F(1)) { Console.WriteLine(1); }
lock (await F(1)) { Console.WriteLine(1); }
lock (a = await F(1)) { Console.WriteLine(1); }
var a = await F(1), b = await G(1);
a = await F(1);
switch (await F(2)) { case 1: return b = await F(1); }
return await F(1);
}
static async Task<int> G() => await F(1);
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await F(2);
if (await F(1)) { Console.WriteLine(2); }
if (await F(2)) { Console.WriteLine(1); }
if (F(1, await F(1))) { Console.WriteLine(2); }
while (await F(1)) { Console.WriteLine(1); }
do { Console.WriteLine(2); } while (await F(2));
for (var x = await F(2); await G(2); await H(2)) { Console.WriteLine(2); }
foreach (var x in await F(2)) { Console.WriteLine(2); }
using (var x = await F(2)) { Console.WriteLine(1); }
lock (await F(2)) { Console.WriteLine(2); }
lock (a = await F(2)) { Console.WriteLine(2); }
var a = await F(2), b = await G(2);
b = await F(2);
switch (await F(2)) { case 1: return b = await F(2); }
return await F(2);
}
static async Task<int> G() => await F(2);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
/// <summary>
/// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>.
/// </summary>
[Fact]
public void AwaitSpilling_Errors()
{
var src1 = @"
class C
{
static async Task<int> F()
{
F(1, await F(1));
F(1, await F(1));
F(await F(1));
await F(await F(1));
if (F(1, await F(1))) { Console.WriteLine(1); }
var a = F(1, await F(1)), b = F(1, await G(1));
b = F(1, await F(1));
b += await F(1);
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
F(2, await F(1));
F(1, await F(2));
F(await F(2));
await F(await F(2));
if (F(2, await F(1))) { Console.WriteLine(1); }
var a = F(1, await F(2)), b = F(1, await G(2));
b = F(1, await F(2));
b += await F(2);
}
}
";
var edits = GetTopEdits(src1, src2);
// consider: these edits can be allowed if we get more sophisticated
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(1, await F(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(await F(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "await F(await F(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1))"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "b = F(1, await F(2));"),
Diagnostic(RudeEditKind.AwaitStatementUpdate, "b += await F(2);"));
}
[Fact]
public void Await_Delete1()
{
var src1 = @"
await F(1);
await F(2);
await F(3);
";
var src2 = @"
await F(1);
await F(3);
";
var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async);
bodyEdits.VerifyEdits(
"Delete [await F(2);]@37",
"Delete [await F(2)]@37");
}
[Fact]
public void Await_Delete2()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await F(1);
{
await F(2);
}
await F(3);
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await F(1);
{
F(2);
}
await F(3);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "F(2);", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Delete3()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await F(await F(1));
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await F(1);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "await F(1);", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Delete4()
{
var src1 = @"
class C
{
static async Task<int> F() => await F(await F(1));
}
";
var src2 = @"
class C
{
static async Task<int> F() => await F(1);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Delete5()
{
var src1 = @"
class C
{
static async Task<int> F() => await F(1);
}
";
var src2 = @"
class C
{
static async Task<int> F() => F(1);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression));
}
[Fact]
public void AwaitForEach_Delete1()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await foreach (var x in G()) { }
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
foreach (var x in G()) { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var x in G())", CSharpFeaturesResources.foreach_statement));
}
[Fact]
public void AwaitForEach_Delete2()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await foreach (var (x, y) in G()) { }
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
foreach (var (x, y) in G()) { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var (x, y) in G())", CSharpFeaturesResources.foreach_statement));
}
[Fact]
public void AwaitForEach_Delete3()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await foreach (var x in G()) { }
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_foreach_statement));
}
[Fact]
public void AwaitUsing_Delete1()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await using D x = new D(), y = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await using D x = new D();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration));
}
[Fact]
public void AwaitUsing_Delete2()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await using D x = new D(), y = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await using D y = new D();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration));
}
[Fact]
public void AwaitUsing_Delete3()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await using D x = new D(), y = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration),
Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration));
}
[Fact]
public void AwaitUsing_Delete4()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await using D x = new D(), y = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
using D x = new D(), y = new D();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty,
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration),
Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration));
}
[Fact]
public void Await_Insert1()
{
var src1 = @"
await F(1);
await F(3);
";
var src2 = @"
await F(1);
await F(2);
await F(3);
await F(4);
";
var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async);
bodyEdits.VerifyEdits(
"Insert [await F(2);]@37",
"Insert [await F(4);]@63",
"Insert [await F(2)]@37",
"Insert [await F(4)]@63");
}
[Fact]
public void Await_Insert2()
{
var src1 = @"
class C
{
static async IEnumerable<int> F()
{
await F(1);
await F(3);
}
}
";
var src2 = @"
class C
{
static async IEnumerable<int> F()
{
await F(1);
await F(2);
await F(3);
await F(4);
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Insert3()
{
var src1 = @"
class C
{
static async IEnumerable<int> F()
{
await F(1);
await F(3);
}
}
";
var src2 = @"
class C
{
static async IEnumerable<int> F()
{
await F(await F(1));
await F(await F(2));
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Delete, "await", CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Insert4()
{
var src1 = @"
class C
{
static async Task<int> F() => await F(1);
}
";
var src2 = @"
class C
{
static async Task<int> F() => await F(await F(1));
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression));
}
[Fact]
public void Await_Insert5()
{
var src1 = @"
class C
{
static Task<int> F() => F(1);
}
";
var src2 = @"
class C
{
static async Task<int> F() => await F(1);
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics();
}
[Fact]
public void AwaitForEach_Insert_Ok()
{
var src1 = @"
class C
{
static async Task<int> F()
{
foreach (var x in G()) { }
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await foreach (var x in G()) { }
}
}
";
var edits = GetTopEdits(src1, src2);
// ok to add awaits if there were none before and no active statements
edits.VerifyRudeDiagnostics();
}
[Fact]
public void AwaitForEach_Insert()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await Task.FromResult(1);
foreach (var x in G()) { }
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await Task.FromResult(1);
await foreach (var x in G()) { }
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "await", "await"));
}
[Fact]
public void AwaitUsing_Insert1()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await using D x = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await using D x = new D(), y = new D();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "y = new D()", CSharpFeaturesResources.asynchronous_using_declaration));
}
[Fact]
public void AwaitUsing_Insert2()
{
var src1 = @"
class C
{
static async Task<int> F()
{
await G();
using D x = new D();
}
}
";
var src2 = @"
class C
{
static async Task<int> F()
{
await G();
await using D x = new D();
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.Insert, "await", "await"));
}
[Fact]
public void Await_Update()
{
var src1 = @"
class C
{
static async IAsyncEnumerable<int> F()
{
await foreach (var x in G()) { }
await Task.FromResult(1);
await Task.FromResult(1);
await Task.FromResult(1);
yield return 1;
yield break;
yield break;
}
}
";
var src2 = @"
class C
{
static async IAsyncEnumerable<int> F()
{
await foreach (var (x,y) in G()) { }
await foreach (var x in G()) { }
await using D x = new D(), y = new D();
await Task.FromResult(1);
await Task.FromResult(1);
yield return 1;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifyRudeDiagnostics(
Diagnostic(RudeEditKind.ChangingStateMachineShape, "await foreach (var x in G()) { }", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_foreach_statement),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "x = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "y = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.await_expression),
Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 1;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement));
}
[Fact]
public void MissingAsyncStateMachineAttribute1()
{
var src1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await new Task();
return 1;
}
}
";
var src2 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await new Task();
return 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
targetFrameworks: new[] { TargetFramework.MinimalAsync },
expectedDiagnostics: new[]
{
Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static async Task<int> F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute")
});
}
[Fact]
public void MissingAsyncStateMachineAttribute2()
{
var src1 = @"
using System.Threading.Tasks;
class C
{
static Task<int> F()
{
return null;
}
}
";
var src2 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await new Task();
return 2;
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
targetFrameworks: new[] { TargetFramework.MinimalAsync });
}
[Fact]
public void SemanticError_AwaitInPropertyAccessor()
{
var src1 = @"
using System.Threading.Tasks;
class C
{
public Task<int> P
{
get
{
await Task.Delay(1);
return 1;
}
}
}
";
var src2 = @"
using System.Threading.Tasks;
class C
{
public Task<int> P
{
get
{
await Task.Delay(2);
return 1;
}
}
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics();
}
#endregion
#region Out Var
[Fact]
public void OutVarType_Update()
{
var src1 = @"
M(out var y);
";
var src2 = @"
M(out int y);
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [M(out var y);]@4 -> [M(out int y);]@4");
}
[Fact]
public void OutVarNameAndType_Update()
{
var src1 = @"
M(out var y);
";
var src2 = @"
M(out int z);
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [M(out var y);]@4 -> [M(out int z);]@4",
"Update [y]@14 -> [z]@14");
}
[Fact]
public void OutVar_Insert()
{
var src1 = @"
M();
";
var src2 = @"
M(out int y);
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [M();]@4 -> [M(out int y);]@4",
"Insert [y]@14");
}
[Fact]
public void OutVar_Delete()
{
var src1 = @"
M(out int y);
";
var src2 = @"
M();
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [M(out int y);]@4 -> [M();]@4",
"Delete [y]@14");
}
#endregion
#region Pattern
[Fact]
public void ConstantPattern_Update()
{
var src1 = @"
if ((o is null) && (y == 7)) return 3;
if (a is 7) return 5;
";
var src2 = @"
if ((o1 is null) && (y == 7)) return 3;
if (a is 77) return 5;
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if ((o is null) && (y == 7)) return 3;]@4 -> [if ((o1 is null) && (y == 7)) return 3;]@4",
"Update [if (a is 7) return 5;]@44 -> [if (a is 77) return 5;]@45");
}
[Fact]
public void DeclarationPattern_Update()
{
var src1 = @"
if (!(o is int i) && (y == 7)) return;
if (!(a is string s)) return;
if (!(b is string t)) return;
if (!(c is int j)) return;
";
var src2 = @"
if (!(o1 is int i) && (y == 7)) return;
if (!(a is int s)) return;
if (!(b is string t1)) return;
if (!(c is int)) return;
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if (!(o is int i) && (y == 7)) return;]@4 -> [if (!(o1 is int i) && (y == 7)) return;]@4",
"Update [if (!(a is string s)) return;]@44 -> [if (!(a is int s)) return;]@45",
"Update [if (!(c is int j)) return;]@106 -> [if (!(c is int)) return;]@105",
"Update [t]@93 -> [t1]@91",
"Delete [j]@121");
}
[Fact]
public void DeclarationPattern_Reorder()
{
var src1 = @"if ((a is int i) && (b is int j)) { A(); }";
var src2 = @"if ((b is int j) && (a is int i)) { A(); }";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if ((a is int i) && (b is int j)) { A(); }]@2 -> [if ((b is int j) && (a is int i)) { A(); }]@2",
"Reorder [j]@32 -> @16");
}
[Fact]
public void VarPattern_Update()
{
var src1 = @"
if (o is (var x, var y)) return;
if (o4 is (string a, var (b, c))) return;
if (o2 is var (e, f, g)) return;
if (o3 is var (k, l, m)) return;
";
var src2 = @"
if (o is (int x, int y1)) return;
if (o1 is (var a, (var b, string c1))) return;
if (o7 is var (g, e, f)) return;
if (o3 is (string k, int l2, int m)) return;
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if (o is (var x, var y)) return;]@4 -> [if (o is (int x, int y1)) return;]@4",
"Update [if (o4 is (string a, var (b, c))) return;]@38 -> [if (o1 is (var a, (var b, string c1))) return;]@39",
"Update [if (o2 is var (e, f, g)) return;]@81 -> [if (o7 is var (g, e, f)) return;]@87",
"Reorder [g]@102 -> @102",
"Update [if (o3 is var (k, l, m)) return;]@115 -> [if (o3 is (string k, int l2, int m)) return;]@121",
"Update [y]@25 -> [y1]@25",
"Update [c]@67 -> [c1]@72",
"Update [l]@133 -> [l2]@146");
}
[Fact]
public void PositionalPattern_Update1()
{
var src1 = @"var r = (x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 };";
var src2 = @"var r = ((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 }]@10 -> [((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 }]@10",
"Update [(0, var b, int c) when c > 1 => 2]@29 -> [(_, int b1, double c1) when c1 > 2 => c1]@31",
"Reorder [c]@44 -> @39",
"Update [c]@44 -> [b1]@39",
"Update [b]@37 -> [c1]@50",
"Update [when c > 1]@47 -> [when c1 > 2]@54");
}
[Fact]
public void PositionalPattern_Update2()
{
var src1 = @"var r = (x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 };";
var src2 = @"var r = ((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [(x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 }]@10 -> [((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 }]@10",
"Update [(var a, 3, 4) => a]@29 -> [(var a1, 3, 4) => a1 * 2]@31",
"Update [(1, 1, Point { X: 0 } p) => 3]@49 -> [(1, 1, Point { Y: 0 } p1) => 3]@57",
"Update [a]@34 -> [a1]@36",
"Update [p]@71 -> [p1]@79");
}
[Fact]
public void PositionalPattern_Reorder()
{
var src1 = @"var r = (x, y, z) switch {
(1, 2, 3) => 0,
(var a, 3, 4) => a,
(0, var b, int c) when c > 1 => 2,
(1, 1, Point { X: 0 } p) => 3,
_ => 4
};
";
var src2 = @"var r = ((x, y, z)) switch {
(1, 1, Point { X: 0 } p) => 3,
(0, var b, int c) when c > 1 => 2,
(var a, 3, 4) => a,
(1, 2, 3) => 0,
_ => 4
};
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
@"Update [(x, y, z) switch {
(1, 2, 3) => 0,
(var a, 3, 4) => a,
(0, var b, int c) when c > 1 => 2,
(1, 1, Point { X: 0 } p) => 3,
_ => 4
}]@10 -> [((x, y, z)) switch {
(1, 1, Point { X: 0 } p) => 3,
(0, var b, int c) when c > 1 => 2,
(var a, 3, 4) => a,
(1, 2, 3) => 0,
_ => 4
}]@10",
"Reorder [(var a, 3, 4) => a]@47 -> @100",
"Reorder [(0, var b, int c) when c > 1 => 2]@68 -> @64",
"Reorder [(1, 1, Point { X: 0 } p) => 3]@104 -> @32");
}
[Fact]
public void PropertyPattern_Update()
{
var src1 = @"
if (address is { State: ""WA"" }) return 1;
if (obj is { Color: Color.Purple }) return 2;
if (o is string { Length: 5 } s) return 3;
";
var src2 = @"
if (address is { ZipCode: 98052 }) return 4;
if (obj is { Size: Size.M }) return 2;
if (o is string { Length: 7 } s7) return 5;
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [if (address is { State: \"WA\" }) return 1;]@4 -> [if (address is { ZipCode: 98052 }) return 4;]@4",
"Update [if (obj is { Color: Color.Purple }) return 2;]@47 -> [if (obj is { Size: Size.M }) return 2;]@50",
"Update [if (o is string { Length: 5 } s) return 3;]@94 -> [if (o is string { Length: 7 } s7) return 5;]@90",
"Update [return 1;]@36 -> [return 4;]@39",
"Update [s]@124 -> [s7]@120",
"Update [return 3;]@127 -> [return 5;]@124");
}
[Fact]
public void RecursivePatterns_Reorder()
{
var src1 = @"var r = obj switch
{
string s when s.Length > 0 => (s, obj1) switch
{
(""a"", int i) => i,
_ => 0
},
int i => i * i,
_ => -1
};
";
var src2 = @"var r = obj switch
{
int i => i * i,
string s when s.Length > 0 => (s, obj1) switch
{
(""a"", int i) => i,
_ => 0
},
_ => -1
};
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [int i => i * i]@140 -> @29",
"Move [i]@102 -> @33",
"Move [i]@144 -> @123");
}
[Fact]
public void CasePattern_UpdateInsert()
{
var src1 = @"
switch(shape)
{
case Circle c: return 1;
default: return 4;
}
";
var src2 = @"
switch(shape)
{
case Circle c1: return 1;
case Point p: return 0;
default: return 4;
}
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case Circle c: return 1;]@26 -> [case Circle c1: return 1;]@26",
"Insert [case Point p: return 0;]@57",
"Insert [case Point p:]@57",
"Insert [return 0;]@71",
"Update [c]@38 -> [c1]@38",
"Insert [p]@68");
}
[Fact]
public void CasePattern_UpdateDelete()
{
var src1 = @"
switch(shape)
{
case Point p: return 0;
case Circle c: A(c); break;
default: return 4;
}
";
var src2 = @"
switch(shape)
{
case Circle c1: A(c1); break;
default: return 4;
}
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case Circle c: A(c); break;]@55 -> [case Circle c1: A(c1); break;]@26",
"Update [A(c);]@70 -> [A(c1);]@42",
"Update [c]@67 -> [c1]@38",
"Delete [case Point p: return 0;]@26",
"Delete [case Point p:]@26",
"Delete [p]@37",
"Delete [return 0;]@40");
}
[Fact]
public void WhenCondition_Update()
{
var src1 = @"
switch(shape)
{
case Circle c when (c < 10): return 1;
case Circle c when (c > 100): return 2;
}
";
var src2 = @"
switch(shape)
{
case Circle c when (c < 5): return 1;
case Circle c2 when (c2 > 100): return 2;
}
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [case Circle c when (c < 10): return 1;]@26 -> [case Circle c when (c < 5): return 1;]@26",
"Update [case Circle c when (c > 100): return 2;]@70 -> [case Circle c2 when (c2 > 100): return 2;]@69",
"Update [when (c < 10)]@40 -> [when (c < 5)]@40",
"Update [c]@82 -> [c2]@81",
"Update [when (c > 100)]@84 -> [when (c2 > 100)]@84");
}
[Fact]
public void CasePatternWithWhenCondition_UpdateReorder()
{
var src1 = @"
switch(shape)
{
case Rectangle r: return 0;
case Circle c when (c.Radius < 10): return 1;
case Circle c when (c.Radius > 100): return 2;
}
";
var src2 = @"
switch(shape)
{
case Circle c when (c.Radius > 99): return 2;
case Circle c when (c.Radius < 10): return 1;
case Rectangle r: return 0;
}
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [case Circle c when (c.Radius < 10): return 1;]@59 -> @77",
"Reorder [case Circle c when (c.Radius > 100): return 2;]@110 -> @26",
"Update [case Circle c when (c.Radius > 100): return 2;]@110 -> [case Circle c when (c.Radius > 99): return 2;]@26",
"Move [c]@71 -> @38",
"Update [when (c.Radius > 100)]@124 -> [when (c.Radius > 99)]@40",
"Move [c]@122 -> @89");
}
#endregion
#region Ref
[Fact]
public void Ref_Update()
{
var src1 = @"
ref int a = ref G(new int[] { 1, 2 });
ref int G(int[] p) { return ref p[1]; }
";
var src2 = @"
ref int32 a = ref G1(new int[] { 1, 2 });
ref int G1(int[] p) { return ref p[2]; }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [ref int G1(int[] p) { return ref p[2]; }]@47",
"Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4",
"Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = ref G1(new int[] { 1, 2 })]@14");
}
[Fact]
public void Ref_Insert()
{
var src1 = @"
int a = G(new int[] { 1, 2 });
int G(int[] p) { return p[1]; }
";
var src2 = @"
ref int32 a = ref G1(new int[] { 1, 2 });
ref int G1(int[] p) { return ref p[2]; }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [int G(int[] p) { return p[1]; }]@36 -> [ref int G1(int[] p) { return ref p[2]; }]@47",
"Update [int a = G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4",
"Update [a = G(new int[] { 1, 2 })]@8 -> [a = ref G1(new int[] { 1, 2 })]@14");
}
[Fact]
public void Ref_Delete()
{
var src1 = @"
ref int a = ref G(new int[] { 1, 2 });
ref int G(int[] p) { return ref p[1]; }
";
var src2 = @"
int32 a = G1(new int[] { 1, 2 });
int G1(int[] p) { return p[2]; }
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [int G1(int[] p) { return p[2]; }]@39",
"Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [int32 a = G1(new int[] { 1, 2 })]@4",
"Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = G1(new int[] { 1, 2 })]@10");
}
#endregion
#region Tuples
[Fact]
public void TupleType_LocalVariables()
{
var src1 = @"
(int a, string c) x = (a, string2);
(int a, int b) y = (3, 4);
(int a, int b, int c) z = (5, 6, 7);
";
var src2 = @"
(int a, int b) x = (a, string2);
(int a, int b, string c) z1 = (5, 6, 7);
(int a, int b) y2 = (3, 4);
";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(
"Reorder [(int a, int b, int c) z = (5, 6, 7);]@69 -> @39",
"Update [(int a, string c) x = (a, string2)]@4 -> [(int a, int b) x = (a, string2)]@4",
"Update [(int a, int b, int c) z = (5, 6, 7)]@69 -> [(int a, int b, string c) z1 = (5, 6, 7)]@39",
"Update [z = (5, 6, 7)]@91 -> [z1 = (5, 6, 7)]@64",
"Update [y = (3, 4)]@56 -> [y2 = (3, 4)]@96");
}
[Fact]
public void TupleElementName()
{
var src1 = @"class C { (int a, int b) F(); }";
var src2 = @"class C { (int x, int b) F(); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int a, int b) F();]@10 -> [(int x, int b) F();]@10");
}
[Fact]
public void TupleInField()
{
var src1 = @"class C { private (int, int) _x = (1, 2); }";
var src2 = @"class C { private (int, string) _y = (1, 2); }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [(int, int) _x = (1, 2)]@18 -> [(int, string) _y = (1, 2)]@18",
"Update [_x = (1, 2)]@29 -> [_y = (1, 2)]@32");
}
[Fact]
public void TupleInProperty()
{
var src1 = @"class C { public (int, int) Property1 { get { return (1, 2); } } }";
var src2 = @"class C { public (int, string) Property2 { get { return (1, string.Empty); } } }";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public (int, int) Property1 { get { return (1, 2); } }]@10 -> [public (int, string) Property2 { get { return (1, string.Empty); } }]@10",
"Update [get { return (1, 2); }]@40 -> [get { return (1, string.Empty); }]@43");
}
[Fact]
public void TupleInDelegate()
{
var src1 = @"public delegate void EventHandler1((int, int) x);";
var src2 = @"public delegate void EventHandler2((int, int) y);";
var edits = GetTopEdits(src1, src2);
edits.VerifyEdits(
"Update [public delegate void EventHandler1((int, int) x);]@0 -> [public delegate void EventHandler2((int, int) y);]@0",
"Update [(int, int) x]@35 -> [(int, int) y]@35");
}
#endregion
#region With Expressions
[Fact]
public void WithExpression_PropertyAdd()
{
var src1 = @"var x = y with { X = 1 };";
var src2 = @"var x = y with { X = 1, Y = 2 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6");
}
[Fact]
public void WithExpression_PropertyDelete()
{
var src1 = @"var x = y with { X = 1, Y = 2 };";
var src2 = @"var x = y with { X = 1 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 2 }]@6 -> [x = y with { X = 1 }]@6");
}
[Fact]
public void WithExpression_PropertyChange()
{
var src1 = @"var x = y with { X = 1 };";
var src2 = @"var x = y with { Y = 1 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { Y = 1 }]@6");
}
[Fact]
public void WithExpression_PropertyValueChange()
{
var src1 = @"var x = y with { X = 1, Y = 1 };";
var src2 = @"var x = y with { X = 1, Y = 2 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6");
}
[Fact]
public void WithExpression_PropertyValueReorder()
{
var src1 = @"var x = y with { X = 1, Y = 1 };";
var src2 = @"var x = y with { Y = 1, X = 1 };";
var edits = GetMethodEdits(src1, src2);
edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { Y = 1, X = 1 }]@6");
}
#endregion
#region Top Level Statements
[Fact]
public void TopLevelStatement_CaptureArgs()
{
var src1 = @"
using System;
var x = new Func<string>(() => ""Hello"");
Console.WriteLine(x());
";
var src2 = @"
using System;
var x = new Func<string>(() => ""Hello"" + args[0]);
Console.WriteLine(x());
";
var edits = GetTopEdits(src1, src2);
// TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.CapturingVariable, "using System;\r\n\r\nvar x = new Func<string>(() => \"Hello\" + args[0]);\r\n\r\nConsole.WriteLine(x());\r\n", "args"));
}
[Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")]
public void TopLevelStatement_InsertMultiScopeCapture()
{
var src1 = @"
using System;
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
int f0(int a) => x0;
int f1(int a) => x1;
}
";
var src2 = @"
using System;
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
int f0(int a) => x0;
int f1(int a) => x1;
int f2(int a) => x0 + x1; // error: connecting previously disconnected closures
}
";
var edits = GetTopEdits(src1, src2);
edits.VerifySemanticDiagnostics(
Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1"));
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./docs/ide/api-designs/Workspace and Source Generated Documents.md | # Source Generator / Workspace API Proposal
In Visual Studio 16.8, we shipped only limited source generator support in the Workspace APIs; any caller requesting a Compilation would get a Compilation that contained the correct generated SyntaxTrees, but there was no way to know where the trees came from, nor interact with the generated documents in any other way. This proposal describes how we are going to shore these APIs up.
## SourceGeneratedDocument Type
A new type will be introduced, `SourceGeneratedDocument`, that inherits from `Document`. `GetSyntaxTreeAsync`, `GetSyntaxRootAsync`, and `GetTextAsync` (and the corresponding synchronous and Try methods) will return the generated text or trees. The trees will be the same instances as would be found in the `Compilation.SyntaxTrees`.
The `Id` of the `Document` will be generated dynamically by the workspace. As much as possible, the Id will be persistent between snapshots as much as is practical. When a generator produces a document, it provides a "hint name" which is intended to be used for the IDE to allow for 'permanence' between runs. `DocumentId`s are defined by a GUID in the implementation, so to ensure the DocumentId can be stable, we will generate the GUID as a hash of the hint name, the generator name, and any other pertinent information. Although the implementation may do extra caching behind the scenes where it won't have to recompute hashes in this way, this will ensure the `DocumentId` stays stable even if the caches fail to avoid any surprises.
`SourceGeneratedDocument` will have some additional members:
1. `HintName`: the exact hint name that was provided by the generator.
1. `SourceGenerator`: the ISourceGenerator instance that produced this document.
For now, any _mutation_ of a SourceGeneratedDocument will not be supported. Calls to the following members will throw `NotSupportedException`:
1. `WithText`
2. `WithSyntaxRoot`
3. `WithName`
4. `WithFolders`
5. `WithFilePath`
Down the road, I hope that we might offer an extension point for a source generator to participate in WithText and WithSyntaxRoot. In many cases the generated source may contain expressions that are verbatim C# (think a .cshtml file having a C# section), and so we could have WithText or WithSyntaxRoot apply the resulting edit back to the document that the verbatim C# came from. The design of this is out of scope here.
## APIs on `Project`
### Existing API: `Documents`
Note the Documents collection will _not_ change, and will only include regular documents. It cannot include source generated documents because since it is a property access, there is no opportunity to make this async, nor have any way to express cancellation. Since a generator could produce any number of documents, there's simply no way to make this answer quickly without fundamentally taking a different approach to the API.
### New API: `ImmutableArray<SourceGeneratedDocument> GetSourceGeneratedDocumentsAsync(CancelationToken)`
This will run generators if they have not already ran, and then return a `SourceGeneratedDocument` for each generated document.
The implementation of this will run `GetCompilationAsync` if the documents have not been generated; if the Compilation had already been generated, we would have cached the generated document information and so this would be cheap. We will hold onto the list of documents strongly (the tree will be a recoverable tree), so even if the `Compilation` is GC'ed we won't have to recompute this part a second time.
### New API: `SourceGeneratedDocument? GetSourceGeneratedDocumentAsync(DocumentId, CancellationToken)`
Fetches a single document by ID; equivalent to calling the API and filtering down to the right document.
### Existing API: `GetDocument(SyntaxTree)`
No changes, it will potentially return a `SourceGeneratedDocument` now. Callers _may_ have to check whether it's a generated document before they try to offer a fix or refactoring on the document.
This API is the hardest API to figure out what to do in this entire spec. If it doesn't return generated documents, many features would break, since it's very common to assume that if a syntax tree exists in a `Compilation`, that there must be a `Document` that matches it. However, some features might _not_ want to see a generated document returned here because then they're going to try to modify that, and that won't make sense either. An audit of the code fixes in Roslyn discovered that for many of the places that would need an update to _ignore_ a generated document would also need an update to deal with the null reference that would come back from `GetDocument`.
The other odd thing here is whether this function needs to be asynchronous or not. The current belief is no, because the only way you can have gotten a SyntaxTree to pass to it from the same `Solution` is either from:
1. The `Compilation` or a symbol that came from it, which means generators have ran.
2. You inspected some `SourceGeneratedDocument` and got it's tree, which means that generator has already ran.
The only surprise you might run into is taking a `SyntaxTree` from an earlier `Solution`, passing it to a newer `Solution`, and getting a document that no longer exists because in the later `Solution` is no longer generating this document. However, passing a `SyntaxTree` between snapshots like that is questionable in the first place. Any code that is working with multiple snapshots and knew that a Document between the snapshots had the same tree could have done something like this, but that code is potentially broken _anyways_ with source generators since now one tree can change due to another tree changing.
## APIs on `Workspace`
### Existing APIs: `OpenDocument(DocumentId)`/`CloseDocument(DocumentId)`
This API today is used by any feature that wants to tell the host to open a file. This will accept the DocumentId of a generated document and work properly.
### Existing APIs: `IsDocumentOpen(DocumentId)` / `GetOpenDocumentIds(...)`
These will behave no differently than before.
### Existing APIs: `OnDocumentOpened`/`OnDocumentClosed`
These APIs today associate a Workspace and a SourceTextContainer. Besides allowing APIs like `GetOpenDocumentInCurrentContextWithChanges` to work, this also ensures that a change to the text buffer updates the Workspace automatically. For generated documents, it will wire up the first part (assocating the container) but will not update the Workspace contents when the buffer changes. This is because the updates flow in the _other_ direction, and for now that updating is being managed by a Visual Studio-layer component. Further refactoring may move the core updating into the Workspace layer directly, but not for now.
## APIs for Fetching Documents
### Existing API: `GetOpenDocumentInCurrentContextWithChanges(ITextSnapshot)`
Because we want source generated documents to have the same IDE affordances as any other open file, this API will still work but return a `SourceGeneratedDocument` in that case. Some special handling is required though due to asynchrony. If a user has a generated document open, we may have an async process running in the background that may be trying to refresh this open generated document. The call to `GetOpenDocumentInCurrentContextWithChanges` however will "freeze" the generated document to match the `ITextSnapshot`, so any calls to `GetSourceGeneratedDocumentsAsync()` will return that exact same text, even if that content is out of sync with what would be generated given that project state.
This does mean that in this case, the contents of this document won't match if you compared the document to Workspace.CurrentSolution, got the generated document by ID, and then asked for it's text. This however is OK: that can _always_ be the case for any caller to `GetOpenDocumentInCurrentContextWithChanges` since it always forks to match the `ITextSnapshot`. We're just making the window where this can happen to be bigger than usual. | # Source Generator / Workspace API Proposal
In Visual Studio 16.8, we shipped only limited source generator support in the Workspace APIs; any caller requesting a Compilation would get a Compilation that contained the correct generated SyntaxTrees, but there was no way to know where the trees came from, nor interact with the generated documents in any other way. This proposal describes how we are going to shore these APIs up.
## SourceGeneratedDocument Type
A new type will be introduced, `SourceGeneratedDocument`, that inherits from `Document`. `GetSyntaxTreeAsync`, `GetSyntaxRootAsync`, and `GetTextAsync` (and the corresponding synchronous and Try methods) will return the generated text or trees. The trees will be the same instances as would be found in the `Compilation.SyntaxTrees`.
The `Id` of the `Document` will be generated dynamically by the workspace. As much as possible, the Id will be persistent between snapshots as much as is practical. When a generator produces a document, it provides a "hint name" which is intended to be used for the IDE to allow for 'permanence' between runs. `DocumentId`s are defined by a GUID in the implementation, so to ensure the DocumentId can be stable, we will generate the GUID as a hash of the hint name, the generator name, and any other pertinent information. Although the implementation may do extra caching behind the scenes where it won't have to recompute hashes in this way, this will ensure the `DocumentId` stays stable even if the caches fail to avoid any surprises.
`SourceGeneratedDocument` will have some additional members:
1. `HintName`: the exact hint name that was provided by the generator.
1. `SourceGenerator`: the ISourceGenerator instance that produced this document.
For now, any _mutation_ of a SourceGeneratedDocument will not be supported. Calls to the following members will throw `NotSupportedException`:
1. `WithText`
2. `WithSyntaxRoot`
3. `WithName`
4. `WithFolders`
5. `WithFilePath`
Down the road, I hope that we might offer an extension point for a source generator to participate in WithText and WithSyntaxRoot. In many cases the generated source may contain expressions that are verbatim C# (think a .cshtml file having a C# section), and so we could have WithText or WithSyntaxRoot apply the resulting edit back to the document that the verbatim C# came from. The design of this is out of scope here.
## APIs on `Project`
### Existing API: `Documents`
Note the Documents collection will _not_ change, and will only include regular documents. It cannot include source generated documents because since it is a property access, there is no opportunity to make this async, nor have any way to express cancellation. Since a generator could produce any number of documents, there's simply no way to make this answer quickly without fundamentally taking a different approach to the API.
### New API: `ImmutableArray<SourceGeneratedDocument> GetSourceGeneratedDocumentsAsync(CancelationToken)`
This will run generators if they have not already ran, and then return a `SourceGeneratedDocument` for each generated document.
The implementation of this will run `GetCompilationAsync` if the documents have not been generated; if the Compilation had already been generated, we would have cached the generated document information and so this would be cheap. We will hold onto the list of documents strongly (the tree will be a recoverable tree), so even if the `Compilation` is GC'ed we won't have to recompute this part a second time.
### New API: `SourceGeneratedDocument? GetSourceGeneratedDocumentAsync(DocumentId, CancellationToken)`
Fetches a single document by ID; equivalent to calling the API and filtering down to the right document.
### Existing API: `GetDocument(SyntaxTree)`
No changes, it will potentially return a `SourceGeneratedDocument` now. Callers _may_ have to check whether it's a generated document before they try to offer a fix or refactoring on the document.
This API is the hardest API to figure out what to do in this entire spec. If it doesn't return generated documents, many features would break, since it's very common to assume that if a syntax tree exists in a `Compilation`, that there must be a `Document` that matches it. However, some features might _not_ want to see a generated document returned here because then they're going to try to modify that, and that won't make sense either. An audit of the code fixes in Roslyn discovered that for many of the places that would need an update to _ignore_ a generated document would also need an update to deal with the null reference that would come back from `GetDocument`.
The other odd thing here is whether this function needs to be asynchronous or not. The current belief is no, because the only way you can have gotten a SyntaxTree to pass to it from the same `Solution` is either from:
1. The `Compilation` or a symbol that came from it, which means generators have ran.
2. You inspected some `SourceGeneratedDocument` and got it's tree, which means that generator has already ran.
The only surprise you might run into is taking a `SyntaxTree` from an earlier `Solution`, passing it to a newer `Solution`, and getting a document that no longer exists because in the later `Solution` is no longer generating this document. However, passing a `SyntaxTree` between snapshots like that is questionable in the first place. Any code that is working with multiple snapshots and knew that a Document between the snapshots had the same tree could have done something like this, but that code is potentially broken _anyways_ with source generators since now one tree can change due to another tree changing.
## APIs on `Workspace`
### Existing APIs: `OpenDocument(DocumentId)`/`CloseDocument(DocumentId)`
This API today is used by any feature that wants to tell the host to open a file. This will accept the DocumentId of a generated document and work properly.
### Existing APIs: `IsDocumentOpen(DocumentId)` / `GetOpenDocumentIds(...)`
These will behave no differently than before.
### Existing APIs: `OnDocumentOpened`/`OnDocumentClosed`
These APIs today associate a Workspace and a SourceTextContainer. Besides allowing APIs like `GetOpenDocumentInCurrentContextWithChanges` to work, this also ensures that a change to the text buffer updates the Workspace automatically. For generated documents, it will wire up the first part (assocating the container) but will not update the Workspace contents when the buffer changes. This is because the updates flow in the _other_ direction, and for now that updating is being managed by a Visual Studio-layer component. Further refactoring may move the core updating into the Workspace layer directly, but not for now.
## APIs for Fetching Documents
### Existing API: `GetOpenDocumentInCurrentContextWithChanges(ITextSnapshot)`
Because we want source generated documents to have the same IDE affordances as any other open file, this API will still work but return a `SourceGeneratedDocument` in that case. Some special handling is required though due to asynchrony. If a user has a generated document open, we may have an async process running in the background that may be trying to refresh this open generated document. The call to `GetOpenDocumentInCurrentContextWithChanges` however will "freeze" the generated document to match the `ITextSnapshot`, so any calls to `GetSourceGeneratedDocumentsAsync()` will return that exact same text, even if that content is out of sync with what would be generated given that project state.
This does mean that in this case, the contents of this document won't match if you compared the document to Workspace.CurrentSolution, got the generated document by ID, and then asked for it's text. This however is OK: that can _always_ be the case for any caller to `GetOpenDocumentInCurrentContextWithChanges` since it always forks to match the `ITextSnapshot`. We're just making the window where this can happen to be bigger than usual. | -1 |
dotnet/roslyn | 56,266 | Handle projects added during break state | For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | tmat | "2021-09-08T21:34:56Z" | "2021-09-09T17:38:34Z" | 9292724c00e59ee81a11ea6c70a8e54ef64d528c | 76311a0936e8c894288971374c795e21dceec37a | Handle projects added during break state. For now we just avoid crashes. Further improvements are tracked by https://github.com/dotnet/roslyn/issues/1204
Fixes [AB#1371694](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371694) | ./src/Features/VisualBasic/Portable/ConvertIfToSwitch/VisualBasicConvertIfToSwitchCodeRefactoringProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.ConvertIfToSwitch
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertIfToSwitch
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertIfToSwitch), [Shared]>
Partial Friend NotInheritable Class VisualBasicConvertIfToSwitchCodeRefactoringProvider
Inherits AbstractConvertIfToSwitchCodeRefactoringProvider(Of ExecutableStatementSyntax, ExpressionSyntax, SyntaxNode, SyntaxNode)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Public Overrides Function GetTitle(forSwitchExpression As Boolean) As String
Debug.Assert(Not forSwitchExpression)
Return VBFeaturesResources.Convert_to_Select_Case
End Function
Public Overrides Function CreateAnalyzer(syntaxFacts As ISyntaxFacts, options As ParseOptions) As Analyzer
Return New VisualBasicAnalyzer(syntaxFacts, Feature.RangePattern Or Feature.RelationalPattern Or Feature.InequalityPattern)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.ConvertIfToSwitch
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertIfToSwitch
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertIfToSwitch), [Shared]>
Partial Friend NotInheritable Class VisualBasicConvertIfToSwitchCodeRefactoringProvider
Inherits AbstractConvertIfToSwitchCodeRefactoringProvider(Of ExecutableStatementSyntax, ExpressionSyntax, SyntaxNode, SyntaxNode)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Public Overrides Function GetTitle(forSwitchExpression As Boolean) As String
Debug.Assert(Not forSwitchExpression)
Return VBFeaturesResources.Convert_to_Select_Case
End Function
Public Overrides Function CreateAnalyzer(syntaxFacts As ISyntaxFacts, options As ParseOptions) As Analyzer
Return New VisualBasicAnalyzer(syntaxFacts, Feature.RangePattern Or Feature.RelationalPattern Or Feature.InequalityPattern)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.OrdinaryMethodSymbols.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
private void {|Definition:Goo|}() { }
void Bar()
{
[|Go$$o|]();
[|Goo|]();
B.Goo();
new C().[|Goo|]();
new C().goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodCaseSensitivity(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class C
private sub {|Definition:Goo|}()
end sub
sub Bar()
[|Go$$o|]()
[|Goo|]()
B.Goo()
Console.WriteLine(new C().[|Goo|]())
Console.WriteLine(new C().[|goo|]())
end sub
end class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_GetAwaiter(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
public class C
{
public TaskAwaiter<bool> {|Definition:Get$$Awaiter|}() => Task.FromResult(true).GetAwaiter();
static async void M(C c)
{
[|await|] c;
[|await|] c;
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_GetAwaiter_VB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class C
Public Function {|Definition:Get$$Awaiter|}() As TaskAwaiter(Of Boolean)
End Function
Shared Async Sub M(c As C)
[|Await|] c
End Sub
End Class
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_GetAwaiterInAnotherDocument(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
public class C
{
public TaskAwaiter<bool> {|Definition:Get$$Awaiter|}() => Task.FromResult(true).GetAwaiter();
}
]]></Document>
<Document><![CDATA[
class D
{
static async void M(C c)
{
[|await|] c;
[|await|] c;
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_Deconstruction(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public void {|Definition:Decons$$truct|}(out int x1, out int x2) { x1 = 1; x2 = 2; }
public void M()
{
[|var (x1, x2)|] = this;
foreach ([|var (y1, y2)|] in new[] { this }) { }
[|(x1, (x2, _))|] = (1, this);
(x1, x2) = (1, 2);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(24184, "https://github.com/dotnet/roslyn/issues/24184")>
Public Async Function FindReferences_DeconstructionInAnotherDocument(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public static class Extensions
{
public void {|Definition:Decons$$truct|}(this C c, out int x1, out int x2) { x1 = 1; x2 = 2; }
}
</Document>
<Document>
class C
{
public void M()
{
[|var (x1, x2)|] = this;
foreach ([|var (y1, y2)|] in new[] { this }) { }
[|(x1, (x2, _))|] = (1, this);
(x1, x2) = (1, 2);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_ForEachDeconstructionOnItsOwn(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public static class Extensions
{
public void {|Definition:Decons$$truct|}(this C c, out int x1, out int x2) { x1 = 1; x2 = 2; }
}
class C
{
public void M()
{
foreach ([|var (y1, y2)|] in new[] { this }) { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_NestedDeconstruction(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public static class Extensions
{
public void {|Definition:Decons$$truct|}(this C c, out int x1, out C x2) { x1 = 1; x2 = null; }
}
class C
{
public void M()
{
[|var (y1, (y2, y3))|] = this;
[|(y1, (y2, y3))|] = (1, this);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_NestedDeconstruction2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public static class Extensions
{
public void Deconstruct(this int i, out int x1, out C x2) { x1 = 1; x2 = null; }
public void {|Definition:Decons$$truct|}(this C c, out int x1, out int x2) { x1 = 1; x2 = 2; }
}
class C
{
public void M()
{
[|var (y1, (y2, y3))|] = 1;
var (z1, z2) = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_NestedDeconstruction3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public static class Extensions
{
public void {|Definition:Decons$$truct|}(this int i, out int x1, out C x2) { x1 = 1; x2 = null; }
public void Deconstruct(this C c, out int x1, out int x2) { x1 = 1; x2 = 2; }
}
class C
{
public void M()
{
[|var (y1, (y2, y3))|] = 1;
[|var (z1, z2)|] = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_DeconstructionAcrossLanguage(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document><![CDATA[
Public Class Deconstructable
Public Sub {|Definition:Decons$$truct|}(<System.Runtime.InteropServices.Out> ByRef x1 As Integer, <System.Runtime.InteropServices.Out> ByRef x2 As Integer)
x1 = 1
x2 = 2
End Sub
End Class
]]></Document>
</Project>
<Project Language="C#" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class C
{
public void M(Deconstructable d)
{
[|var (x1, x2)|] = d;
foreach ([|var (y1, y2)|] in new[] { d }) { }
[|(x1, (x2, _))|] = (1, d);
(x1, x2) = (1, 2);
d.[|Deconstruct|](out var t1, out var t2);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverride1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual void {|Definition:Go$$o|}() { }
void Bar() { [|Goo|](); }
}
class D : C
{
public override void {|Definition:Goo|}() { }
void Quux() { [|Goo|](); }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverride2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual void {|Definition:Goo|}() { }
void Bar() { [|Goo|](); }
}
class D : C
{
public override void {|Definition:Go$$o|}() { }
void Quux() { [|Goo|](); }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverride3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual void Goo() { }
void Bar() { Goo(); }
}
class D : C
{
public override void Goo() { }
void Quux() { Goo(); }
}
class E : D
{
public new void {|Definition:Go$$o|}() { }
void Z() { [|Goo|](); }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverride_InMetadata_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
// Will walk up to Object.ToString
public override string {|Definition:To$$String|}() { }
}
class O
{
public override string {|Definition:ToString|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverride_InMetadata_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
// Will walk up to Object.ToString
public override string {|Definition:To$$String|}() { }
}
class O
{
public override string ToString() { }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverrideCrossLanguage(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<Document>
public class C
{
public virtual void {|Definition:Go$$o|}() { }
}
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSharpAssembly</ProjectReference>
<Document>
class D : Inherits C
public overrides sub {|Definition:Goo|}()
end sub
private sub Bar()
[|Goo|]()
end sub
sub class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceInheritance_FromReference_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Goo|}();
}
class C1 : I1
{
public void {|Definition:Goo|}()
{
}
}
interface I2 : I1
{
void {|Definition:Goo|}();
void Bar();
}
class C2 : I2
{
public void Bar()
{
[|Goo$$|]();
}
public void {|Definition:Goo|}();
{
}
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceInheritance_FromReference_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Goo|}();
}
class C1 : I1
{
public void Goo()
{
}
}
interface I2 : I1
{
void {|Definition:Goo|}();
void Bar();
}
class C2 : I2
{
public void Bar()
{
[|Goo$$|]();
}
public void {|Definition:Goo|}();
{
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceInheritance_FromDefinition_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Go$$o|}();
}
class C1 : I1
{
public void {|Definition:Goo|}()
{
}
}
interface I2 : I1
{
void {|Definition:Goo|}();
void Bar();
}
class C2 : I2
{
public void Bar()
{
[|Goo|]();
}
public void {|Definition:Goo|}();
{
}
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceInheritance_FromDefinition_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Go$$o|}();
}
class C1 : I1
{
public void {|Definition:Goo|}()
{
}
}
interface I2 : I1
{
void Goo();
void Bar();
}
class C2 : I2
{
public void Bar()
{
[|Goo|]();
}
public void {|Definition:Goo|}();
{
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceImplementation1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IGoo
{
void {|Definition:Goo|}();
}
class C
{
public void {|Definition:Go$$o|}() { }
}
class D : C, IGoo
{
void Quux()
{
IGoo f;
f.[|Goo|]();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529616")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceImplementationVB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface IGoo
Sub {|Definition:TestSub|}()
End Interface
Class Goo
Implements IGoo
Public Sub {|Definition:MethodWithADifferentName|}() Implements IGoo.[|$$TestSub|]
End Function
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceImplementation2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IGoo
{
void {|Definition:G$$oo|}();
}
class C
{
public void {|Definition:Goo|}() { }
void Zap()
{
this.[|Goo|]();
[|Goo|]();
}
}
class D : C, IGoo
{
void Quux()
{
IGoo f;
f.[|Goo|]();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceImplementationSingleFileOnly(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Zap()
{
IGoo goo;
goo.[|Go$$o|]();
}
}
class D : IGoo
{
void Quux()
{
IGoo f;
f.[|Goo|]();
}
}
</Document>
<Document>
interface IGoo
{
void {|Definition:Goo|}();
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host, searchSingleFileOnly:=True)
End Function
<WorkItem(522786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522786")>
<WorkItem(34107, "https://github.com/dotnet/roslyn/issues/34107")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34107"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceDispose1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : System.IDisposable
{
public void {|Definition:Disp$$ose|}() { }
void Zap()
{
[|using|] (new C())
{
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(522786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522786")>
<WorkItem(34107, "https://github.com/dotnet/roslyn/issues/34107")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34107"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceDispose2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : System.IDisposable
{
public void {|Definition:Disp$$ose|}() { }
void Zap()
{
[|using|] (new D())
{
}
}
}
class D : System.IDisposable
{
public void {|Definition:Dispose|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Collections;
class C : IEnumerable
{
public IEnumerator {|Definition:GetEnumera$$tor|}() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Collections;
class C
{
public struct Enumerator : IEnumerator
{
public object Current { get { } }
public bool {|Definition:MoveNe$$xt|}() { }
}
public Enumerator GetEnumerator() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Collections;
class C
{
public struct Enumerator : IEnumerator
{
public object {|Definition:Cu$$rrent|} { get { } }
public bool MoveNext() { }
}
public Enumerator GetEnumerator() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
class C : IEnumerable<int>
{
public IEnumerator<int> {|Definition:GetEnumera$$tor|}() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable5(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
class C
{
public struct Enumerator<T> : IEnumerator<T>
{
public T Current { get { } }
public bool {|Definition:MoveNe$$xt|}() { }
}
public Enumerator<int> GetEnumerator() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable6(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
class C
{
public struct Enumerator<T> : IEnumerator<T>
{
public object {|Definition:Cu$$rrent|} { get { } }
public bool MoveNext() { }
}
public Enumerator<T> GetEnumerator() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(634818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634818")>
<WorkItem(34106, "https://github.com/dotnet/roslyn/issues/34106")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34106"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodLinqWhere1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
class C
{
void Zap()
{
var q = from v in this
[|where|] v > 21
select v;
}
}
static class Extensions
{
public static IEnumerable<int> {|Definition:Whe$$re|}(this IEnumerable<int> source, Func<int, bool> predicate) => throw null;
public static IEnumerable<int> Select(this IEnumerable<int> source, Func<int, int> func) => throw null;
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(636943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636943")>
<WorkItem(34106, "https://github.com/dotnet/roslyn/issues/34106")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34106"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodLinqWhere2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
class C
{
void Zap()
{
var q = from v in this
[|w$$here|] v > 21
select v;
}
}
static class Extensions
{
public static IEnumerable<int> {|Definition:Where|}(this IEnumerable<int> source, Func<int, bool> predicate) => throw null;
public static IEnumerable<int> Select(this IEnumerable<int> source, Func<int, int> func) => throw null;
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(636943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636943")>
<WorkItem(34106, "https://github.com/dotnet/roslyn/issues/34106")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34106"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodLinqSelect1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
class C
{
void Zap()
{
var q = from v in this
where v > 21
[|select|] v + 1;
}
}
static class Extensions
{
public static IEnumerable<int> Where(this IEnumerable<int> source, Func<int, bool> predicate) => throw null;
public static IEnumerable<int> {|Definition:Sel$$ect|}(this IEnumerable<int> source, Func<int, int> func) => throw null;
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(636943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636943")>
<WorkItem(34106, "https://github.com/dotnet/roslyn/issues/34106")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34106"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodLinqSelect2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
class C
{
void Zap()
{
var q = from v in this
where v > 21
[|sel$$ect|] v + 1;
}
}
static class Extensions
{
public static IEnumerable<int> Where(this IEnumerable<int> source, Func<int, bool> predicate) => throw null;
public static IEnumerable<int> {|Definition:Select|}(this IEnumerable<int> source, Func<int, int> func) => throw null;
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(528936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528936")>
<WorkItem(34105, "https://github.com/dotnet/roslyn/issues/34105")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34105"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodMonitorEnter(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><;
[|lock|] (new C())
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(528936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528936")>
<WorkItem(34105, "https://github.com/dotnet/roslyn/issues/34105")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34105"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodMonitorExit(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><;
[|lock|] (new C())
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_CSharpInaccessibleInstanceAbstractMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
abstract class C
{
public abstract void {|Definition:$$M|}(int i);
}
class D
{
void Goo()
{
C.[|M|](1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_VBInaccessibleInstanceAbstractMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
MustInherit Class C
public MustOverride Sub {|Definition:$$M|} (ByVal i as Integer)
End Class
Class D
Sub Goo()
C.[|M|](1);
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538794")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_CSharpInaccessibleInstancePrivateStaticMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
private static void {|Definition:$$M|}(int i) { }
}
class D
{
void Goo()
{
C.[|M|](1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_VBInaccessibleInstancePrivateStaticMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private shared Sub {|Definition:$$M|} (ByVal i as Integer)
End Sub
End Class
Class D
Sub Goo()
C.[|M|](1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538794")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_CSharpInaccessibleInstanceProtectedMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
protected void {|Definition:$$M|}(int i) { }
}
class D
{
void Goo()
{
C.[|M|](1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_VBInaccessibleInstanceProtectedMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Protected Sub {|Definition:$$M|} (ByVal i as Integer)
End Sub
End Class
Class D
Sub Goo()
C.[|M|](1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(2544, "https://github.com/dotnet/roslyn/issues/2544")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestInaccessibleMemberOverrideVB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private Sub M(d As D)
d.[|$$M|](1)
End Sub
End Class
Class D
Private Sub {|Definition:M|}(i As Integer)
End Sub
Private Sub M(d As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(2544, "https://github.com/dotnet/roslyn/issues/2544")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestInaccessibleMemberOverrideCS(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
private void M(D d)
{
d.[|$$M|](1);
}
}
class D
{
private void {|Definition:M|}(int i) { }
private void M(double d) { }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_CSharpAccessibleInstanceProtectedMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
protected void {|Definition:$$M|}(int i) { }
}
class D : C
{
void Goo()
{
D.[|M|](1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_CSharpAccessibleStaticProtectedMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
protected static void {|Definition:$$M|}(int i) { }
}
class D : C
{
void Goo()
{
C.[|M|](1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538726")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceMethodsDontCascadeThroughOtherInterfaceMethods1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IControl
{
void {|Definition:Pa$$int|}();
}
interface ISurface : IControl
{
void Paint();
}
class SampleClass : IControl
{
public void {|Definition:Paint|}()
{
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538726")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceMethodsDontCascadeThroughOtherInterfaceMethods2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IControl
{
void {|Definition:Paint|}();
}
interface ISurface : IControl
{
void Paint();
}
class SampleClass : IControl
{
public void {|Definition:Pa$$int|}()
{
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538726")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceMethodsDontCascadeThroughOtherInterfaceMethods3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IControl
{
void Definition();
}
interface ISurface : IControl
{
void {|Definition:Pa$$int|}();
}
class SampleClass : IControl
{
public void Paint()
{
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538898, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538898")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodMatchEntireInvocation(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module M
Sub Main
Dim x As I
x.Goo(1)
End Sub
End Module
Interface I
Sub Goo(x as Integer)
Sub {|Definition:G$$oo|}(x as Date)
End Interface
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:$$F|}();
}
class Base<U> : I<U>
{
void I<U>.{|Definition:F|}() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:F|}()
{
[|F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface2_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.{|Definition:$$F|}() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:F|}()
{
[|F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface2_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.{|Definition:$$F|}() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void F()
{
F();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface3_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.{|Definition:F|}() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:$$F|}()
{
[|F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface3_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.F() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:$$F|}()
{
[|F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface4_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.{|Definition:F|}() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:F|}()
{
[|$$F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface4_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.F() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:F|}()
{
[|$$F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539046")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_DoNotFindInNonImplementingClass1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I
{
void {|Definition:$$Goo|}();
}
class C : I
{
public void {|Definition:Goo|}()
{
}
}
class D : C
{
public void Goo()
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539046")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_DoNotFindInNonImplementingClass2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I
{
void {|Definition:Goo|}();
}
class C : I
{
public void {|Definition:$$Goo|}()
{
}
}
class D : C
{
public void Goo()
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539046")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_DoNotFindInNonImplementingClass3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I
{
void Goo();
}
class C : I
{
public void Goo()
{
}
}
class D : C
{
public void {|Definition:$$Goo|}()
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_GenericMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}<T>(IList<T> list);
}
class C : I
{
public void {|Definition:Goo|}<U>(IList<U> list)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_GenericMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:Goo|}<T>(IList<T> list);
}
class C : I
{
public void {|Definition:$$Goo|}<U>(IList<U> list)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_GenericMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}<T>(IList<T> list);
}
class C<T> : I
{
public void Goo<U>(IList<T> list)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_GenericMethod4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}<T>(IList<T> list);
}
class C<T> : I
{
public void Goo(IList<T> list)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_GenericMethod5(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}<T>(IList<T> list);
}
class C : I
{
public void Goo<T>(IList<int> list)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_RefOut1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}(ref int i);
}
class C : I
{
public void {|Definition:Goo|}(ref System.Int32 j)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_RefOut2_Success(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}(ref int i);
}
class C : I
{
public void Goo(out System.Int32 j)
{
}
void I.{|Definition:Goo|}(ref System.Int32 j)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_RefOut2_Error(kind As TestKind, host As TestHost) As Task
' In non-compiling code, finding an almost-matching definition
' seems reasonable.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}(ref int i);
}
class C : I
{
public void {|Definition:Goo|}(out System.Int32 j)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethod_DelegateConstructor1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class Program
{
delegate double DoubleFunc(double x);
DoubleFunc f = new DoubleFunc([|$$Square|]);
static float Square(float x)
{
return x * x;
}
static double {|Definition:Square|}(double x)
{
return x * x;
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethod_DelegateConstructor2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class Program
{
delegate double DoubleFunc(double x);
DoubleFunc f = new DoubleFunc(Square);
static float {|Definition:$$Square|}(float x)
{
return x * x;
}
static double Square(double x)
{
return x * x;
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethod_DelegateConstructor3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class Program
{
delegate double DoubleFunc(double x);
DoubleFunc f = new DoubleFunc([|Square|]);
static float Square(float x)
{
return x * x;
}
static double {|Definition:$$Square|}(double x)
{
return x * x;
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539646")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDelegateMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Program
{
delegate R {|Definition:Func|}<T, R>(T t);
static void Main(string[] args)
{
[|Func|]<int, int> f = (arg) =>
{
int s = 3;
return s;
};
f.[|$$BeginInvoke|](2, null, null);
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539646")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDelegateMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Program
{
delegate R {|Definition:$$Func|}<T, R>(T t);
static void Main(string[] args)
{
[|Func|]<int, int> f = (arg) =>
{
int s = 3;
return s;
};
f.BeginInvoke(2, null, null);
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539646")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDelegateMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Program
{
delegate R {|Definition:Func|}<T, R>(T t);
static void Main(string[] args)
{
[|$$Func|]<int, int> f = (arg) =>
{
int s = 3;
return s;
};
f.BeginInvoke(2, null, null);
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539824")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodGroup1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
public delegate int Func(int i);
public Func Goo()
{
return [|$$Goo|];
}
private int {|Definition:Goo|}(int i)
{
return i;
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539824")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodGroup2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
public delegate int Func(int i);
public Func Goo()
{
return [|Goo|];
}
private int {|Definition:$$Goo|}(int i)
{
return i;
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540349")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestNonImplementedInterfaceMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I
Sub {|Definition:$$Goo|}()
End Interface
Class A
Implements I
Public Sub {|Definition:Goo|}() Implements I.[|Goo|]
End Sub
End Class
Class B
Inherits A
Implements I
Public Sub Goo()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540349")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestNonImplementedInterfaceMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I
Sub {|Definition:Goo|}()
End Interface
Class A
Implements I
Public Sub {|Definition:$$Goo|}() Implements I.[|Goo|]
End Sub
End Class
Class B
Inherits A
Implements I
Public Sub Goo()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540349")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestNonImplementedInterfaceMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I
Sub Goo()
End Interface
Class A
Implements I
Public Sub Goo() Implements I.Goo
End Sub
End Class
Class B
Inherits A
Implements I
Public Sub {|Definition:$$Goo|}()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540359")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestShadowedMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I1
Function {|Definition:$$Goo|}() As Integer
End Interface
Interface I2
Inherits I1
Shadows Function Goo() As Integer
End Interface
Class C
Implements I1
Public Function {|Definition:Goo|}() As Integer Implements I1.[|Goo|]
Return 1
End Function
End Class
Class M
Inherits C
Implements I2
Public Overloads Function Goo() As Integer Implements I2.Goo
Return 1
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540359")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestShadowedMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I1
Function {|Definition:Goo|}() As Integer
End Interface
Interface I2
Inherits I1
Shadows Function Goo() As Integer
End Interface
Class C
Implements I1
Public Function {|Definition:$$Goo|}() As Integer Implements I1.[|Goo|]
Return 1
End Function
End Class
Class M
Inherits C
Implements I2
Public Overloads Function Goo() As Integer Implements I2.Goo
Return 1
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540359")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestShadowedMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I1
Function Goo() As Integer
End Interface
Interface I2
Inherits I1
Shadows Function {|Definition:$$Goo|}() As Integer
End Interface
Class C
Implements I1
Public Function Goo() As Integer Implements I1.Goo
Return 1
End Function
End Class
Class M
Inherits C
Implements I2
Public Overloads Function {|Definition:Goo|}() As Integer Implements I2.[|Goo|]
Return 1
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540359")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestShadowedMethod4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I1
Function Goo() As Integer
End Interface
Interface I2
Inherits I1
Shadows Function {|Definition:Goo|}() As Integer
End Interface
Class C
Implements I1
Public Function Goo() As Integer Implements I1.Goo
Return 1
End Function
End Class
Class M
Inherits C
Implements I2
Public Overloads Function {|Definition:$$Goo|}() As Integer Implements I2.[|Goo|]
Return 1
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540946")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAddressOfOverloads1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim a As Action(Of Integer) = AddressOf [|$$Goo|]
End Sub
Sub Goo()
End Sub
Shared Sub {|Definition:Goo|}(x As Integer)
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540946")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAddressOfOverloads2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim a As Action(Of Integer) = AddressOf [|Goo|]
End Sub
Sub Goo()
End Sub
Shared Sub {|Definition:$$Goo|}(x As Integer)
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540946")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAddressOfOverloads3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim a As Action(Of Integer) = AddressOf Goo
End Sub
Sub {|Definition:$$Goo|}()
End Sub
Shared Sub Goo(x As Integer)
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542034")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFunctionValue1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Public Class MyClass1
Public Shared Sub Main()
End Sub
Shared Function {|Definition:$$Function1|}(ByRef arg)
[|Function1|] = arg * 2
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542034")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFunctionValue2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Public Class MyClass1
Public Shared Sub Main()
End Sub
Shared Function {|Definition:Function1|}(ByRef arg)
[|$$Function1|] = arg * 2
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543002")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestForEachGetEnumerator1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class B
{
public int Current { get; set; }
public bool MoveNext()
{
return false;
}
}
class C
{
static void Main()
{
[|foreach|] (var x in new C()) { }
}
public B {|Definition:$$GetEnumerator|}()
{
return null;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestForEachGetEnumeratorViaExtension(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true" LanguageVersion="Preview">
<Document>
class B
{
public int Current { get; set; }
public bool MoveNext()
{
return false;
}
}
class C
{
static void Main()
{
[|foreach|] (var x in new C()) { }
}
}
public static class Extensions
{
public static B {|Definition:$$GetEnumerator|}(this C c)
{
return null;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543002")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestForEachMoveNext1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class B
{
public int Current { get; set; }
public bool {|Definition:$$MoveNext|}()
{
return false;
}
}
class C
{
static void Main()
{
[|foreach|] (var x in new C()) { }
}
public B GetEnumerator()
{
return null;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543002")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestForEachCurrent1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class B
{
public int {|Definition:$$Current|} { get; set; }
public bool MoveNext()
{
return false;
}
}
class C
{
static void Main()
{
[|foreach|] (var x in new C()) { }
}
public B GetEnumerator()
{
return null;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544439")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodPartial1_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Class1
{
partial void {|Definition:$$goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U;
partial void {|Definition:goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544439")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodPartial2_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Class1
{
partial void {|Definition:$$goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U;
partial void {|Definition:goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544439")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodExtendedPartial1_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Class1
{
public partial void {|Definition:$$goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U;
public partial void {|Definition:goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544439")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodExtendedPartial2_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Class1
{
public partial void {|Definition:$$goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U;
public partial void {|Definition:goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544437")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodPartial1_VB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Public Module Module1
Partial Private Sub {|Definition:$$GOo|}(Of T As Class, U As T, V As {U, Exception})(aa As T, y As U, z As V)
End Sub
Private Sub {|Definition:goo|}(Of T As Class, U As T, V As {U, Exception})(aa As T, y As U, z As V)
Console.WriteLine("goo")
End Sub
Sub Main()
End Sub
End Module
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544437")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodPartial2_VB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Public Module Module1
Partial Private Sub {|Definition:GOo|}(Of T As Class, U As T, V As {U, Exception})(aa As T, y As U, z As V)
End Sub
Private Sub {|Definition:$$goo|}(Of T As Class, U As T, V As {U, Exception})(aa As T, y As U, z As V)
Console.WriteLine("goo")
End Sub
Sub Main()
End Sub
End Module
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestInterfaceMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public Main()
{
var c1 = new Class1();
var c2 = new Class2();
var c3 = new Class3();
PrintMyName(c1);
PrintMyName(c2);
PrintMyName(c3);
}
public void PrintMyName(IClass c)
{
Console.WriteLine(c.$$[|GetMyName|]());
}
public class Class1 : IClass
{
public string {|Definition:GetMyName|}()
{
return "Class1";
}
}
public class Class2 : IClass
{
public string {|Definition:GetMyName|}()
{
return "Class2";
}
}
public class Class3 : Class2
{
public new string GetMyName()
{
return "Class3";
}
}
public interface IClass
{
string {|Definition:GetMyName|}();
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCrefMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
/// <see cref="Program.[|Main|]"/> to start the program.
static void {|Definition:Ma$$in|}(string[] args)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCrefMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
/// <see cref="Program.[|Ma$$in|]"/> to start the program.
static void {|Definition:Main|}(string[] args)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCrefMethodAcrossMultipleFiles(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Program
{
/// <see cref="Program.[|Main|]"/> to start the program.
static void {|Definition:Ma$$in|}(string[] args)
{
}
}
]]>
</Document>
<Document><![CDATA[
partial class Program
{
/// <see cref="Program.[|Main|]"/>
void goo() {}
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCrefMethodAcrossMultipleFiles2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Program
{
/// <see cref="Program.[|Main|]"/> to start the program.
static void {|Definition:Main|}(string[] args)
{
}
}
]]>
</Document>
<Document><![CDATA[
partial class Program
{
/// <see cref="Program.[|Ma$$in|]"/>
void goo() {}
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(531010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531010")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCrossAssemblyReferencesFromMetadata(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<MetadataReferenceFromSource Language="Visual Basic" CommonReferences="true">
<Document FilePath="ReferencedDocument">
Public Interface I
Sub Goo()
End Interface
Friend Class F : Implements I
Public Sub Goo() Implements I.Goo
End Sub
End Class
</Document>
</MetadataReferenceFromSource>
<Document>
Public Class C
Sub Bar(i As I)
i.$$[|Goo|]()
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(623148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623148")>
Public Async Function TestFarWithInternalVisibleTo(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="ProjectA" CommonReferences="true">
<Document>
<![CDATA[
<Assembly: Global.System.Runtime.CompilerServices.InternalsVisibleTo("ProjectB")>
Friend Class A
Public Sub {|Definition:$$Goo|}()
End Sub
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="ProjectB" CommonReferences="true">
<ProjectReference>ProjectA</ProjectReference>
<Document>
<![CDATA[
Public Class B
Public Sub Bar(a as A)
a.[|Goo|]()
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(657262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657262")>
Public Async Function TestMethodInsideMetadataToSourcePrimitiveTypeInCSharpSource(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="mscorlib" CommonReferences="true">
<Document>
namespace System
{
struct Int32
{
public override string {|Definition:$$ToString|}() { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(657262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657262")>
Public Async Function TestMethodInsideMetadataToSourcePrimitiveTypeInVisualBasicSource(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="mscorlib" CommonReferences="true">
<Document>
Namespace System
Structure Int32
Public Overrides Function {|Definition:$$ToString|}() As String
End Function
End Structure
End Namespace
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingMethod_Basic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableClassLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System.Collections.Generic;
namespace PortableClassLibrary
{
public class Class1
{
int x;
public void {|Definition:Go$$o|}(int x) { }
}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="MainLibrary" CommonReferences="true">
<ProjectReference>PortableClassLibrary</ProjectReference>
<Document><;
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingMethod_GenericType(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableClassLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
namespace PortableClassLibrary
{
public class Class1
{
Tuple<int> x;
public void {|Definition:Go$$o|}(Tuple<int> x) { }
}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="MainLibrary" CommonReferences="true">
<ProjectReference>PortableClassLibrary</ProjectReference>
<Document><;
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingMethod_FARFromReferencingProject(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableClassLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
namespace PortableClassLibrary
{
public class Class1
{
Tuple<int> x;
public void {|Definition:Goo|}(Tuple<int> x) { }
}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="MainLibrary" CommonReferences="true">
<ProjectReference>PortableClassLibrary</ProjectReference>
<Document><;
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingMethod_MultipleForwardedTypes(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableClassLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
namespace PortableClassLibrary
{
public class Class1
{
Tuple<int> x;
public void {|Definition:$$Goo|}(Tuple<int> x, float y) { }
}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="MainLibrary" CommonReferences="true">
<ProjectReference>PortableClassLibrary</ProjectReference>
<Document><;
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingMethod_NestedType(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableClassLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
namespace PortableClassLibrary
{
public class Class1
{
public void {|Definition:$$Goo|}(System.Environment.SpecialFolder x) { }
}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="MainLibrary" CommonReferences="true">
<ProjectReference>PortableClassLibrary</ProjectReference>
<Document><;
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRefKindRef_FromDefinition(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="Lib" CommonReferences="true">
<Document><![CDATA[
using System;
public class C
{
public static void {|Definition:$$M|}(ref int x) { }
}
]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Test" CommonReferences="true">
<ProjectReference>Lib</ProjectReference>
<Document><
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRefKindRef_FromReference(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="Lib" CommonReferences="true">
<Document><![CDATA[
using System;
public class C
{
public static void {|Definition:M|}(ref int x) { }
}
]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Test" CommonReferences="true">
<ProjectReference>Lib</ProjectReference>
<Document><
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRefKindOut_FromDefinition(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="Lib" CommonReferences="true">
<Document><![CDATA[
using System;
public class C
{
public static void {|Definition:$$M|}(out int x) { }
}
]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Test" CommonReferences="true">
<ProjectReference>Lib</ProjectReference>
<Document><
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRefKindOut_FromReference(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="Lib" CommonReferences="true">
<Document><![CDATA[
using System;
public class C
{
public static void {|Definition:M|}(out int x) { }
}
]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Test" CommonReferences="true">
<ProjectReference>Lib</ProjectReference>
<Document><
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(428072, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/428072")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestInterfaceMethodImplementedInStruct1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface IGoo
{
void {|Definition:$$Goo|}();
}
public struct MyStruct : IGoo
{
public void {|Definition:Goo|}()
{
throw new System.NotImplementedException();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(428072, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/428072")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestInterfaceMethodImplementedInStruct2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface IGoo
{
void {|Definition:Goo|}();
}
public struct MyStruct : IGoo
{
public void {|Definition:$$Goo|}()
{
throw new System.NotImplementedException();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodReferenceInGlobalSuppression(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:C.[|M|]")]
class C
{
private void {|Definition:$$M|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodReferenceInGlobalSuppression_MethodWithParameters(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:C.[|M|](System.String)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:C.M(System.Int32)")]
class C
{
private void {|Definition:$$M|}(string s) { }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodWithMissingReferences_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="false">
<Document>
class C
{
// string will be an error type because we have no actual references.
private void {|Definition:Goo|}(string s) { }
void Bar()
{
[|Go$$o|]("");
[|Goo|](s);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodWithMissingReferences_VB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="false">
<Document>
class C
' string will be an error type because we have no actual references.
private sub {|Definition:Goo|}(s as string)
end sub
sub Bar()
[|Go$$o|]("")
[|Goo|](s)
end sub
end class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodUsedInSourceGenerator(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C
{
private void {|Definition:Goo|}() { }
}
</Document>
<DocumentFromSourceGenerator>
partial class C
{
void Bar()
{
[|Go$$o|]();
[|Goo|]();
B.Goo();
new C().[|Goo|]();
new C().goo();
}
}
</DocumentFromSourceGenerator>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFeatureHierarchyCascade1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:$$Goo|}();
}
interface I2
{
void Goo();
}
class B : I1
{
public virtual void {|Definition:Goo|}() {}
}
class D1 : B, I1, I2
{
public override void {|Definition:Goo|}() {}
}
class D2 : B, I1
{
public override void {|Definition:Goo|}() {}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFeatureHierarchyCascade2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void Goo();
}
interface I2
{
void {|Definition:$$Goo|}();
}
class B : I1
{
public virtual void Goo() {}
}
class D1 : B, I1, I2
{
public override void {|Definition:Goo|}() {}
}
class D2 : B, I1
{
public override void Goo() {}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFeatureHierarchyCascade3(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Goo|}();
}
interface I2
{
void Goo();
}
class B : I1
{
public virtual void {|Definition:$$Goo|}() {}
}
class D1 : B, I1, I2
{
public override void {|Definition:Goo|}() {}
}
class D2 : B, I1
{
public override void {|Definition:Goo|}() {}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFeatureHierarchyCascade4(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Goo|}();
}
interface I2
{
void {|Definition:Goo|}();
}
class B : I1
{
public virtual void {|Definition:Goo|}() {}
}
class D1 : B, I1, I2
{
public override void {|Definition:$$Goo|}() {}
}
class D2 : B, I1
{
public override void Goo() {}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFeatureHierarchyCascade5(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Goo|}();
}
interface I2
{
void Goo();
}
class B : I1
{
public virtual void {|Definition:Goo|}() {}
}
class D1 : B, I1, I2
{
public override void Goo() {}
}
class D2 : B, I1
{
public override void {|Definition:$$Goo|}() {}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMemberStaticAbstractMethodFromInterface(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
static abstract void {|Definition:M$$1|}();
}
class C1_1 : I1
{
public static void {|Definition:M1|}() { }
}
class C1_2 : I1
{
static void I1.{|Definition:M1|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDerivedMemberStaticAbstractMethodViaFeature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
static abstract void {|Definition:M1|}();
}
class C1_1 : I1
{
public static void {|Definition:M$$1|}() { }
}
class C1_2 : I1
{
static void I1.M1() { }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDerivedMemberStaticAbstractMethodViaFeature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
static abstract void {|Definition:M1|}();
}
class C1_1 : I1
{
public static void M1() { }
}
class C1_2 : I1
{
static void I1.{|Definition:M$$1|}() { }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDerivedMemberStaticAbstractMethodViaAPI1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
static abstract void {|Definition:M1|}();
}
class C1_1 : I1
{
public static void {|Definition:M$$1|}() { }
}
class C1_2 : I1
{
static void I1.{|Definition:M1|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDerivedMemberStaticAbstractMethodViaAPI2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
static abstract void {|Definition:M1|}();
}
class C1_1 : I1
{
public static void {|Definition:M1|}() { }
}
class C1_2 : I1
{
static void I1.{|Definition:M$$1|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
private void {|Definition:Goo|}() { }
void Bar()
{
[|Go$$o|]();
[|Goo|]();
B.Goo();
new C().[|Goo|]();
new C().goo();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodCaseSensitivity(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
class C
private sub {|Definition:Goo|}()
end sub
sub Bar()
[|Go$$o|]()
[|Goo|]()
B.Goo()
Console.WriteLine(new C().[|Goo|]())
Console.WriteLine(new C().[|goo|]())
end sub
end class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_GetAwaiter(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
public class C
{
public TaskAwaiter<bool> {|Definition:Get$$Awaiter|}() => Task.FromResult(true).GetAwaiter();
static async void M(C c)
{
[|await|] c;
[|await|] c;
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_GetAwaiter_VB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class C
Public Function {|Definition:Get$$Awaiter|}() As TaskAwaiter(Of Boolean)
End Function
Shared Async Sub M(c As C)
[|Await|] c
End Sub
End Class
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_GetAwaiterInAnotherDocument(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
public class C
{
public TaskAwaiter<bool> {|Definition:Get$$Awaiter|}() => Task.FromResult(true).GetAwaiter();
}
]]></Document>
<Document><![CDATA[
class D
{
static async void M(C c)
{
[|await|] c;
[|await|] c;
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_Deconstruction(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public void {|Definition:Decons$$truct|}(out int x1, out int x2) { x1 = 1; x2 = 2; }
public void M()
{
[|var (x1, x2)|] = this;
foreach ([|var (y1, y2)|] in new[] { this }) { }
[|(x1, (x2, _))|] = (1, this);
(x1, x2) = (1, 2);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(24184, "https://github.com/dotnet/roslyn/issues/24184")>
Public Async Function FindReferences_DeconstructionInAnotherDocument(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public static class Extensions
{
public void {|Definition:Decons$$truct|}(this C c, out int x1, out int x2) { x1 = 1; x2 = 2; }
}
</Document>
<Document>
class C
{
public void M()
{
[|var (x1, x2)|] = this;
foreach ([|var (y1, y2)|] in new[] { this }) { }
[|(x1, (x2, _))|] = (1, this);
(x1, x2) = (1, 2);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_ForEachDeconstructionOnItsOwn(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public static class Extensions
{
public void {|Definition:Decons$$truct|}(this C c, out int x1, out int x2) { x1 = 1; x2 = 2; }
}
class C
{
public void M()
{
foreach ([|var (y1, y2)|] in new[] { this }) { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_NestedDeconstruction(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public static class Extensions
{
public void {|Definition:Decons$$truct|}(this C c, out int x1, out C x2) { x1 = 1; x2 = null; }
}
class C
{
public void M()
{
[|var (y1, (y2, y3))|] = this;
[|(y1, (y2, y3))|] = (1, this);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_NestedDeconstruction2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public static class Extensions
{
public void Deconstruct(this int i, out int x1, out C x2) { x1 = 1; x2 = null; }
public void {|Definition:Decons$$truct|}(this C c, out int x1, out int x2) { x1 = 1; x2 = 2; }
}
class C
{
public void M()
{
[|var (y1, (y2, y3))|] = 1;
var (z1, z2) = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_NestedDeconstruction3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public static class Extensions
{
public void {|Definition:Decons$$truct|}(this int i, out int x1, out C x2) { x1 = 1; x2 = null; }
public void Deconstruct(this C c, out int x1, out int x2) { x1 = 1; x2 = 2; }
}
class C
{
public void M()
{
[|var (y1, (y2, y3))|] = 1;
[|var (z1, z2)|] = 1;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(18963, "https://github.com/dotnet/roslyn/issues/18963")>
Public Async Function FindReferences_DeconstructionAcrossLanguage(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document><![CDATA[
Public Class Deconstructable
Public Sub {|Definition:Decons$$truct|}(<System.Runtime.InteropServices.Out> ByRef x1 As Integer, <System.Runtime.InteropServices.Out> ByRef x2 As Integer)
x1 = 1
x2 = 2
End Sub
End Class
]]></Document>
</Project>
<Project Language="C#" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class C
{
public void M(Deconstructable d)
{
[|var (x1, x2)|] = d;
foreach ([|var (y1, y2)|] in new[] { d }) { }
[|(x1, (x2, _))|] = (1, d);
(x1, x2) = (1, 2);
d.[|Deconstruct|](out var t1, out var t2);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverride1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual void {|Definition:Go$$o|}() { }
void Bar() { [|Goo|](); }
}
class D : C
{
public override void {|Definition:Goo|}() { }
void Quux() { [|Goo|](); }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverride2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual void {|Definition:Goo|}() { }
void Bar() { [|Goo|](); }
}
class D : C
{
public override void {|Definition:Go$$o|}() { }
void Quux() { [|Goo|](); }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverride3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual void Goo() { }
void Bar() { Goo(); }
}
class D : C
{
public override void Goo() { }
void Quux() { Goo(); }
}
class E : D
{
public new void {|Definition:Go$$o|}() { }
void Z() { [|Goo|](); }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverride_InMetadata_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
// Will walk up to Object.ToString
public override string {|Definition:To$$String|}() { }
}
class O
{
public override string {|Definition:ToString|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverride_InMetadata_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
// Will walk up to Object.ToString
public override string {|Definition:To$$String|}() { }
}
class O
{
public override string ToString() { }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodOverrideCrossLanguage(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<Document>
public class C
{
public virtual void {|Definition:Go$$o|}() { }
}
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>CSharpAssembly</ProjectReference>
<Document>
class D : Inherits C
public overrides sub {|Definition:Goo|}()
end sub
private sub Bar()
[|Goo|]()
end sub
sub class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceInheritance_FromReference_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Goo|}();
}
class C1 : I1
{
public void {|Definition:Goo|}()
{
}
}
interface I2 : I1
{
void {|Definition:Goo|}();
void Bar();
}
class C2 : I2
{
public void Bar()
{
[|Goo$$|]();
}
public void {|Definition:Goo|}();
{
}
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceInheritance_FromReference_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Goo|}();
}
class C1 : I1
{
public void Goo()
{
}
}
interface I2 : I1
{
void {|Definition:Goo|}();
void Bar();
}
class C2 : I2
{
public void Bar()
{
[|Goo$$|]();
}
public void {|Definition:Goo|}();
{
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceInheritance_FromDefinition_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Go$$o|}();
}
class C1 : I1
{
public void {|Definition:Goo|}()
{
}
}
interface I2 : I1
{
void {|Definition:Goo|}();
void Bar();
}
class C2 : I2
{
public void Bar()
{
[|Goo|]();
}
public void {|Definition:Goo|}();
{
}
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceInheritance_FromDefinition_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Go$$o|}();
}
class C1 : I1
{
public void {|Definition:Goo|}()
{
}
}
interface I2 : I1
{
void Goo();
void Bar();
}
class C2 : I2
{
public void Bar()
{
[|Goo|]();
}
public void {|Definition:Goo|}();
{
}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceImplementation1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IGoo
{
void {|Definition:Goo|}();
}
class C
{
public void {|Definition:Go$$o|}() { }
}
class D : C, IGoo
{
void Quux()
{
IGoo f;
f.[|Goo|]();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529616")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceImplementationVB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface IGoo
Sub {|Definition:TestSub|}()
End Interface
Class Goo
Implements IGoo
Public Sub {|Definition:MethodWithADifferentName|}() Implements IGoo.[|$$TestSub|]
End Function
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceImplementation2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IGoo
{
void {|Definition:G$$oo|}();
}
class C
{
public void {|Definition:Goo|}() { }
void Zap()
{
this.[|Goo|]();
[|Goo|]();
}
}
class D : C, IGoo
{
void Quux()
{
IGoo f;
f.[|Goo|]();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceImplementationSingleFileOnly(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Zap()
{
IGoo goo;
goo.[|Go$$o|]();
}
}
class D : IGoo
{
void Quux()
{
IGoo f;
f.[|Goo|]();
}
}
</Document>
<Document>
interface IGoo
{
void {|Definition:Goo|}();
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host, searchSingleFileOnly:=True)
End Function
<WorkItem(522786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522786")>
<WorkItem(34107, "https://github.com/dotnet/roslyn/issues/34107")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34107"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceDispose1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : System.IDisposable
{
public void {|Definition:Disp$$ose|}() { }
void Zap()
{
[|using|] (new C())
{
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(522786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522786")>
<WorkItem(34107, "https://github.com/dotnet/roslyn/issues/34107")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34107"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceDispose2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : System.IDisposable
{
public void {|Definition:Disp$$ose|}() { }
void Zap()
{
[|using|] (new D())
{
}
}
}
class D : System.IDisposable
{
public void {|Definition:Dispose|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Collections;
class C : IEnumerable
{
public IEnumerator {|Definition:GetEnumera$$tor|}() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Collections;
class C
{
public struct Enumerator : IEnumerator
{
public object Current { get { } }
public bool {|Definition:MoveNe$$xt|}() { }
}
public Enumerator GetEnumerator() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Collections;
class C
{
public struct Enumerator : IEnumerator
{
public object {|Definition:Cu$$rrent|} { get { } }
public bool MoveNext() { }
}
public Enumerator GetEnumerator() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
class C : IEnumerable<int>
{
public IEnumerator<int> {|Definition:GetEnumera$$tor|}() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable5(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
class C
{
public struct Enumerator<T> : IEnumerator<T>
{
public T Current { get { } }
public bool {|Definition:MoveNe$$xt|}() { }
}
public Enumerator<int> GetEnumerator() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodIEnumerable6(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
class C
{
public struct Enumerator<T> : IEnumerator<T>
{
public object {|Definition:Cu$$rrent|} { get { } }
public bool MoveNext() { }
}
public Enumerator<T> GetEnumerator() { }
void Zap()
{
[|foreach|] (var v in this)
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(634818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634818")>
<WorkItem(34106, "https://github.com/dotnet/roslyn/issues/34106")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34106"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodLinqWhere1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
class C
{
void Zap()
{
var q = from v in this
[|where|] v > 21
select v;
}
}
static class Extensions
{
public static IEnumerable<int> {|Definition:Whe$$re|}(this IEnumerable<int> source, Func<int, bool> predicate) => throw null;
public static IEnumerable<int> Select(this IEnumerable<int> source, Func<int, int> func) => throw null;
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(636943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636943")>
<WorkItem(34106, "https://github.com/dotnet/roslyn/issues/34106")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34106"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodLinqWhere2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
class C
{
void Zap()
{
var q = from v in this
[|w$$here|] v > 21
select v;
}
}
static class Extensions
{
public static IEnumerable<int> {|Definition:Where|}(this IEnumerable<int> source, Func<int, bool> predicate) => throw null;
public static IEnumerable<int> Select(this IEnumerable<int> source, Func<int, int> func) => throw null;
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(636943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636943")>
<WorkItem(34106, "https://github.com/dotnet/roslyn/issues/34106")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34106"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodLinqSelect1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
class C
{
void Zap()
{
var q = from v in this
where v > 21
[|select|] v + 1;
}
}
static class Extensions
{
public static IEnumerable<int> Where(this IEnumerable<int> source, Func<int, bool> predicate) => throw null;
public static IEnumerable<int> {|Definition:Sel$$ect|}(this IEnumerable<int> source, Func<int, int> func) => throw null;
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(636943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636943")>
<WorkItem(34106, "https://github.com/dotnet/roslyn/issues/34106")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34106"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodLinqSelect2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
class C
{
void Zap()
{
var q = from v in this
where v > 21
[|sel$$ect|] v + 1;
}
}
static class Extensions
{
public static IEnumerable<int> Where(this IEnumerable<int> source, Func<int, bool> predicate) => throw null;
public static IEnumerable<int> {|Definition:Select|}(this IEnumerable<int> source, Func<int, int> func) => throw null;
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(528936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528936")>
<WorkItem(34105, "https://github.com/dotnet/roslyn/issues/34105")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34105"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodMonitorEnter(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><;
[|lock|] (new C())
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(528936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528936")>
<WorkItem(34105, "https://github.com/dotnet/roslyn/issues/34105")>
<WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/34105"), CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodMonitorExit(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><;
[|lock|] (new C())
{
}
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_CSharpInaccessibleInstanceAbstractMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
abstract class C
{
public abstract void {|Definition:$$M|}(int i);
}
class D
{
void Goo()
{
C.[|M|](1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_VBInaccessibleInstanceAbstractMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
MustInherit Class C
public MustOverride Sub {|Definition:$$M|} (ByVal i as Integer)
End Class
Class D
Sub Goo()
C.[|M|](1);
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538794")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_CSharpInaccessibleInstancePrivateStaticMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
private static void {|Definition:$$M|}(int i) { }
}
class D
{
void Goo()
{
C.[|M|](1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_VBInaccessibleInstancePrivateStaticMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private shared Sub {|Definition:$$M|} (ByVal i as Integer)
End Sub
End Class
Class D
Sub Goo()
C.[|M|](1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538794")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_CSharpInaccessibleInstanceProtectedMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
protected void {|Definition:$$M|}(int i) { }
}
class D
{
void Goo()
{
C.[|M|](1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_VBInaccessibleInstanceProtectedMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Protected Sub {|Definition:$$M|} (ByVal i as Integer)
End Sub
End Class
Class D
Sub Goo()
C.[|M|](1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(2544, "https://github.com/dotnet/roslyn/issues/2544")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestInaccessibleMemberOverrideVB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private Sub M(d As D)
d.[|$$M|](1)
End Sub
End Class
Class D
Private Sub {|Definition:M|}(i As Integer)
End Sub
Private Sub M(d As Double)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(2544, "https://github.com/dotnet/roslyn/issues/2544")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestInaccessibleMemberOverrideCS(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
private void M(D d)
{
d.[|$$M|](1);
}
}
class D
{
private void {|Definition:M|}(int i) { }
private void M(double d) { }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_CSharpAccessibleInstanceProtectedMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
protected void {|Definition:$$M|}(int i) { }
}
class D : C
{
void Goo()
{
D.[|M|](1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestField_CSharpAccessibleStaticProtectedMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
protected static void {|Definition:$$M|}(int i) { }
}
class D : C
{
void Goo()
{
C.[|M|](1);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538726")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceMethodsDontCascadeThroughOtherInterfaceMethods1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IControl
{
void {|Definition:Pa$$int|}();
}
interface ISurface : IControl
{
void Paint();
}
class SampleClass : IControl
{
public void {|Definition:Paint|}()
{
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538726")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceMethodsDontCascadeThroughOtherInterfaceMethods2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IControl
{
void {|Definition:Paint|}();
}
interface ISurface : IControl
{
void Paint();
}
class SampleClass : IControl
{
public void {|Definition:Pa$$int|}()
{
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538726")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodInterfaceMethodsDontCascadeThroughOtherInterfaceMethods3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IControl
{
void Definition();
}
interface ISurface : IControl
{
void {|Definition:Pa$$int|}();
}
class SampleClass : IControl
{
public void Paint()
{
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538898, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538898")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodMatchEntireInvocation(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module M
Sub Main
Dim x As I
x.Goo(1)
End Sub
End Module
Interface I
Sub Goo(x as Integer)
Sub {|Definition:G$$oo|}(x as Date)
End Interface
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:$$F|}();
}
class Base<U> : I<U>
{
void I<U>.{|Definition:F|}() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:F|}()
{
[|F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface2_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.{|Definition:$$F|}() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:F|}()
{
[|F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface2_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.{|Definition:$$F|}() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void F()
{
F();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface3_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.{|Definition:F|}() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:$$F|}()
{
[|F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface3_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.F() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:$$F|}()
{
[|F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface4_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.{|Definition:F|}() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:F|}()
{
[|$$F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539033")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethodFromGenericInterface4_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I<T>
{
void {|Definition:F|}();
}
class Base<U> : I<U>
{
void I<U>.F() { }
}
class Derived<U, V> : Base<U>, I<V>
{
public void {|Definition:F|}()
{
[|$$F|]();
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539046")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_DoNotFindInNonImplementingClass1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I
{
void {|Definition:$$Goo|}();
}
class C : I
{
public void {|Definition:Goo|}()
{
}
}
class D : C
{
public void Goo()
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539046")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_DoNotFindInNonImplementingClass2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I
{
void {|Definition:Goo|}();
}
class C : I
{
public void {|Definition:$$Goo|}()
{
}
}
class D : C
{
public void Goo()
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539046")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_DoNotFindInNonImplementingClass3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
interface I
{
void Goo();
}
class C : I
{
public void Goo()
{
}
}
class D : C
{
public void {|Definition:$$Goo|}()
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_GenericMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}<T>(IList<T> list);
}
class C : I
{
public void {|Definition:Goo|}<U>(IList<U> list)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_GenericMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:Goo|}<T>(IList<T> list);
}
class C : I
{
public void {|Definition:$$Goo|}<U>(IList<U> list)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_GenericMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}<T>(IList<T> list);
}
class C<T> : I
{
public void Goo<U>(IList<T> list)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_GenericMethod4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}<T>(IList<T> list);
}
class C<T> : I
{
public void Goo(IList<T> list)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_GenericMethod5(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}<T>(IList<T> list);
}
class C : I
{
public void Goo<T>(IList<int> list)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_RefOut1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}(ref int i);
}
class C : I
{
public void {|Definition:Goo|}(ref System.Int32 j)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_RefOut2_Success(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}(ref int i);
}
class C : I
{
public void Goo(out System.Int32 j)
{
}
void I.{|Definition:Goo|}(ref System.Int32 j)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCascadeOrdinaryMethod_RefOut2_Error(kind As TestKind, host As TestHost) As Task
' In non-compiling code, finding an almost-matching definition
' seems reasonable.
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System.Collections.Generic;
interface I
{
void {|Definition:$$Goo|}(ref int i);
}
class C : I
{
public void {|Definition:Goo|}(out System.Int32 j)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethod_DelegateConstructor1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class Program
{
delegate double DoubleFunc(double x);
DoubleFunc f = new DoubleFunc([|$$Square|]);
static float Square(float x)
{
return x * x;
}
static double {|Definition:Square|}(double x)
{
return x * x;
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethod_DelegateConstructor2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class Program
{
delegate double DoubleFunc(double x);
DoubleFunc f = new DoubleFunc(Square);
static float {|Definition:$$Square|}(float x)
{
return x * x;
}
static double Square(double x)
{
return x * x;
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethod_DelegateConstructor3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class Program
{
delegate double DoubleFunc(double x);
DoubleFunc f = new DoubleFunc([|Square|]);
static float Square(float x)
{
return x * x;
}
static double {|Definition:$$Square|}(double x)
{
return x * x;
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539646")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDelegateMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Program
{
delegate R {|Definition:Func|}<T, R>(T t);
static void Main(string[] args)
{
[|Func|]<int, int> f = (arg) =>
{
int s = 3;
return s;
};
f.[|$$BeginInvoke|](2, null, null);
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539646")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDelegateMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Program
{
delegate R {|Definition:$$Func|}<T, R>(T t);
static void Main(string[] args)
{
[|Func|]<int, int> f = (arg) =>
{
int s = 3;
return s;
};
f.BeginInvoke(2, null, null);
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539646")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDelegateMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
class Program
{
delegate R {|Definition:Func|}<T, R>(T t);
static void Main(string[] args)
{
[|$$Func|]<int, int> f = (arg) =>
{
int s = 3;
return s;
};
f.BeginInvoke(2, null, null);
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539824")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodGroup1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
public delegate int Func(int i);
public Func Goo()
{
return [|$$Goo|];
}
private int {|Definition:Goo|}(int i)
{
return i;
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539824")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodGroup2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
class C
{
public delegate int Func(int i);
public Func Goo()
{
return [|Goo|];
}
private int {|Definition:$$Goo|}(int i)
{
return i;
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540349")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestNonImplementedInterfaceMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I
Sub {|Definition:$$Goo|}()
End Interface
Class A
Implements I
Public Sub {|Definition:Goo|}() Implements I.[|Goo|]
End Sub
End Class
Class B
Inherits A
Implements I
Public Sub Goo()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540349")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestNonImplementedInterfaceMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I
Sub {|Definition:Goo|}()
End Interface
Class A
Implements I
Public Sub {|Definition:$$Goo|}() Implements I.[|Goo|]
End Sub
End Class
Class B
Inherits A
Implements I
Public Sub Goo()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540349")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestNonImplementedInterfaceMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I
Sub Goo()
End Interface
Class A
Implements I
Public Sub Goo() Implements I.Goo
End Sub
End Class
Class B
Inherits A
Implements I
Public Sub {|Definition:$$Goo|}()
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540359")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestShadowedMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I1
Function {|Definition:$$Goo|}() As Integer
End Interface
Interface I2
Inherits I1
Shadows Function Goo() As Integer
End Interface
Class C
Implements I1
Public Function {|Definition:Goo|}() As Integer Implements I1.[|Goo|]
Return 1
End Function
End Class
Class M
Inherits C
Implements I2
Public Overloads Function Goo() As Integer Implements I2.Goo
Return 1
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540359")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestShadowedMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I1
Function {|Definition:Goo|}() As Integer
End Interface
Interface I2
Inherits I1
Shadows Function Goo() As Integer
End Interface
Class C
Implements I1
Public Function {|Definition:$$Goo|}() As Integer Implements I1.[|Goo|]
Return 1
End Function
End Class
Class M
Inherits C
Implements I2
Public Overloads Function Goo() As Integer Implements I2.Goo
Return 1
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540359")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestShadowedMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I1
Function Goo() As Integer
End Interface
Interface I2
Inherits I1
Shadows Function {|Definition:$$Goo|}() As Integer
End Interface
Class C
Implements I1
Public Function Goo() As Integer Implements I1.Goo
Return 1
End Function
End Class
Class M
Inherits C
Implements I2
Public Overloads Function {|Definition:Goo|}() As Integer Implements I2.[|Goo|]
Return 1
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540359")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestShadowedMethod4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Interface I1
Function Goo() As Integer
End Interface
Interface I2
Inherits I1
Shadows Function {|Definition:Goo|}() As Integer
End Interface
Class C
Implements I1
Public Function Goo() As Integer Implements I1.Goo
Return 1
End Function
End Class
Class M
Inherits C
Implements I2
Public Overloads Function {|Definition:$$Goo|}() As Integer Implements I2.[|Goo|]
Return 1
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540946")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAddressOfOverloads1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim a As Action(Of Integer) = AddressOf [|$$Goo|]
End Sub
Sub Goo()
End Sub
Shared Sub {|Definition:Goo|}(x As Integer)
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540946")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAddressOfOverloads2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim a As Action(Of Integer) = AddressOf [|Goo|]
End Sub
Sub Goo()
End Sub
Shared Sub {|Definition:$$Goo|}(x As Integer)
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540946")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestAddressOfOverloads3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Strict On
Imports System
Class C
Shared Sub Main()
Dim a As Action(Of Integer) = AddressOf Goo
End Sub
Sub {|Definition:$$Goo|}()
End Sub
Shared Sub Goo(x As Integer)
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542034")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFunctionValue1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Public Class MyClass1
Public Shared Sub Main()
End Sub
Shared Function {|Definition:$$Function1|}(ByRef arg)
[|Function1|] = arg * 2
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542034, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542034")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFunctionValue2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Public Class MyClass1
Public Shared Sub Main()
End Sub
Shared Function {|Definition:Function1|}(ByRef arg)
[|$$Function1|] = arg * 2
End Function
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543002")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestForEachGetEnumerator1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class B
{
public int Current { get; set; }
public bool MoveNext()
{
return false;
}
}
class C
{
static void Main()
{
[|foreach|] (var x in new C()) { }
}
public B {|Definition:$$GetEnumerator|}()
{
return null;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestForEachGetEnumeratorViaExtension(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true" LanguageVersion="Preview">
<Document>
class B
{
public int Current { get; set; }
public bool MoveNext()
{
return false;
}
}
class C
{
static void Main()
{
[|foreach|] (var x in new C()) { }
}
}
public static class Extensions
{
public static B {|Definition:$$GetEnumerator|}(this C c)
{
return null;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543002")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestForEachMoveNext1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class B
{
public int Current { get; set; }
public bool {|Definition:$$MoveNext|}()
{
return false;
}
}
class C
{
static void Main()
{
[|foreach|] (var x in new C()) { }
}
public B GetEnumerator()
{
return null;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543002")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestForEachCurrent1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class B
{
public int {|Definition:$$Current|} { get; set; }
public bool MoveNext()
{
return false;
}
}
class C
{
static void Main()
{
[|foreach|] (var x in new C()) { }
}
public B GetEnumerator()
{
return null;
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544439")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodPartial1_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Class1
{
partial void {|Definition:$$goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U;
partial void {|Definition:goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544439")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodPartial2_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Class1
{
partial void {|Definition:$$goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U;
partial void {|Definition:goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544439")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodExtendedPartial1_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Class1
{
public partial void {|Definition:$$goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U;
public partial void {|Definition:goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544439")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodExtendedPartial2_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Class1
{
public partial void {|Definition:$$goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U;
public partial void {|Definition:goo|}<T, U, V>(T x, U y, V z) where T : class where U : Exception, T where V : U
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544437")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodPartial1_VB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Public Module Module1
Partial Private Sub {|Definition:$$GOo|}(Of T As Class, U As T, V As {U, Exception})(aa As T, y As U, z As V)
End Sub
Private Sub {|Definition:goo|}(Of T As Class, U As T, V As {U, Exception})(aa As T, y As U, z As V)
Console.WriteLine("goo")
End Sub
Sub Main()
End Sub
End Module
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(544437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544437")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodPartial2_VB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Public Module Module1
Partial Private Sub {|Definition:GOo|}(Of T As Class, U As T, V As {U, Exception})(aa As T, y As U, z As V)
End Sub
Private Sub {|Definition:$$goo|}(Of T As Class, U As T, V As {U, Exception})(aa As T, y As U, z As V)
Console.WriteLine("goo")
End Sub
Sub Main()
End Sub
End Module
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestInterfaceMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public Main()
{
var c1 = new Class1();
var c2 = new Class2();
var c3 = new Class3();
PrintMyName(c1);
PrintMyName(c2);
PrintMyName(c3);
}
public void PrintMyName(IClass c)
{
Console.WriteLine(c.$$[|GetMyName|]());
}
public class Class1 : IClass
{
public string {|Definition:GetMyName|}()
{
return "Class1";
}
}
public class Class2 : IClass
{
public string {|Definition:GetMyName|}()
{
return "Class2";
}
}
public class Class3 : Class2
{
public new string GetMyName()
{
return "Class3";
}
}
public interface IClass
{
string {|Definition:GetMyName|}();
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCrefMethod(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
/// <see cref="Program.[|Main|]"/> to start the program.
static void {|Definition:Ma$$in|}(string[] args)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCrefMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class Program
{
/// <see cref="Program.[|Ma$$in|]"/> to start the program.
static void {|Definition:Main|}(string[] args)
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCrefMethodAcrossMultipleFiles(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Program
{
/// <see cref="Program.[|Main|]"/> to start the program.
static void {|Definition:Ma$$in|}(string[] args)
{
}
}
]]>
</Document>
<Document><![CDATA[
partial class Program
{
/// <see cref="Program.[|Main|]"/>
void goo() {}
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCrefMethodAcrossMultipleFiles2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class Program
{
/// <see cref="Program.[|Main|]"/> to start the program.
static void {|Definition:Main|}(string[] args)
{
}
}
]]>
</Document>
<Document><![CDATA[
partial class Program
{
/// <see cref="Program.[|Ma$$in|]"/>
void goo() {}
{
}
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(531010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531010")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCrossAssemblyReferencesFromMetadata(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<MetadataReferenceFromSource Language="Visual Basic" CommonReferences="true">
<Document FilePath="ReferencedDocument">
Public Interface I
Sub Goo()
End Interface
Friend Class F : Implements I
Public Sub Goo() Implements I.Goo
End Sub
End Class
</Document>
</MetadataReferenceFromSource>
<Document>
Public Class C
Sub Bar(i As I)
i.$$[|Goo|]()
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(623148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623148")>
Public Async Function TestFarWithInternalVisibleTo(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="ProjectA" CommonReferences="true">
<Document>
<![CDATA[
<Assembly: Global.System.Runtime.CompilerServices.InternalsVisibleTo("ProjectB")>
Friend Class A
Public Sub {|Definition:$$Goo|}()
End Sub
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="ProjectB" CommonReferences="true">
<ProjectReference>ProjectA</ProjectReference>
<Document>
<![CDATA[
Public Class B
Public Sub Bar(a as A)
a.[|Goo|]()
End Sub
End Class]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(657262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657262")>
Public Async Function TestMethodInsideMetadataToSourcePrimitiveTypeInCSharpSource(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="mscorlib" CommonReferences="true">
<Document>
namespace System
{
struct Int32
{
public override string {|Definition:$$ToString|}() { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
<WorkItem(657262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657262")>
Public Async Function TestMethodInsideMetadataToSourcePrimitiveTypeInVisualBasicSource(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="mscorlib" CommonReferences="true">
<Document>
Namespace System
Structure Int32
Public Overrides Function {|Definition:$$ToString|}() As String
End Function
End Structure
End Namespace
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingMethod_Basic(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableClassLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System.Collections.Generic;
namespace PortableClassLibrary
{
public class Class1
{
int x;
public void {|Definition:Go$$o|}(int x) { }
}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="MainLibrary" CommonReferences="true">
<ProjectReference>PortableClassLibrary</ProjectReference>
<Document><;
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingMethod_GenericType(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableClassLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
namespace PortableClassLibrary
{
public class Class1
{
Tuple<int> x;
public void {|Definition:Go$$o|}(Tuple<int> x) { }
}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="MainLibrary" CommonReferences="true">
<ProjectReference>PortableClassLibrary</ProjectReference>
<Document><;
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingMethod_FARFromReferencingProject(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableClassLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
namespace PortableClassLibrary
{
public class Class1
{
Tuple<int> x;
public void {|Definition:Goo|}(Tuple<int> x) { }
}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="MainLibrary" CommonReferences="true">
<ProjectReference>PortableClassLibrary</ProjectReference>
<Document><;
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingMethod_MultipleForwardedTypes(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableClassLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
namespace PortableClassLibrary
{
public class Class1
{
Tuple<int> x;
public void {|Definition:$$Goo|}(Tuple<int> x, float y) { }
}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="MainLibrary" CommonReferences="true">
<ProjectReference>PortableClassLibrary</ProjectReference>
<Document><;
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(55955, "https://github.com/dotnet/roslyn/issues/55955")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingInheritanceAcrossProjects(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableInterfaceLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System;
public interface IInterface
{
void {|Definition:$$Method|}(string s) { }
}
]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="PortableClassLibrary1" CommonReferencesPortable="true">
<ProjectReference>PortableInterfaceLibrary</ProjectReference>
<Document><![CDATA[
using System;
public class PortableClass : IInterface
{
public virtual void {|Definition:Method|}(string s) {}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="NormalClassLibrary1" CommonReferences="true">
<ProjectReference>PortableInterfaceLibrary</ProjectReference>
<Document><![CDATA[
using System;
public class NormalClass : IInterface
{
public virtual void {|Definition:Method|}(string s) {}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="ReferencesBoth" CommonReferences="true">
<ProjectReference>PortableInterfaceLibrary</ProjectReference>
<ProjectReference>PortableClassLibrary1</ProjectReference>
<ProjectReference>NormalClassLibrary1</ProjectReference>
<Document><;
new NormalClass().[|Method|](s);
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRetargetingMethod_NestedType(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="PortableClassLibrary" CommonReferencesPortable="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
namespace PortableClassLibrary
{
public class Class1
{
public void {|Definition:$$Goo|}(System.Environment.SpecialFolder x) { }
}
}]]>
</Document>
</Project>
<Project Language="C#" AssemblyName="MainLibrary" CommonReferences="true">
<ProjectReference>PortableClassLibrary</ProjectReference>
<Document><;
}
}]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRefKindRef_FromDefinition(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="Lib" CommonReferences="true">
<Document><![CDATA[
using System;
public class C
{
public static void {|Definition:$$M|}(ref int x) { }
}
]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Test" CommonReferences="true">
<ProjectReference>Lib</ProjectReference>
<Document><
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRefKindRef_FromReference(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="Lib" CommonReferences="true">
<Document><![CDATA[
using System;
public class C
{
public static void {|Definition:M|}(ref int x) { }
}
]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Test" CommonReferences="true">
<ProjectReference>Lib</ProjectReference>
<Document><
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRefKindOut_FromDefinition(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="Lib" CommonReferences="true">
<Document><![CDATA[
using System;
public class C
{
public static void {|Definition:$$M|}(out int x) { }
}
]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Test" CommonReferences="true">
<ProjectReference>Lib</ProjectReference>
<Document><
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(599, "https://github.com/dotnet/roslyn/issues/599")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestRefKindOut_FromReference(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" AssemblyName="Lib" CommonReferences="true">
<Document><![CDATA[
using System;
public class C
{
public static void {|Definition:M|}(out int x) { }
}
]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Test" CommonReferences="true">
<ProjectReference>Lib</ProjectReference>
<Document><
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(428072, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/428072")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestInterfaceMethodImplementedInStruct1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface IGoo
{
void {|Definition:$$Goo|}();
}
public struct MyStruct : IGoo
{
public void {|Definition:Goo|}()
{
throw new System.NotImplementedException();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(428072, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/428072")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestInterfaceMethodImplementedInStruct2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface IGoo
{
void {|Definition:Goo|}();
}
public struct MyStruct : IGoo
{
public void {|Definition:$$Goo|}()
{
throw new System.NotImplementedException();
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodReferenceInGlobalSuppression(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:C.[|M|]")]
class C
{
private void {|Definition:$$M|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodReferenceInGlobalSuppression_MethodWithParameters(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:C.[|M|](System.String)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:C.M(System.Int32)")]
class C
{
private void {|Definition:$$M|}(string s) { }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodWithMissingReferences_CSharp(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="false">
<Document>
class C
{
// string will be an error type because we have no actual references.
private void {|Definition:Goo|}(string s) { }
void Bar()
{
[|Go$$o|]("");
[|Goo|](s);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodWithMissingReferences_VB(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="false">
<Document>
class C
' string will be an error type because we have no actual references.
private sub {|Definition:Goo|}(s as string)
end sub
sub Bar()
[|Go$$o|]("")
[|Goo|](s)
end sub
end class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestOrdinaryMethodUsedInSourceGenerator(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C
{
private void {|Definition:Goo|}() { }
}
</Document>
<DocumentFromSourceGenerator>
partial class C
{
void Bar()
{
[|Go$$o|]();
[|Goo|]();
B.Goo();
new C().[|Goo|]();
new C().goo();
}
}
</DocumentFromSourceGenerator>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFeatureHierarchyCascade1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:$$Goo|}();
}
interface I2
{
void Goo();
}
class B : I1
{
public virtual void {|Definition:Goo|}() {}
}
class D1 : B, I1, I2
{
public override void {|Definition:Goo|}() {}
}
class D2 : B, I1
{
public override void {|Definition:Goo|}() {}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFeatureHierarchyCascade2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void Goo();
}
interface I2
{
void {|Definition:$$Goo|}();
}
class B : I1
{
public virtual void Goo() {}
}
class D1 : B, I1, I2
{
public override void {|Definition:Goo|}() {}
}
class D2 : B, I1
{
public override void Goo() {}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFeatureHierarchyCascade3(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Goo|}();
}
interface I2
{
void Goo();
}
class B : I1
{
public virtual void {|Definition:$$Goo|}() {}
}
class D1 : B, I1, I2
{
public override void {|Definition:Goo|}() {}
}
class D2 : B, I1
{
public override void {|Definition:Goo|}() {}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFeatureHierarchyCascade4(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Goo|}();
}
interface I2
{
void {|Definition:Goo|}();
}
class B : I1
{
public virtual void {|Definition:Goo|}() {}
}
class D1 : B, I1, I2
{
public override void {|Definition:$$Goo|}() {}
}
class D2 : B, I1
{
public override void Goo() {}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestFeatureHierarchyCascade5(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
void {|Definition:Goo|}();
}
interface I2
{
void Goo();
}
class B : I1
{
public virtual void {|Definition:Goo|}() {}
}
class D1 : B, I1, I2
{
public override void Goo() {}
}
class D2 : B, I1
{
public override void {|Definition:$$Goo|}() {}
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMemberStaticAbstractMethodFromInterface(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
static abstract void {|Definition:M$$1|}();
}
class C1_1 : I1
{
public static void {|Definition:M1|}() { }
}
class C1_2 : I1
{
static void I1.{|Definition:M1|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDerivedMemberStaticAbstractMethodViaFeature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
static abstract void {|Definition:M1|}();
}
class C1_1 : I1
{
public static void {|Definition:M$$1|}() { }
}
class C1_2 : I1
{
static void I1.M1() { }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDerivedMemberStaticAbstractMethodViaFeature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
static abstract void {|Definition:M1|}();
}
class C1_1 : I1
{
public static void M1() { }
}
class C1_2 : I1
{
static void I1.{|Definition:M$$1|}() { }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDerivedMemberStaticAbstractMethodViaAPI1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
static abstract void {|Definition:M1|}();
}
class C1_1 : I1
{
public static void {|Definition:M$$1|}() { }
}
class C1_2 : I1
{
static void I1.{|Definition:M1|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDerivedMemberStaticAbstractMethodViaAPI2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
static abstract void {|Definition:M1|}();
}
class C1_1 : I1
{
public static void {|Definition:M1|}() { }
}
class C1_2 : I1
{
static void I1.{|Definition:M$$1|}() { }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
End Class
End Namespace
| 1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.BidirectionalSymbolSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// Symbol set used when <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> is <see
/// langword="false"/>. This symbol set will cascade up *and* down the inheritance hierarchy for all symbols we
/// are searching for. This is the symbol set used for features like 'Rename', where all cascaded symbols must
/// be updated in order to keep the code compiling.
/// </summary>
private sealed class BidirectionalSymbolSet : SymbolSet
{
/// <summary>
/// When we're cascading in both direction, we can just keep all symbols in a single set. We'll always be
/// examining all of them to go in both up and down directions in every project we process. Any time we
/// add a new symbol to it we'll continue to cascade in both directions looking for more.
/// </summary>
private readonly HashSet<ISymbol> _allSymbols = new();
public BidirectionalSymbolSet(FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, HashSet<ISymbol> upSymbols)
: base(engine)
{
_allSymbols.AddRange(initialSymbols);
_allSymbols.AddRange(upSymbols);
}
public override ImmutableArray<ISymbol> GetAllSymbols()
=> _allSymbols.ToImmutableArray();
public override async Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken)
{
// Start searching using the current set of symbols built up so far.
var workQueue = new Stack<ISymbol>();
workQueue.Push(_allSymbols);
var projects = ImmutableHashSet.Create(project);
while (workQueue.Count > 0)
{
var current = workQueue.Pop();
// For each symbol we're examining try to walk both up and down from it to see if we discover any
// new symbols in this project. As long as we keep finding symbols, we'll keep searching from them
// in both directions.
await AddDownSymbolsAsync(this.Engine, current, _allSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false);
await AddUpSymbolsAsync(this.Engine, current, _allSymbols, workQueue, projects, 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.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// Symbol set used when <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> is <see
/// langword="false"/>. This symbol set will cascade up *and* down the inheritance hierarchy for all symbols we
/// are searching for. This is the symbol set used for features like 'Rename', where all cascaded symbols must
/// be updated in order to keep the code compiling.
/// </summary>
private sealed class BidirectionalSymbolSet : SymbolSet
{
/// <summary>
/// When we're cascading in both direction, we can just keep all symbols in a single set. We'll always be
/// examining all of them to go in both up and down directions in every project we process. Any time we
/// add a new symbol to it we'll continue to cascade in both directions looking for more.
/// </summary>
private readonly MetadataUnifyingSymbolHashSet _allSymbols = new();
public BidirectionalSymbolSet(FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, HashSet<ISymbol> upSymbols)
: base(engine)
{
_allSymbols.AddRange(initialSymbols);
_allSymbols.AddRange(upSymbols);
}
public override ImmutableArray<ISymbol> GetAllSymbols()
=> _allSymbols.ToImmutableArray();
public override async Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken)
{
// Start searching using the current set of symbols built up so far.
var workQueue = new Stack<ISymbol>();
workQueue.Push(_allSymbols);
var projects = ImmutableHashSet.Create(project);
while (workQueue.Count > 0)
{
var current = workQueue.Pop();
// For each symbol we're examining try to walk both up and down from it to see if we discover any
// new symbols in this project. As long as we keep finding symbols, we'll keep searching from them
// in both directions.
await AddDownSymbolsAsync(this.Engine, current, _allSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false);
await AddUpSymbolsAsync(this.Engine, current, _allSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false);
}
}
}
}
}
| 1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.SymbolSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// Represents the set of symbols that the engine is searching for. While the find-refs engine is passed an
/// initial symbol to find results for, the engine will often have to 'cascade' that symbol to many more symbols
/// that clients will also need. This includes:
/// <list type="number">
/// <item>Cascading to all linked symbols for the requested symbol. This ensures a unified set of results for a
/// particular symbol, regardless of what project context it was originally found in.</item>
/// <item>Symbol specific cascading. For example, when searching for a named type, references to that named
/// type will be found through its constructors.</item>
/// <item>Cascading up and down the inheritance hierarchy for members (e.g. methods, properties, events). This
/// is controllable through the <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/>
/// option.</item>
/// </list>
/// </summary>
private abstract class SymbolSet
{
protected readonly FindReferencesSearchEngine Engine;
protected SymbolSet(FindReferencesSearchEngine engine)
{
Engine = engine;
}
protected Solution Solution => Engine._solution;
/// <summary>
/// Get a copy of all the symbols in the set. Cannot be called concurrently with <see
/// cref="InheritanceCascadeAsync"/>
/// </summary>
public abstract ImmutableArray<ISymbol> GetAllSymbols();
/// <summary>
/// Update the set of symbols in this set with any appropriate symbols in the inheritance hierarchy brought
/// in within <paramref name="project"/>. For example, given a project 'A' with interface <c>interface IGoo
/// { void Goo(); }</c>, and a project 'B' with class <c>class Goo : IGoo { public void Goo() { } }</c>,
/// then initially the symbol set will only contain IGoo.Goo. However, when project 'B' is processed, this
/// will add Goo.Goo is added to the set as well so that references to it can be found.
/// </summary>
/// <remarks>
/// This method is non threadsafe as it mutates the symbol set instance. As such, it should only be
/// called serially. <see cref="GetAllSymbols"/> should not be called concurrently with this.
/// </remarks>
public abstract Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken);
private static bool InvolvesInheritance(ISymbol symbol)
=> symbol.Kind is SymbolKind.Method or SymbolKind.Property or SymbolKind.Event;
public static async Task<SymbolSet> CreateAsync(
FindReferencesSearchEngine engine, ISymbol symbol, CancellationToken cancellationToken)
{
var solution = engine._solution;
var options = engine._options;
// Start by mapping the initial symbol to the appropriate source symbol in originating project if possible.
var searchSymbol = await MapToAppropriateSymbolAsync(solution, symbol, cancellationToken).ConfigureAwait(false);
// If the caller doesn't want any cascading then just return an appropriate set that will just point at
// only the search symbol and won't cascade to any related symbols, linked symbols, or inheritance
// symbols.
if (!options.Cascade)
return new NonCascadingSymbolSet(engine, searchSymbol);
// Keep track of the initial symbol group corresponding to search-symbol. Any references to this group
// will always be reported.
//
// Depending on what type of search we're doing, return an appropriate set that will have those
// inheritance cascading semantics.
var initialSymbols = await DetermineInitialSearchSymbolsAsync(engine, searchSymbol, cancellationToken).ConfigureAwait(false);
// Walk and find all the symbols above the starting symbol set.
var upSymbols = await DetermineInitialUpSymbolsAsync(engine, initialSymbols, cancellationToken).ConfigureAwait(false);
return options.UnidirectionalHierarchyCascade
? new UnidirectionalSymbolSet(engine, initialSymbols, upSymbols)
: new BidirectionalSymbolSet(engine, initialSymbols, upSymbols);
}
private static async Task<ISymbol> MapToAppropriateSymbolAsync(
Solution solution, ISymbol symbol, CancellationToken cancellationToken)
{
// Never search for an alias. Always search for it's target. Note: if the caller was
// actually searching for an alias, they can always get that information out in the end
// by checking the ReferenceLocations that are returned.
var searchSymbol = symbol;
if (searchSymbol is IAliasSymbol aliasSymbol)
searchSymbol = aliasSymbol.Target;
searchSymbol = searchSymbol.GetOriginalUnreducedDefinition();
// If they're searching for a delegate constructor, then just search for the delegate
// itself. They're practically interchangeable for consumers.
if (searchSymbol.IsConstructor() && searchSymbol.ContainingType.TypeKind == TypeKind.Delegate)
searchSymbol = symbol.ContainingType;
Contract.ThrowIfNull(searchSymbol);
// Attempt to map this symbol back to a source symbol if possible as we always prefer the original
// source definition as the 'truth' of a symbol versus seeing it projected into dependent cross language
// projects as a metadata symbol. If there is no source symbol, then continue to just use the metadata
// symbol as the one to be looking for.
var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(searchSymbol, solution, cancellationToken).ConfigureAwait(false);
return sourceSymbol ?? searchSymbol;
}
/// <summary>
/// Determines the initial set of symbols that we should actually be finding references for given a request
/// to find refs to <paramref name="symbol"/>. This will include any symbols that a specific <see
/// cref="IReferenceFinder"/> cascades to, as well as all the linked symbols to those across any
/// multi-targetting/shared-project documents. This will not include symbols up or down the inheritance
/// hierarchy.
/// </summary>
private static async Task<HashSet<ISymbol>> DetermineInitialSearchSymbolsAsync(
FindReferencesSearchEngine engine, ISymbol symbol, CancellationToken cancellationToken)
{
var result = new HashSet<ISymbol>();
var workQueue = new Stack<ISymbol>();
// Start with the initial symbol we're searching for.
workQueue.Push(symbol);
// As long as there's work in the queue, keep going.
while (workQueue.Count > 0)
{
var currentSymbol = workQueue.Pop();
await AddCascadedAndLinkedSymbolsToAsync(engine, currentSymbol, result, workQueue, cancellationToken).ConfigureAwait(false);
}
return result;
}
private static async Task<HashSet<ISymbol>> DetermineInitialUpSymbolsAsync(
FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, CancellationToken cancellationToken)
{
var upSymbols = new HashSet<ISymbol>();
var workQueue = new Stack<ISymbol>();
workQueue.Push(initialSymbols);
var solution = engine._solution;
var allProjects = solution.Projects.ToImmutableHashSet();
while (workQueue.Count > 0)
{
var currentSymbol = workQueue.Pop();
await AddUpSymbolsAsync(engine, currentSymbol, upSymbols, workQueue, allProjects, cancellationToken).ConfigureAwait(false);
}
return upSymbols;
}
protected static async Task AddCascadedAndLinkedSymbolsToAsync(
FindReferencesSearchEngine engine, ImmutableArray<ISymbol> symbols, HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue, CancellationToken cancellationToken)
{
foreach (var symbol in symbols)
await AddCascadedAndLinkedSymbolsToAsync(engine, symbol, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
}
protected static async Task AddCascadedAndLinkedSymbolsToAsync(
FindReferencesSearchEngine engine, ISymbol symbol, HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue, CancellationToken cancellationToken)
{
var solution = engine._solution;
symbol = await MapAndAddLinkedSymbolsAsync(symbol).ConfigureAwait(false);
foreach (var finder in engine._finders)
{
var cascaded = await finder.DetermineCascadedSymbolsAsync(symbol, solution, engine._options, cancellationToken).ConfigureAwait(false);
foreach (var cascade in cascaded)
await MapAndAddLinkedSymbolsAsync(cascade).ConfigureAwait(false);
}
return;
async Task<ISymbol> MapAndAddLinkedSymbolsAsync(ISymbol symbol)
{
symbol = await MapToAppropriateSymbolAsync(solution, symbol, cancellationToken).ConfigureAwait(false);
foreach (var linked in await SymbolFinder.FindLinkedSymbolsAsync(symbol, solution, cancellationToken).ConfigureAwait(false))
{
if (seenSymbols.Add(linked))
workQueue.Push(linked);
}
return symbol;
}
}
/// <summary>
/// Finds all the symbols 'down' the inheritance hierarchy of <paramref name="symbol"/> in the given
/// project. The symbols found are added to <paramref name="seenSymbols"/>. If <paramref name="seenSymbols"/> did not
/// contain that symbol, then it is also added to <paramref name="workQueue"/> to allow fixed point
/// algorithms to continue.
/// </summary>
/// <remarks><paramref name="projects"/> will always be a single project. We just pass this in as a set to
/// avoid allocating a fresh set every time this calls into FindMemberImplementationsArrayAsync.
/// </remarks>
protected static async Task AddDownSymbolsAsync(
FindReferencesSearchEngine engine, ISymbol symbol,
HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue,
ImmutableHashSet<Project> projects, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(projects.Count == 1, "Only a single project should be passed in");
// Don't bother on symbols that aren't even involved in inheritance computations.
if (!InvolvesInheritance(symbol))
return;
var solution = engine._solution;
if (symbol.IsImplementableMember())
{
var implementations = await SymbolFinder.FindMemberImplementationsArrayAsync(
symbol, solution, projects, cancellationToken).ConfigureAwait(false);
await AddCascadedAndLinkedSymbolsToAsync(engine, implementations, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
}
else
{
var overrrides = await SymbolFinder.FindOverridesArrayAsync(
symbol, solution, projects, cancellationToken).ConfigureAwait(false);
await AddCascadedAndLinkedSymbolsToAsync(engine, overrrides, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Finds all the symbols 'up' the inheritance hierarchy of <paramref name="symbol"/> in the solution. The
/// symbols found are added to <paramref name="seenSymbols"/>. If <paramref name="seenSymbols"/> did not contain that symbol,
/// then it is also added to <paramref name="workQueue"/> to allow fixed point algorithms to continue.
/// </summary>
protected static async Task AddUpSymbolsAsync(
FindReferencesSearchEngine engine, ISymbol symbol,
HashSet<ISymbol> seenSymbols, Stack<ISymbol> workQueue,
ImmutableHashSet<Project> projects, CancellationToken cancellationToken)
{
if (!InvolvesInheritance(symbol))
return;
var solution = engine._solution;
var originatingProject = solution.GetOriginatingProject(symbol);
if (originatingProject != null)
{
// We have a normal method. Find any interface methods up the inheritance hierarchy that it implicitly
// or explicitly implements and cascade to those.
foreach (var match in await SymbolFinder.FindImplementedInterfaceMembersArrayAsync(symbol, solution, projects, cancellationToken).ConfigureAwait(false))
await AddCascadedAndLinkedSymbolsToAsync(engine, match, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
}
// If we're overriding a member, then add it to the up-set
if (symbol.GetOverriddenMember() is ISymbol overriddenMember)
await AddCascadedAndLinkedSymbolsToAsync(engine, overriddenMember, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
// An explicit interface method will cascade to all the methods that it implements in the up direction.
await AddCascadedAndLinkedSymbolsToAsync(engine, symbol.ExplicitInterfaceImplementations(), seenSymbols, workQueue, 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.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// Represents the set of symbols that the engine is searching for. While the find-refs engine is passed an
/// initial symbol to find results for, the engine will often have to 'cascade' that symbol to many more symbols
/// that clients will also need. This includes:
/// <list type="number">
/// <item>Cascading to all linked symbols for the requested symbol. This ensures a unified set of results for a
/// particular symbol, regardless of what project context it was originally found in.</item>
/// <item>Symbol specific cascading. For example, when searching for a named type, references to that named
/// type will be found through its constructors.</item>
/// <item>Cascading up and down the inheritance hierarchy for members (e.g. methods, properties, events). This
/// is controllable through the <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/>
/// option.</item>
/// </list>
/// </summary>
private abstract class SymbolSet
{
protected readonly FindReferencesSearchEngine Engine;
protected SymbolSet(FindReferencesSearchEngine engine)
{
Engine = engine;
}
protected Solution Solution => Engine._solution;
/// <summary>
/// Get a copy of all the symbols in the set. Cannot be called concurrently with <see
/// cref="InheritanceCascadeAsync"/>
/// </summary>
public abstract ImmutableArray<ISymbol> GetAllSymbols();
/// <summary>
/// Update the set of symbols in this set with any appropriate symbols in the inheritance hierarchy brought
/// in within <paramref name="project"/>. For example, given a project 'A' with interface <c>interface IGoo
/// { void Goo(); }</c>, and a project 'B' with class <c>class Goo : IGoo { public void Goo() { } }</c>,
/// then initially the symbol set will only contain IGoo.Goo. However, when project 'B' is processed, this
/// will add Goo.Goo is added to the set as well so that references to it can be found.
/// </summary>
/// <remarks>
/// This method is non threadsafe as it mutates the symbol set instance. As such, it should only be
/// called serially. <see cref="GetAllSymbols"/> should not be called concurrently with this.
/// </remarks>
public abstract Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken);
private static bool InvolvesInheritance(ISymbol symbol)
=> symbol.Kind is SymbolKind.Method or SymbolKind.Property or SymbolKind.Event;
public static async Task<SymbolSet> CreateAsync(
FindReferencesSearchEngine engine, ISymbol symbol, CancellationToken cancellationToken)
{
var solution = engine._solution;
var options = engine._options;
// Start by mapping the initial symbol to the appropriate source symbol in originating project if possible.
var searchSymbol = await MapToAppropriateSymbolAsync(solution, symbol, cancellationToken).ConfigureAwait(false);
// If the caller doesn't want any cascading then just return an appropriate set that will just point at
// only the search symbol and won't cascade to any related symbols, linked symbols, or inheritance
// symbols.
if (!options.Cascade)
return new NonCascadingSymbolSet(engine, searchSymbol);
// Keep track of the initial symbol group corresponding to search-symbol. Any references to this group
// will always be reported.
//
// Depending on what type of search we're doing, return an appropriate set that will have those
// inheritance cascading semantics.
var initialSymbols = await DetermineInitialSearchSymbolsAsync(engine, searchSymbol, cancellationToken).ConfigureAwait(false);
// Walk and find all the symbols above the starting symbol set.
var upSymbols = await DetermineInitialUpSymbolsAsync(engine, initialSymbols, cancellationToken).ConfigureAwait(false);
return options.UnidirectionalHierarchyCascade
? new UnidirectionalSymbolSet(engine, initialSymbols, upSymbols)
: new BidirectionalSymbolSet(engine, initialSymbols, upSymbols);
}
private static async Task<ISymbol> MapToAppropriateSymbolAsync(
Solution solution, ISymbol symbol, CancellationToken cancellationToken)
{
// Never search for an alias. Always search for it's target. Note: if the caller was
// actually searching for an alias, they can always get that information out in the end
// by checking the ReferenceLocations that are returned.
var searchSymbol = symbol;
if (searchSymbol is IAliasSymbol aliasSymbol)
searchSymbol = aliasSymbol.Target;
searchSymbol = searchSymbol.GetOriginalUnreducedDefinition();
// If they're searching for a delegate constructor, then just search for the delegate
// itself. They're practically interchangeable for consumers.
if (searchSymbol.IsConstructor() && searchSymbol.ContainingType.TypeKind == TypeKind.Delegate)
searchSymbol = symbol.ContainingType;
Contract.ThrowIfNull(searchSymbol);
// Attempt to map this symbol back to a source symbol if possible as we always prefer the original
// source definition as the 'truth' of a symbol versus seeing it projected into dependent cross language
// projects as a metadata symbol. If there is no source symbol, then continue to just use the metadata
// symbol as the one to be looking for.
var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(searchSymbol, solution, cancellationToken).ConfigureAwait(false);
return sourceSymbol ?? searchSymbol;
}
/// <summary>
/// Determines the initial set of symbols that we should actually be finding references for given a request
/// to find refs to <paramref name="symbol"/>. This will include any symbols that a specific <see
/// cref="IReferenceFinder"/> cascades to, as well as all the linked symbols to those across any
/// multi-targetting/shared-project documents. This will not include symbols up or down the inheritance
/// hierarchy.
/// </summary>
private static async Task<MetadataUnifyingSymbolHashSet> DetermineInitialSearchSymbolsAsync(
FindReferencesSearchEngine engine, ISymbol symbol, CancellationToken cancellationToken)
{
var result = new MetadataUnifyingSymbolHashSet();
var workQueue = new Stack<ISymbol>();
// Start with the initial symbol we're searching for.
workQueue.Push(symbol);
// As long as there's work in the queue, keep going.
while (workQueue.Count > 0)
{
var currentSymbol = workQueue.Pop();
await AddCascadedAndLinkedSymbolsToAsync(engine, currentSymbol, result, workQueue, cancellationToken).ConfigureAwait(false);
}
return result;
}
private static async Task<HashSet<ISymbol>> DetermineInitialUpSymbolsAsync(
FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, CancellationToken cancellationToken)
{
var upSymbols = new MetadataUnifyingSymbolHashSet();
var workQueue = new Stack<ISymbol>();
workQueue.Push(initialSymbols);
var solution = engine._solution;
var allProjects = solution.Projects.ToImmutableHashSet();
while (workQueue.Count > 0)
{
var currentSymbol = workQueue.Pop();
await AddUpSymbolsAsync(engine, currentSymbol, upSymbols, workQueue, allProjects, cancellationToken).ConfigureAwait(false);
}
return upSymbols;
}
protected static async Task AddCascadedAndLinkedSymbolsToAsync(
FindReferencesSearchEngine engine, ImmutableArray<ISymbol> symbols, MetadataUnifyingSymbolHashSet seenSymbols, Stack<ISymbol> workQueue, CancellationToken cancellationToken)
{
foreach (var symbol in symbols)
await AddCascadedAndLinkedSymbolsToAsync(engine, symbol, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
}
protected static async Task AddCascadedAndLinkedSymbolsToAsync(
FindReferencesSearchEngine engine, ISymbol symbol, MetadataUnifyingSymbolHashSet seenSymbols, Stack<ISymbol> workQueue, CancellationToken cancellationToken)
{
var solution = engine._solution;
symbol = await MapAndAddLinkedSymbolsAsync(symbol).ConfigureAwait(false);
foreach (var finder in engine._finders)
{
var cascaded = await finder.DetermineCascadedSymbolsAsync(symbol, solution, engine._options, cancellationToken).ConfigureAwait(false);
foreach (var cascade in cascaded)
await MapAndAddLinkedSymbolsAsync(cascade).ConfigureAwait(false);
}
return;
async Task<ISymbol> MapAndAddLinkedSymbolsAsync(ISymbol symbol)
{
symbol = await MapToAppropriateSymbolAsync(solution, symbol, cancellationToken).ConfigureAwait(false);
foreach (var linked in await SymbolFinder.FindLinkedSymbolsAsync(symbol, solution, cancellationToken).ConfigureAwait(false))
{
if (seenSymbols.Add(linked))
workQueue.Push(linked);
}
return symbol;
}
}
/// <summary>
/// Finds all the symbols 'down' the inheritance hierarchy of <paramref name="symbol"/> in the given
/// project. The symbols found are added to <paramref name="seenSymbols"/>. If <paramref name="seenSymbols"/> did not
/// contain that symbol, then it is also added to <paramref name="workQueue"/> to allow fixed point
/// algorithms to continue.
/// </summary>
/// <remarks><paramref name="projects"/> will always be a single project. We just pass this in as a set to
/// avoid allocating a fresh set every time this calls into FindMemberImplementationsArrayAsync.
/// </remarks>
protected static async Task AddDownSymbolsAsync(
FindReferencesSearchEngine engine, ISymbol symbol,
MetadataUnifyingSymbolHashSet seenSymbols, Stack<ISymbol> workQueue,
ImmutableHashSet<Project> projects, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(projects.Count == 1, "Only a single project should be passed in");
// Don't bother on symbols that aren't even involved in inheritance computations.
if (!InvolvesInheritance(symbol))
return;
var solution = engine._solution;
if (symbol.IsImplementableMember())
{
var implementations = await SymbolFinder.FindMemberImplementationsArrayAsync(
symbol, solution, projects, cancellationToken).ConfigureAwait(false);
await AddCascadedAndLinkedSymbolsToAsync(engine, implementations, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
}
else
{
var overrrides = await SymbolFinder.FindOverridesArrayAsync(
symbol, solution, projects, cancellationToken).ConfigureAwait(false);
await AddCascadedAndLinkedSymbolsToAsync(engine, overrrides, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Finds all the symbols 'up' the inheritance hierarchy of <paramref name="symbol"/> in the solution. The
/// symbols found are added to <paramref name="seenSymbols"/>. If <paramref name="seenSymbols"/> did not contain that symbol,
/// then it is also added to <paramref name="workQueue"/> to allow fixed point algorithms to continue.
/// </summary>
protected static async Task AddUpSymbolsAsync(
FindReferencesSearchEngine engine, ISymbol symbol,
MetadataUnifyingSymbolHashSet seenSymbols, Stack<ISymbol> workQueue,
ImmutableHashSet<Project> projects, CancellationToken cancellationToken)
{
if (!InvolvesInheritance(symbol))
return;
var solution = engine._solution;
var originatingProject = solution.GetOriginatingProject(symbol);
if (originatingProject != null)
{
// We have a normal method. Find any interface methods up the inheritance hierarchy that it implicitly
// or explicitly implements and cascade to those.
foreach (var match in await SymbolFinder.FindImplementedInterfaceMembersArrayAsync(symbol, solution, projects, cancellationToken).ConfigureAwait(false))
await AddCascadedAndLinkedSymbolsToAsync(engine, match, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
}
// If we're overriding a member, then add it to the up-set
if (symbol.GetOverriddenMember() is ISymbol overriddenMember)
await AddCascadedAndLinkedSymbolsToAsync(engine, overriddenMember, seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
// An explicit interface method will cascade to all the methods that it implements in the up direction.
await AddCascadedAndLinkedSymbolsToAsync(engine, symbol.ExplicitInterfaceImplementations(), seenSymbols, workQueue, cancellationToken).ConfigureAwait(false);
}
}
}
}
| 1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.UnidirectionalSymbolSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// Symbol set used when <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> is <see
/// langword="true"/>. This symbol set will only cascade in a uniform direction once it walks either up or down
/// from the initial set of symbols. This is the symbol set used for features like 'Find Refs', where we only
/// want to return location results for members that could feasible actually end up calling into that member at
/// runtime. See the docs of <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> for more
/// information on this.
/// </summary>
private sealed class UnidirectionalSymbolSet : SymbolSet
{
private readonly HashSet<ISymbol> _initialAndDownSymbols;
/// <summary>
/// When we're doing a unidirectional find-references, the initial set of up-symbols can never change.
/// That's because we have computed the up set entirely up front, and no down symbols can produce new
/// up-symbols (as going down then up would not be unidirectional).
/// </summary>
private readonly ImmutableHashSet<ISymbol> _upSymbols;
public UnidirectionalSymbolSet(FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, HashSet<ISymbol> upSymbols)
: base(engine)
{
_initialAndDownSymbols = initialSymbols;
_upSymbols = upSymbols.ToImmutableHashSet();
}
public override ImmutableArray<ISymbol> GetAllSymbols()
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(_upSymbols.Count + _initialAndDownSymbols.Count, out var result);
result.AddRange(_upSymbols);
result.AddRange(_initialAndDownSymbols);
result.RemoveDuplicates();
return result.ToImmutable();
}
public override async Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken)
{
// Start searching using the existing set of symbols found at the start (or anything found below that).
var workQueue = new Stack<ISymbol>();
workQueue.Push(_initialAndDownSymbols);
var projects = ImmutableHashSet.Create(project);
while (workQueue.Count > 0)
{
var current = workQueue.Pop();
// Keep adding symbols downwards in this project as long as we keep finding new symbols.
await AddDownSymbolsAsync(this.Engine, current, _initialAndDownSymbols, workQueue, projects, 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.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// Symbol set used when <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> is <see
/// langword="true"/>. This symbol set will only cascade in a uniform direction once it walks either up or down
/// from the initial set of symbols. This is the symbol set used for features like 'Find Refs', where we only
/// want to return location results for members that could feasible actually end up calling into that member at
/// runtime. See the docs of <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> for more
/// information on this.
/// </summary>
private sealed class UnidirectionalSymbolSet : SymbolSet
{
private readonly MetadataUnifyingSymbolHashSet _initialAndDownSymbols;
/// <summary>
/// When we're doing a unidirectional find-references, the initial set of up-symbols can never change.
/// That's because we have computed the up set entirely up front, and no down symbols can produce new
/// up-symbols (as going down then up would not be unidirectional).
/// </summary>
private readonly ImmutableHashSet<ISymbol> _upSymbols;
public UnidirectionalSymbolSet(FindReferencesSearchEngine engine, MetadataUnifyingSymbolHashSet initialSymbols, HashSet<ISymbol> upSymbols)
: base(engine)
{
_initialAndDownSymbols = initialSymbols;
_upSymbols = upSymbols.ToImmutableHashSet();
}
public override ImmutableArray<ISymbol> GetAllSymbols()
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(_upSymbols.Count + _initialAndDownSymbols.Count, out var result);
result.AddRange(_upSymbols);
result.AddRange(_initialAndDownSymbols);
result.RemoveDuplicates();
return result.ToImmutable();
}
public override async Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken)
{
// Start searching using the existing set of symbols found at the start (or anything found below that).
var workQueue = new Stack<ISymbol>();
workQueue.Push(_initialAndDownSymbols);
var projects = ImmutableHashSet.Create(project);
while (workQueue.Count > 0)
{
var current = workQueue.Pop();
// Keep adding symbols downwards in this project as long as we keep finding new symbols.
await AddDownSymbolsAsync(this.Engine, current, _initialAndDownSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false);
}
}
}
}
}
| 1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Compilers/VisualBasic/Test/Syntax/Parser/ParseStatements.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports Roslyn.Test.Utilities
<CLSCompliant(False)>
Public Class ParseStatements
Inherits BasicTestBase
<Fact>
Public Sub ParseIf()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
if true then f() else if true then g()
If True
End If
If True Then
End If
If True Then
Else
End If
If True Then
ElseIf False Then
End If
If True Then
ElseIf False Then
Else
End If
if true then else
if true then else :
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseDo()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
Do
Loop
do while true
loop
do until true
loop
do
loop until true
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseWhile()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
dim x = 1
while x < 1
end while
with x
end with
synclock x
end synclock
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseFor()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
for i = 0 to 100
next
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseForEach()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
for each c in "hello"
next
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseSelect()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
select i
case 0
case 1
case 2
case else
end select
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseTry()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
try
catch
finally
end try
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseUsing()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
using e0
end using
using e1 as new C, e2 as new C
end using
using e3 as new with {.goo="bar"}
end using
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseUsingMultipleVariablesInAsNew()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
dim a, b as new C
using e1, e2 as new C, e3 as new C
end using
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseContinue()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
do
continue do
loop
while true
continue do
end while
for i = 0 to 10
continue for
next
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseExit()
ParseAndVerify(<![CDATA[
Module Module1
Sub s1()
do
exit do
loop
while true
exit while
end while
for i = 0 to 10
exit for
next
select 0
case 0
exit select
end select
try
exit try
catch
end try
Exit sub
end sub
function f1() as integer
exit function
end function
readonly property p1 as integer
get
exit property
end get
end property
End Module
]]>)
End Sub
<WorkItem(538594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538594")>
<Fact>
Public Sub ParseOnErrorGoto()
ParseAndVerify(<![CDATA[
Module Module1
Sub s1()
on error goto 0
on error goto 0UL
on error goto -1
on error goto -1UL
on error goto mylabel
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseResume()
ParseAndVerify(<![CDATA[
Module Module1
Sub s1()
resume next
resume mylabel
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseCallStatement()
ParseAndVerify(<![CDATA[
Module Module1
Sub s1()
call mysub(of string)(1,2,3,4)
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseRedim()
ParseAndVerify(<![CDATA[
Class c1
Dim a(,) As Integer
Sub s()
Dim a() As c1
ReDim a(10)
ReDim a(0 To 10)
ReDim Preserve a(10)
ReDim Preserve a(10).a(0 To 10, 0 To 20)
' the following is actually wrong according to the grammar
' but VB10 parses it, so we will too for now.
ReDim Preserve a(0 To 10).a(0 To 10, 0 To 20)
End Sub
End Class
]]>)
End Sub
<Fact>
Public Sub ParseReturn_Bug868414()
'Bug 868414 - Exception when return is missing expression.
ParseAndVerify(<![CDATA[
Class Class1
Function Goo() As Integer
Return
End Function
End Class
]]>)
End Sub
<Fact>
Public Sub ParseAssignmentOrCall()
ParseAndVerify(<![CDATA[
class c1
sub s
i = 1
i(10)
end sub
end class
]]>)
End Sub
<WorkItem(871360, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineIfThen()
ParseAndVerify(<![CDATA[
Class Class1
Function Goo() As Boolean
Return True
End Function
Sub Bar()
If Goo() = True Then Return True
If Goo() <> True Then
Return Not True
End If
End Sub
End Class
]]>)
End Sub
<WorkItem(539194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539194")>
<Fact>
Public Sub ParseSingleLineIfThenWithColon()
' Goo should be a call statement and not a label
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub Main()
If True Then Goo: Else
End Sub
Sub Goo()
End Sub
End Module
]]>)
Dim compUnit = tree.GetRoot()
Dim moduleM = TryCast(compUnit.ChildNodesAndTokens()(0).AsNode, TypeBlockSyntax)
Dim subMain = TryCast(moduleM.ChildNodesAndTokens()(1).AsNode, MethodBlockSyntax)
Dim ifStmt = TryCast(subMain.ChildNodesAndTokens()(1).AsNode, SingleLineIfStatementSyntax)
Dim goo = ifStmt.Statements(0)
Assert.Equal(SyntaxKind.ExpressionStatement, goo.Kind)
Assert.Equal(SyntaxKind.InvocationExpression, DirectCast(goo, ExpressionStatementSyntax).Expression.Kind)
End Sub
<Fact>
Public Sub ParseSingleLineIfThenWithElseIf()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub Main()
If True Then ElseIf True Then x = 2 end if
If True Then x = 1 elseIf true then x = 2 end if
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedEOS, "ElseIf True Then").WithLocation(4, 18),
Diagnostic(ERRID.ERR_ExpectedEOS, "x").WithLocation(4, 35),
Diagnostic(ERRID.ERR_ExpectedEOS, "elseIf").WithLocation(5, 24)
)
End Sub
<WorkItem(539204, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539204")>
<Fact>
Public Sub ParseColonLineCont()
' 2nd Else and ElseIf are dangling in the line ifs
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub Main()
' not an error
Return : _
End Sub
End Module
Module M2
Sub Main2()
' error
Return :_
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_LineContWithCommentOrNoPrecSpace, "_"))
End Sub
<WorkItem(539204, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539204")>
<Fact>
Public Sub ParseSingleLineIfThenExtraElse()
' 2nd Else and ElseIf are dangling in the line ifs
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If True Then Console.WriteLine Else Else Console.WriteLine
If True Then Console.WriteLine Else ElseIf Console.WriteLine
End Sub
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="84" end="88"/>
<error id="36005" message="'ElseIf' must be preceded by a matching 'If' or 'ElseIf'." start="152" end="176"/>
</errors>)
End Sub
<WorkItem(539205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539205")>
<Fact>
Public Sub ParseSingleLineIfWithNestedSingleLineIf()
' This is a valid nested line if in a line if
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If False Then If True Then Else Else Console.WriteLine(1)
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseSingleLineIfWithNestedMultiLineIf1()
' This is a single line if that contains an invalid multi line if.
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If False Then If True Console.WriteLine(1)
End Sub
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="62" end="69"/>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
End Sub
<Fact>
Public Sub ParseSingleLineIfWithNestedMultiLineIf2()
' This is a single line if that contains an invalid multi line if/then/else.
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If False Then If True Else Else Console.WriteLine(1)
End Sub
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="62" end="69"/>
<error id="30205" message="End of statement expected."/>
</errors>)
End Sub
<Fact>
Public Sub ParseSingleLineIfWithNestedMultiLineIf3()
' This is a single line if that contains an invalid multi line if.
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If true Then If True
Console.WriteLine(1)
end if
End Sub
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="61" end="68"/>
<error id="30087" message="'End If' must be preceded by a matching 'If'." start="112" end="118"/>
</errors>)
End Sub
<WorkItem(539207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539207")>
<Fact>
Public Sub ParseSingleLineIfWithNestedDoLoop1()
' This is a single line if that contains an invalid do .. loop
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If true Then do
End Sub
End Module
]]>,
<errors>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="61" end="63"/>
</errors>)
End Sub
<Fact>
Public Sub ParseSingleLineIfWithNestedDoLoop2()
' This is a single line if that contains an invalid do .. loop
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If true Then do
Console.WriteLine(1)
loop
End Sub
End Module
]]>,
<errors>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="61" end="63"/>
<error id="30091" message="'Loop' must be preceded by a matching 'Do'." start="105" end="109"/>
</errors>)
End Sub
<Fact>
Public Sub ParseSingleLineIfWithNestedDoLoop3()
' This is a single line if that contains a valid do loop
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If true Then do : Console.WriteLine(1) : loop
End Sub
End Module
]]>)
End Sub
<WorkItem(539209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539209")>
<Fact>
Public Sub ParseSingleLineSubWithSingleLineIfFollowedByColonComma()
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module Program
Sub Main()
Dim a = Sub() If True Then Dim b = 1 :, c = 2
End Sub
End Module
]]>)
End Sub
<WorkItem(539210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539210")>
<Fact>
Public Sub ParseSingleLineIfFollowedByColonNewLine()
' Per Dev10 the second WriteLine should NOT be part of
' the single line if. This regression was caused by scanner change
' to scan ":" after trivia. The scanner now scans in new statement state after
' the colon and eats up new lines.
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub Main()
If True Then Console.WriteLine(1) :
Console.WriteLine(2)
End Sub
End Module
]]>)
Dim compUnit = tree.GetRoot()
Dim moduleM = TryCast(compUnit.ChildNodesAndTokens()(0).AsNode, TypeBlockSyntax)
Dim subMain = TryCast(moduleM.ChildNodesAndTokens()(1).AsNode, MethodBlockSyntax)
Assert.Equal(4, subMain.ChildNodesAndTokens().Count)
Assert.Equal(SyntaxKind.SingleLineIfStatement, subMain.ChildNodesAndTokens()(1).Kind())
Assert.Equal(SyntaxKind.ExpressionStatement, subMain.ChildNodesAndTokens()(2).Kind())
Assert.Equal(SyntaxKind.InvocationExpression, DirectCast(subMain.ChildNodesAndTokens()(2).AsNode, ExpressionStatementSyntax).Expression.Kind)
End Sub
<Fact>
Public Sub ParseSingleLineIfFollowedByColonNewLine1()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub Main()
dim s1 = sub () If True Then Console.WriteLine(1) :
dim s2 = sub () If True Then Console.WriteLine(1) ::Console.WriteLine(1)::
dim s3 = sub() If True Then Console.WriteLine(1) :::: Console.WriteLine(1)
Console.WriteLine(2)
End Sub
End Module
]]>)
End Sub
<WorkItem(539211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539211")>
<Fact>
Public Sub ParseSingleLineSubWithSingleLineIfFollowedByComma()
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module Program
Sub Main()
Dim a = Sub() If True Then Console.WriteLine, b = 2
End Sub
End Module
]]>)
End Sub
<WorkItem(539211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539211")>
<Fact>
Public Sub ParseSingleLineSubWithSingleLineIfFollowedByParen()
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module Program
Sub Main()
Dim a = (Sub() If True Then Console.WriteLine), b = 2
End Sub
End Module
]]>)
End Sub
<WorkItem(530904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530904")>
<Fact>
Public Sub SingleLineLambdaComma()
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim a(0)
Dim b = Sub() ReDim a(1),
Return
End Sub
End Module
]]>,
<errors>
<error id="30201" message="Expression expected." start="153" end="153"/>
</errors>)
End Sub
<WorkItem(539212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539212")>
<Fact>
Public Sub ParseSingleLineSubWithSingleLineIfWithAnotherSingleLineSub()
' The second single line sub is within a var declaration after the end statement in the then clause!
Dim tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
Dim a = Sub() If True Then End _
: Dim b = Sub() If True Then End Else End Else
End Sub
End Module
]]>)
End Sub
<WorkItem(539212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539212")>
<Fact>
Public Sub ParseSingleLineSubWithIncompleteSingleLineIf()
' Dev10 reports single line if must contain one statement.
Dim tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
Dim a = Sub() If True Then
End Sub
End Module
]]>, Diagnostic(ERRID.ERR_ExpectedEndIf, "If True Then"))
End Sub
<WorkItem(539212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539212")>
<Fact>
Public Sub ParseSubLambdaWithIncompleteSingleLineIf()
' The single line if actually gets parsed as a block if in both dev10 and roslyn
Dim tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
Dim a = Sub()
If True Then
End Sub
End Module
]]>,
<errors>
<error id="30026" message="'End Sub' expected." start="18" end="28"/>
<error id="30081" message="'If' must end with a matching 'End If'." start="56" end="68"/>
</errors>)
End Sub
<WorkItem(871931, "DevDiv/Personal")>
<Fact>
Public Sub ParseErase()
ParseAndVerify(<![CDATA[
Class Class1
Public vobja() As Object
Public Sub Goo()
Erase vobja
End Sub
End Class
]]>)
End Sub
<WorkItem(872003, "DevDiv/Personal")>
<Fact>
Public Sub ParseError()
ParseAndVerify(<![CDATA[
Class Class1
Public Sub Goo()
Error 5
End Sub
End Class
]]>)
End Sub
<WorkItem(872005, "DevDiv/Personal")>
<Fact>
Public Sub ParseLabel()
ParseAndVerify(<![CDATA[
Class Class1
Public Sub Goo()
10: Dim x = 42
End Sub
End Class
]]>)
End Sub
<WorkItem(538606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538606")>
<Fact>
Public Sub LabelFollowedByMethodInvocation()
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Goo : Goo : Goo()
End Sub
Sub Goo()
End Sub
End Module
]]>)
End Sub
<WorkItem(541358, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541358")>
<Fact>
Public Sub LabelRelatedToBug8037()
ParseAndVerify(<![CDATA[
Module M
Sub Main()
#if 1 < 2
label1:
#elseif 2 < 3
label2:
#elseif false
label3:
#end if
label4:
label5:
End Sub
::
#region "goo"
Sub Goo()
End Sub
::
#end region
Sub Goo_()
End Sub
''' <summary>
''' </summary>
:Sub Goo2()
:End Sub
''' <summary>
''' </summary>
Sub Goo2_()
End Sub
:<summary()>
Sub Goo3()
:End Sub
#if false
#end if
Sub Goo4()
:
:End Sub
:' nice little innocent comment
Sub Goo5()
End Sub
#garbage on
Sub Goo6()
End Sub
#Const CustomerNumber = 36
Sub Goo7()
End Sub
End Module
]]>, <errors>
<error id="32009" message="Method declaration statements must be the first statement on a logical line." start="441" end="451"/>
<error id="32009" message="Method declaration statements must be the first statement on a logical line." start="599" end="635"/>
<error id="30248" message="'If', 'ElseIf', 'Else', 'End If', 'Const', or 'Region' expected." start="853" end="854"/>
</errors>)
' doesn't work, most probably because of the line break ...
'Diagnostic(ERRID.ERR_MethodMustBeFirstStatementOnLine, "Sub Goo2()"),
'Diagnostic(ERRID.ERR_MethodMustBeFirstStatementOnLine, "<summary()>" + vbCrLf + " Sub Goo3()"),
'Diagnostic(ERRID.ERR_ExpectedConditionalDirective, "#"))
End Sub
<WorkItem(872013, "DevDiv/Personal")>
<Fact>
Public Sub ParseMid()
ParseAndVerify(<![CDATA[
Class Class1
Public Sub Goo(ByRef r As aType)
Mid$(r.S(2, 2), 1, 1) = "-"
Mid(r.S(2, 2), 1, 1) = "-"
End Sub
End Class
]]>)
End Sub
<WorkItem(542623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542623")>
<Fact>
Public Sub ParseMidIdentifier1()
ParseAndVerify(< = 33
End Sub
Public Sub Mid(p as Integer)
End Sub
End Class
]]>, Diagnostic(ERRID.ERR_ExpectedComma, ""),
Diagnostic(ERRID.ERR_ExpectedExpression, "")
)
End Sub
<WorkItem(542623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542623")>
<Fact>
Public Sub ParseMidIdentifier2()
ParseAndVerify(<
End Sub
End Class
]]>, Diagnostic(ERRID.ERR_ExpectedComma, ""),
Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_ExpectedEQ, ""),
Diagnostic(ERRID.ERR_ExpectedExpression, "")
)
End Sub
<Fact>
Public Sub ParseMidIdentifier3()
ParseAndVerify(<
End Sub
End Class
]]>, Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_ExpectedEQ, ""),
Diagnostic(ERRID.ERR_ExpectedExpression, "")
)
End Sub
<Fact>
Public Sub ParseMidIdentifier4()
ParseAndVerify(<![CDATA[
Class Mid
Public Sub Mid(p as Integer)
Mid(23, 24,
End Sub
End Class
]]>, Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_ExpectedRparen, ""),
Diagnostic(ERRID.ERR_ExpectedEQ, ""),
Diagnostic(ERRID.ERR_ExpectedExpression, "")
)
End Sub
<WorkItem(872018, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineIfThenElse()
ParseAndVerify(<![CDATA[
Class Class1
Sub Method1()
Dim IsSA As Short
If True Then IsSA = True Else IsSA = False
End Sub
End Class
]]>)
End Sub
<WorkItem(872030, "DevDiv/Personal")>
<Fact>
Public Sub ParseRedimClauses()
ParseAndVerify(<![CDATA[
Module Module1
Function FUN1%()
Dim C21#(), C22#(,), C23#()
ReDim C21#(1), C22#(2, 1), C23#(2)
End Function
End Module
]]>)
End Sub
<WorkItem(872034, "DevDiv/Personal")>
<Fact>
Public Sub ParseForNext()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
For i = 0 To 1
For j = 0 To 1
Next j, i
End Sub
End Module
]]>)
End Sub
<WorkItem(872042, "DevDiv/Personal")>
<Fact>
Public Sub ParseWhen()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Try
Catch e As InvalidCastException When (Bln = True)
End Try
End Sub
End Module
]]>)
End Sub
<WorkItem(873525, "DevDiv/Personal")>
<Fact>
Public Sub ParseAndAlsoInOrElseArgumentList()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo(ByVal x As Boolean)
End Sub
Function Bar() As Boolean
End Function
Sub Main()
Goo(True AndAlso Bar())
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo(ByVal x As Boolean)
End Sub
Function Bar() As Boolean
End Function
Sub Main()
Goo(False OrElse Bar())
End Sub
End Module
]]>)
End Sub
<WorkItem(873526, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineIfThenWithFollowingStatement()
ParseAndVerify(<![CDATA[
Class c1
Sub goo()
If True Then goo()
bar()
End Sub
End Class
]]>)
End Sub
<WorkItem(874045, "DevDiv/Personal")>
<Fact>
Public Sub ParseEnd()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
End
End Sub
End Module
]]>)
End Sub
<WorkItem(874054, "DevDiv/Personal")>
<Fact>
Public Sub ParseForEachControlVariableArray()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim files()() As String = {New String() {"Template0.bmp", "Template0.txt"}}
For Each fs() As String In files
Next fs
End Sub
End Module
]]>)
End Sub
<WorkItem(874067, "DevDiv/Personal")>
<Fact>
Public Sub ParseQuerySelectWithInitializerFollowedByFrom()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim q = From i In {} Select p = New Object From j In {} Select j
End Sub
End Module
]]>)
End Sub
<WorkItem(874074, "DevDiv/Personal")>
<Fact>
Public Sub ParseExtensionMethodInvokeOnLiteral()
ParseAndVerify(<![CDATA[
<System.Runtime.CompilerServices.Extension()>
Module Module1
Sub Main()
Dim r = 42.IntegerExtension()
Dim r = 42.BAD
End Sub
<System.Runtime.CompilerServices.Extension()>
Function IntegerExtension(i As Integer) As Boolean
Return True
End Function
End Module
]]>)
End Sub
<WorkItem(874120, "DevDiv/Personal")>
<Fact>
Public Sub ParseDoUntilNested()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Do Until True
Do Until True
Loop
Loop
End Sub
End Module
]]>)
End Sub
<WorkItem(874355, "DevDiv/Personal")>
<Fact>
Public Sub BC31151ERR_MissingXmlEndTag_ParseLessThan()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim a = ( < 13)
End Sub
End Module
]]>,
<errors>
<error id="30198"/>
<error id="30636"/>
<error id="31165"/>
<error id="30035"/>
<error id="31169"/>
<error id="31177"/>
<error id="31151"/>
</errors>)
End Sub
<WorkItem(875188, "DevDiv/Personal")>
<Fact>
Public Sub ParseSelectCaseClauses()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim bytevar
Select Case bytevar
Case Is < 0, Is > 255
End Select
End Sub
End Module
]]>)
End Sub
<WorkItem(875194, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineContinuationWithTrailingWhitespace()
ParseAndVerify(
"Class Class1" & vbCrLf &
" <Obsolete(True)> _ " & vbTab & vbCrLf &
" Sub AnachronisticMethod()" & vbCrLf &
" End Sub" & vbCrLf &
"End Class")
End Sub
<WorkItem(879296, "DevDiv/Personal")>
<Fact>
Public Sub ParseRightShiftEquals()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim i = &H1000
i >>= 1
End Sub
End Module
]]>)
End Sub
<WorkItem(879373, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaFollowedByColon()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = Function() 3 :
End Sub
End Module
]]>)
End Sub
<WorkItem(879385, "DevDiv/Personal")>
<Fact>
Public Sub ParseQueryGroupByIntoWithXmlLiteral()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim col1 As IQueryable = Nothing
Dim q3 = From i In col1 Group el1.<moo>.@attr1, el1.<moo> By el1...<moo> Into G=Group
End Sub
End Module
]]>)
End Sub
<WorkItem(879690, "DevDiv/Personal")>
<Fact>
Public Sub ParseThrow()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Throw
End Sub
End Module
]]>)
End Sub
<WorkItem(536076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536076")>
<Fact>
Public Sub ParseQueryFromNullableRangeVariable()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim col As New Collections.ArrayList()
Dim w3 = From i? As Integer In col
End Sub
End Module
]]>)
End Sub
<WorkItem(880312, "DevDiv/Personal")>
<Fact>
Public Sub ParseEmptyMultilineFunctionLambda()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim f = Function()
End Function
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseEmptyMultilineSubLambda()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim s = Sub()
End Sub
End Sub
End Module
]]>)
End Sub
<WorkItem(881451, "DevDiv/Personal")>
<Fact>
Public Sub ParseQueryIntoAllImplicitLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim i10 = Aggregate el In coll1 Into All(
el <= 5
)
End Sub
End Module
]]>)
End Sub
<WorkItem(881528, "DevDiv/Personal")>
<Fact>
Public Sub ParseMethodInvocationNestedImplicitLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Goo(
GetType(
Integer
)
)
End Sub
End Module
]]>)
End Sub
<WorkItem(881570, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaInvokeDeclaration()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = Function()
Return 42
End Function()
End Sub
End Module
]]>)
End Sub
<WorkItem(881585, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaBodyWithLineIfForEach()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim m1, list2() As Integer
Dim x = Sub() If True Then For Each i In list2 : m1 = i : Exit Sub : Exit For : Next
End Sub
End Module
]]>)
End Sub
<WorkItem(881590, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaDeclarationCommaSeparated()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim s1 = Sub()
End Sub, s2 = Sub() End
End Sub
End Module
]]>)
End Sub
<WorkItem(881597, "DevDiv/Personal")>
<Fact>
Public Sub ParseQueryCollectionExpressionContainsLambda()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x2 = From f In {Sub() Console.WriteLine("Hello")}
Select f
End Sub
End Module
]]>)
End Sub
<WorkItem(531540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531540")>
<Fact>
Public Sub SelectCaseInLambda()
ParseAndVerify(<![CDATA[
Module Program
Sub Main(args As String())
Dim l = Function(m) Function(m3)
Dim num = 10
Select Case num
Case Is = 10
Console.WriteLine("10")
End Select
End Function
End Sub
End Module
]]>)
End Sub
<WorkItem(530633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530633")>
<Fact>
Public Sub SubImplements()
ParseAndVerify(<![CDATA[
Interface I
Property A As Action
End Interface
Class C
Implements I
Property A As Action = Sub() Implements I.A
End Class
]]>,
<errors>
<error id="30024" message="Statement is not valid inside a method." start="112" end="126"/>
</errors>)
End Sub
<WorkItem(881603, "DevDiv/Personal")>
<Fact>
Public Sub ParseTernaryIfReturningLambda()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x2 = If(True, Nothing, Sub()
Console.WriteLine("Hi")
End Sub)
End Sub
End Module
]]>)
End Sub
<WorkItem(881606, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaMethodArgument()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo(a As Action)
End Sub
Sub Main()
Goo(Sub()
Environment.ExitCode = 42
End Sub)
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo(a As Action)
End Sub
Sub Main()
Goo(Sub(c) Console.WriteLine(c))
End Sub
End Module
]]>)
End Sub
<WorkItem(881614, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineIfThenElseIfElse()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = 0
If True Then x = 1 Else If False Then x = 2 Else x = 3
End Sub
End Module
]]>)
End Sub
<WorkItem(881640, "DevDiv/Personal")>
<Fact>
Public Sub ParseBinaryIfReturningLambdaArray()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim e1 = If({Sub()
End Sub}, {})
End Sub
End Module
]]>)
End Sub
<WorkItem(881826, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaDeclareMultipleCommaSeparated()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim m = Sub(ByRef x As String, _
y As Integer) Console.WriteLine(x & y), k = Sub(y, _
x) m(y, x), _
l = Sub(x) _
Console.WriteLine(x)
End Sub
End Module
]]>)
End Sub
<WorkItem(881827, "DevDiv/Personal")>
<Fact>
Public Sub ParseGenericNoTypeArgsImplicitLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = GetType(Action(Of
)
)
End Sub
End Module
]]>)
End Sub
<WorkItem(882391, "DevDiv/Personal")>
<Fact>
Public Sub ParseRightShiftLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = 4 >> _
1
End Sub
End Module
]]>)
End Sub
<WorkItem(882801, "DevDiv/Personal")>
<Fact>
Public Sub ParseObjectInitializerParenthesizedLambda()
ParseAndVerify(<![CDATA[
Class Class1
Sub Test()
Dim e = New With {.f = New Action(Of Integer)(Sub() If True Then Stop)}
Dim g = 3
End Sub
End Class
]]>)
End Sub
<WorkItem(883286, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaSingleLineWithFollowingStatements()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = Sub() Main()
Main()
End Sub
End Module
]]>)
End Sub
<WorkItem(882934, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaSingleLineIfInsideIfBlock()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
If True Then
Dim x = 0
Dim d = Sub() If True Then x = 1 Else x = 2
End If
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseLambdaSingleLineIfWithColon()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() If True Then :
End Sub
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() If True Then : End If
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
End Sub
<WorkItem(546693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546693")>
<Fact()>
Public Sub ParseLambdaSingleLineIfWithColonElseIfInsideIfBlock_1()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() If True Then Return : ElseIf
Else
End If
End Sub
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
<error id="30201" message="Expression expected."/>
</errors>)
End Sub
<WorkItem(546693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546693")>
<Fact()>
Public Sub ParseLambdaSingleLineIfWithColonElseIfInsideIfBlock_2()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() If True Then Return : ElseIf False Then
End If
End Sub
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
End Sub
<Fact()>
Public Sub ParseLambdaSingleLineIfWithColonElseInsideIfBlock()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() If True Then Return : Else
End If
End Sub
End Module
]]>)
End Sub
<Fact()>
Public Sub ParseLambdaSingleLineIfWithColonElseSpaceIfInsideIfBlock()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() If True Then Return : Else If False Then Return
End If
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseLambdaSingleLineIfWithStatementColon()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() If True Then M() :
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseLambdaSingleLineIfWithStatementColonElse()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() If True Then M() : Else
End Sub
End Module
]]>)
End Sub
<WorkItem(530940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530940")>
<Fact()>
Public Sub ParseSingleLineIfColon()
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then Return : Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then Return : Return Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then M() : M() Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then Return : _
Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then Return : _
Return Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then M() : _
M() Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
Return Else
End Sub
End Module
]]>,
<errors>
<error id="30205"/>
</errors>)
End Sub
<WorkItem(601004, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601004")>
<Fact()>
Public Sub ParseSingleLineIfEmptyElse()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return Else
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Return Else
End Sub
End Module
]]>)
End Sub
''' <summary>
''' EmptyStatement following colon.
''' </summary>
<WorkItem(530966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530966")>
<Fact()>
Public Sub ParseEmptyStatementFollowingColon()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
M() :
If True Then Else M1() :
If True Then Else : M2()
If True Then Else :
10:
20::
30: M3()
L4: M4():
L5: : M5()
End Sub
End Module
]]>)
Dim root = tree.GetRoot()
' If/Else statement lists should not contain EmptyToken.
Dim tokens = root.DescendantTokens().Select(Function(t) t.Kind).ToArray()
CheckArray(tokens,
SyntaxKind.ModuleKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.SubKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.EmptyToken,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.IntegerLiteralToken,
SyntaxKind.ColonToken,
SyntaxKind.IntegerLiteralToken,
SyntaxKind.ColonToken,
SyntaxKind.IntegerLiteralToken,
SyntaxKind.ColonToken,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IdentifierToken,
SyntaxKind.ColonToken,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IdentifierToken,
SyntaxKind.ColonToken,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.EndKeyword,
SyntaxKind.SubKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.ModuleKeyword,
SyntaxKind.EndOfFileToken)
End Sub
<WorkItem(531486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531486")>
<Fact()>
Public Sub ParseSingleLineIfElse()
ParseAndVerify(<![CDATA[
Module Program
Sub Main()
Dim x = Sub() If True Then ElseIf False Then
End Sub
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="66" end="82"/>
</errors>)
End Sub
<WorkItem(546910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546910")>
<Fact()>
Public Sub ParseMultiLineIfLambdaWithStatementColonElse()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() M() : Else
End If
End Sub
End Module
]]>,
<errors>
<error id="36918"/>
</errors>)
End Sub
<WorkItem(546910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546910")>
<Fact()>
Public Sub ParseSingleLineIfLambdaWithStatementColonElse()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Dim x = Sub() M() : Else
End Sub
End Module
]]>,
<errors>
<error id="36918"/>
</errors>)
End Sub
<WorkItem(882943, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaExitFunction()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim f = Function()
Exit Function
End Function
End Sub
End Module
]]>)
End Sub
<WorkItem(883063, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaSingleLineIfInPreprocessorIf()
ParseAndVerify(<![CDATA[
Class Class1
#If True Then
Dim x = 0
Dim y = Sub() If True Then x = 1 : x = 2
#End If
End Class
]]>)
End Sub
<WorkItem(883204, "DevDiv/Personal")>
<Fact>
Public Sub ParseQueryLetLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x11 = From i In (<e e="v"></e>.<e>) Let j = i.@e _
Select j
End Sub
End Module
]]>)
End Sub
<WorkItem(883646, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaCallsEndInArrayInitializer()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim f = {Sub() End}
End Sub
End Module
]]>)
End Sub
<WorkItem(883726, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaNestedCall()
ParseAndVerify(<![CDATA[
Class Class1
Function Goo()
Dim x = Sub() Call Sub()
Console.WriteLine("hi")
End Sub
Return True
End Function
End Class
]]>)
End Sub
<WorkItem(895166, "DevDiv/Personal")>
<Fact>
Public Sub ParseCommentWithDoubleTicks()
ParseAndVerify(<![CDATA[
''string
]]>)
End Sub
'Parse a nested line if with an else clause. Else should associate with nearest if.
<WorkItem(895059, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineIfWithNestedLineIfAndElse()
ParseAndVerify(<![CDATA[
Class C
Sub s
If o1 Then If o2 Then X = 1 Else X = 2
End Sub
End Class
]]>)
End Sub
<Fact>
Public Sub ParseOneLineStatement()
Dim str = " Dim x = 3 "
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind)
End Sub
<Fact>
Public Sub ParseEndSubStatement()
Dim str = "End Sub "
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(True, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.EndSubStatement, statement.Kind)
End Sub
<Fact>
Public Sub ParseEndClassStatement()
Dim str = "End Class "
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(True, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.EndClassStatement, statement.Kind)
End Sub
<Fact>
Public Sub ParseEmptyStatement()
Dim str = ""
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.EmptyStatement, statement.Kind)
str = " "
statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.EmptyStatement, statement.Kind)
str = " " & vbCrLf & vbCrLf
statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.EmptyStatement, statement.Kind)
End Sub
<Fact>
Public Sub ParseMultiLineStatement()
Dim str =
<Q>
For i as integer = 1 to 10
While true
End While
Next
</Q>.Value
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.ForBlock, statement.Kind)
End Sub
<Fact>
Public Sub Parse2MultiLineStatement01()
Dim str =
<Q>
For i as integer = 1 to 10
While true
End While
Next
While true
End While
</Q>.Value
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(True, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.ForBlock, statement.Kind)
End Sub
<Fact>
Public Sub Parse2MultiLineStatement02()
Dim str =
<Q>
For i as integer = 1 to 10
While true
End While
Next
While true
End While
</Q>.Value
Dim statement = SyntaxFactory.ParseExecutableStatement(str, consumeFullText:=False)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.ForBlock, statement.Kind)
End Sub
<Fact>
Public Sub ParseBadMultiLineStatement()
Dim str =
<Q>
For i as integer = 1 to 10
While true
End Sub
Next
While true
End While
</Q>.Value
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(True, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.ForBlock, statement.Kind)
End Sub
<WorkItem(537169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537169")>
<Fact>
Public Sub ParseGettypeNextString()
ParseAndVerify(<![CDATA[Next.goo(GetType(Func(Of A))), "")]]>,
Diagnostic(ERRID.ERR_NextNoMatchingFor, "Next.goo(GetType(Func(Of A))), """""),
Diagnostic(ERRID.ERR_ExtraNextVariable, ".goo(GetType(Func(Of A)))"))
End Sub
<WorkItem(538515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538515")>
<Fact>
Public Sub IncParseAGPower17()
Dim code As String = (<![CDATA[
Namespace AGPower17
Friend Module AGPower17mod
Sub AGPower17()
Scen242358()
Scen242359()
End Sub
Public Sub Scen242200()
Dim varLeftUInt16242200 As UInt16 = 126US
Dim varRightByteEnumAlt242200 As ByteEnumAlt = ByteEnumAlt.e1
Dim varObjLeftUInt16242200 As Object = 126US
Dim varObjRightByteEnumAlt242200 As Object = ByteEnumAlt.e1
End Sub
Public sub Scen242358()
dim varLeftUInt16242358 as UInt16 = 127US
dim varRightUlongEnumAlt242358 as UlongEnumAlt = ULongEnumAlt.e2
Dim varObjLeftUInt16242358 As Object = 127US
dim varObjRightUlongEnumAlt242358 as object = ULongEnumAlt.e2
End Sub
Public sub Scen242359()
dim varLeftUInt16242359 as UInt16 = 127US
dim varRightUlongEnumAlt242359 as UlongEnumAlt = ULongEnumAlt.e3
Dim varObjLeftUInt16242359 As Object = 127US
dim varObjRightUlongEnumAlt242359 as object = ULongEnumAlt.e3
End Sub
Enum ByteEnumAlt As Byte
e1
e2
e3
End Enum
Enum UlongEnumAlt As ULong
e1
e2
e3
End Enum
End Module
End Namespace
]]>).Value
ParseAndVerify(code)
End Sub
<WorkItem(539055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539055")>
<Fact>
Public Sub ParseReturnFollowedByComma()
ParseAndVerify(<![CDATA[
Module Module1
Dim x = Sub() Return, r = 42
End Module
]]>)
End Sub
<WorkItem(538443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538443")>
<Fact>
Public Sub ParseMultiIfThenElseOnOneLine()
ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If True Then : Else Console.WriteLine() : End If
dim x = sub ()
If True Then : Else Console.WriteLine() : End If
end sub
End Sub
End Module
]]>)
End Sub
<WorkItem(538440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538440")>
<Fact>
Public Sub ParseSingleIfElseTerminatedByColon()
Dim t = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If True Then Console.WriteLine(1) Else Console.WriteLine(2) : Console.WriteLine(3)
'Colon after the else terminates the line if
If True Then Console.WriteLine(4) Else : Console.WriteLine(5)
End Sub
End Module
]]>)
Dim moduleBlock = t.GetRoot().ChildNodesAndTokens()(1)
Dim mainBlock = moduleBlock.ChildNodesAndTokens()(1)
Dim if1 = mainBlock.ChildNodesAndTokens()(1)
Dim if2 = mainBlock.ChildNodesAndTokens()(2)
Dim wl5 = mainBlock.ChildNodesAndTokens()(3)
Assert.Equal(5, mainBlock.ChildNodesAndTokens().Count)
Assert.Equal(SyntaxKind.SingleLineIfStatement, if1.Kind())
Assert.Equal(SyntaxKind.SingleLineIfStatement, if2.Kind())
Assert.Equal(SyntaxKind.ExpressionStatement, wl5.Kind())
Assert.Equal(SyntaxKind.InvocationExpression, DirectCast(wl5.AsNode, ExpressionStatementSyntax).Expression.Kind)
End Sub
<WorkItem(4784, "DevDiv_Projects/Roslyn")>
<Fact>
Public Sub ParseSingleLineSubFollowedByComma()
Dim t = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
session.Raise(Sub(sess) AddHandler sess.SelectedSignatureChanged, Sub(s, e) Return, New SelectedSignatureChangedEventArgs(Nothing, bestMatch))
End Sub
End Module
]]>)
End Sub
<WorkItem(538481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538481")>
<Fact>
Public Sub ParseLineContAtEnd()
Dim t = ParseAndVerify(<![CDATA[
Module M
End Module
_]]>)
End Sub
<Fact>
Public Sub ParseHandlerStatements()
Dim t = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
dim button1 = new Button()
AddHandler Button1.Click, addressof Button1_Click
RemoveHandler Button1.Click, addressof Button1_Click
End Sub
End Module
]]>)
Dim moduleBlock = t.GetRoot().ChildNodesAndTokens()(1)
Dim mainBlock = moduleBlock.ChildNodesAndTokens()(1)
Dim ah = mainBlock.ChildNodesAndTokens()(2)
Dim rh = mainBlock.ChildNodesAndTokens()(3)
Assert.Equal(ah.Kind(), SyntaxKind.AddHandlerStatement)
Assert.Equal(rh.Kind(), SyntaxKind.RemoveHandlerStatement)
End Sub
<Fact>
Public Sub Regression5150()
Dim code = <String>Module Program
Sub Main()
If True Then : Dim x = Sub() If True Then Dim y :
ElseIf True Then
Console.WriteLine()
End If
End Sub
End Module
</String>.Value
Dim compilation = SyntaxFactory.ParseCompilationUnit(code)
Assert.False(compilation.ContainsDiagnostics)
Dim ifBlock =
CType(CType(CType(compilation.Members(0), TypeBlockSyntax).Members(0), MethodBlockSyntax).Statements(0), MultiLineIfBlockSyntax)
Assert.Equal(1, ifBlock.ElseIfBlocks.Count)
Dim statements = ifBlock.ElseIfBlocks(0).Statements
Assert.Equal(1, statements.Count)
Assert.IsType(Of ExpressionStatementSyntax)(statements(0))
Assert.IsType(Of InvocationExpressionSyntax)(DirectCast(statements(0), ExpressionStatementSyntax).Expression)
Assert.Equal(1, ifBlock.Statements.Count)
Assert.IsType(Of LocalDeclarationStatementSyntax)(ifBlock.Statements(0))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Regression5150WithStaticLocal()
Dim code = <String>Module Program
Sub Main()
If True Then : Static x = Sub() If True Then Static y :
ElseIf True Then
Console.WriteLine()
End If
End Sub
End Module
</String>.Value
Dim compilation = SyntaxFactory.ParseCompilationUnit(code)
Assert.False(compilation.ContainsDiagnostics)
Dim ifBlock =
CType(CType(CType(compilation.Members(0), TypeBlockSyntax).Members(0), MethodBlockSyntax).Statements(0), MultiLineIfBlockSyntax)
Assert.Equal(1, ifBlock.ElseIfBlocks.Count)
Dim statements = ifBlock.ElseIfBlocks(0).Statements
Assert.Equal(1, statements.Count)
Assert.IsType(Of ExpressionStatementSyntax)(statements(0))
Assert.IsType(Of InvocationExpressionSyntax)(DirectCast(statements(0), ExpressionStatementSyntax).Expression)
Assert.Equal(1, ifBlock.Statements.Count)
Assert.IsType(Of LocalDeclarationStatementSyntax)(ifBlock.Statements(0))
End Sub
<WorkItem(540669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540669")>
<Fact>
Public Sub SingleLineIfNotTerminateByEmptyStatement()
' Verify that "::" in the else of a single line if does not terminate the single line if.
' The else contains a call, empty statement and the second single line if.
Dim code = <String>
Module Module1
Sub Main()
If True Then Goo(1) Else Goo(2) :: If True Then Goo(3) Else Goo(4) : Goo(5)
End Sub
Private Sub Goo(i As Integer)
Console.WriteLine(i)
End Sub
End Module
</String>.Value
Dim compilation = SyntaxFactory.ParseCompilationUnit(code)
Assert.False(compilation.ContainsDiagnostics)
Dim singleLineIf =
CType(CType(CType(compilation.Members(0), TypeBlockSyntax).Members(0), MethodBlockSyntax).Statements(0), SingleLineIfStatementSyntax)
Dim statements = singleLineIf.ElseClause.Statements
Assert.Equal(2, statements.Count)
Assert.IsType(Of ExpressionStatementSyntax)(statements(0))
Assert.IsType(Of InvocationExpressionSyntax)(DirectCast(statements(0), ExpressionStatementSyntax).Expression)
Assert.IsType(Of SingleLineIfStatementSyntax)(singleLineIf.ElseClause.Statements(1))
End Sub
<WorkItem(540844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540844")>
<Fact>
Public Sub TestForEachAfterOffset()
Const prefix As String = "GARBAGE"
Dim forEachText = <![CDATA['A for each statement
for each a in b
next
]]>.Value
Dim leading = SyntaxFactory.ParseLeadingTrivia(prefix + forEachText, offset:=prefix.Length)
Assert.Equal(3, leading.Count)
Assert.Equal(SyntaxKind.CommentTrivia, leading(0).Kind)
Assert.Equal(SyntaxKind.EndOfLineTrivia, leading(1).Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, leading(2).Kind)
Dim trailing = SyntaxFactory.ParseTrailingTrivia(prefix + forEachText, offset:=prefix.Length)
Assert.Equal(2, trailing.Count)
Assert.Equal(SyntaxKind.CommentTrivia, trailing(0).Kind)
Assert.Equal(SyntaxKind.EndOfLineTrivia, trailing(1).Kind)
Dim t = SyntaxFactory.ParseToken(prefix + forEachText, offset:=prefix.Length, startStatement:=True)
Assert.Equal(SyntaxKind.ForKeyword, t.Kind)
Dim tokens = SyntaxFactory.ParseTokens(prefix + forEachText, offset:=prefix.Length)
Assert.Equal(9, tokens.Count)
Assert.Equal(SyntaxKind.NextKeyword, tokens(6).Kind)
Dim statement = SyntaxFactory.ParseExecutableStatement(prefix + forEachText, offset:=prefix.Length)
Assert.NotNull(statement)
Assert.Equal(SyntaxKind.ForEachBlock, statement.Kind)
Assert.Equal(False, statement.ContainsDiagnostics)
End Sub
<WorkItem(543248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543248")>
<Fact()>
Public Sub ParseBadCollectionRangeVariableDeclaration1()
ParseAndVerify(<![CDATA[
Imports System
Class Program
Shared Sub Main(args As String())
Dim x = From y As Char i, In String.Empty
End Sub
End Class
]]>, Diagnostic(ERRID.ERR_ExpectedIn, ""),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "In"),
Diagnostic(ERRID.ERR_ExpectedIn, ""))
End Sub
<WorkItem(543364, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543364")>
<Fact()>
Public Sub ParseLabelAfterElse()
ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If False Then
Else 100:
End If
End Sub
End Module]]>, Diagnostic(ERRID.ERR_Syntax, "100"))
End Sub
<WorkItem(544224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544224")>
<Fact()>
Public Sub ParsePartialSingleLineIfStatement()
Dim stmt = SyntaxFactory.ParseExecutableStatement("If True")
Assert.Equal(stmt.Kind, SyntaxKind.MultiLineIfBlock)
Assert.True(stmt.HasErrors)
stmt = SyntaxFactory.ParseExecutableStatement("If True then goo()")
Assert.Equal(stmt.Kind, SyntaxKind.SingleLineIfStatement)
Assert.False(stmt.HasErrors)
End Sub
#Region "Error Test"
<Fact()>
Public Sub BC30003ERR_MissingNext_ParseOnErrorResume()
ParseAndVerify(<![CDATA[
Module Module1
Sub s1()
on error resume
on error resume next
end sub
End Module
]]>,
<errors>
<error id="30003"/>
</errors>)
End Sub
<WorkItem(536260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536260")>
<Fact()>
Public Sub BC30012ERR_LbExpectedEndIf()
ParseAndVerify(<![CDATA[
Module Module1
#If True Then
Dim d = <aoeu>
#End If
</aoeu>
End Module
]]>,
<errors>
<error id="30012"/>
</errors>)
End Sub
<WorkItem(527095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527095")>
<Fact()>
Public Sub BC30016ERR_InvOutsideProc_Label()
ParseAndVerify(<![CDATA[
Module Module1
3
End Module
Module Module2
Goo:
End Module
]]>,
<errors>
<error id="30801"/>
<error id="30016"/>
<error id="30016"/>
</errors>)
End Sub
<WorkItem(874301, "DevDiv/Personal")>
<Fact()>
Public Sub BC30024ERR_InvInsideProc_Option()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Option Explicit On
End Sub
End Module
]]>,
<errors>
<error id="30024"/>
</errors>)
End Sub
<WorkItem(1531, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub BC30035ERR_Syntax_ParseErrorPrecededByComment()
ParseAndVerify(<![CDATA[Module M1
Sub Goo
'this is a
'long
'comment
(1).ToString
End Sub
End Module]]>,
<errors>
<error id="30035" message="Syntax error." start="45" end="46"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30058ERR_ExpectedCase()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
select i
dim j = false
case 0
case 1
case 2
case else
end select
end sub
End Module
]]>,
<errors>
<error id="30058"/>
</errors>)
' ERRID.ERR_ExpectedCase
End Sub
<WorkItem(926761, "DevDiv/Personal")>
<Fact()>
Public Sub BC30071ERR_CaseElseNoSelect()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Case Else
End Sub
End Module
]]>,
<errors>
<error id="30071"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30072ERR_CaseNoSelect()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
case 0
end sub
End Module
]]>,
<errors>
<error id="30072"/>
</errors>)
' ERRID.ERR_CaseNoSelect
End Sub
'Parse a nested line if with a block if (if is followed by eol)
<Fact()>
Public Sub BC30081ERR_ExpectedEndIf_ParseNestedLineIfWithBlockIf()
ParseAndVerify(<![CDATA[
Class C
Sub s
If o1 Then If o2
End Sub
End Class
]]>,
<errors>
<error id="30081"/>
</errors>)
End Sub
<WorkItem(878016, "DevDiv/Personal")>
<Fact()>
Public Sub BC30084ERR_ExpectedNext_For()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
For i = 1 To 10
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
</errors>)
End Sub
<WorkItem(887521, "DevDiv/Personal")>
<Fact()>
Public Sub BC30084ERR_ExpectedNext_ParseErrorCatchClosesForBlock()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
Try
For u = 0 To 2 Step 1
For i = 0 To 2 Step 1
Next
Catch
Finally
End Try
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
</errors>)
End Sub
<WorkItem(874308, "DevDiv/Personal")>
<WorkItem(879764, "DevDiv/Personal")>
<Fact()>
Public Sub BC30086ERR_ElseNoMatchingIf()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Else
End Sub
End Module
]]>,
<errors>
<error id="30086"/>
</errors>)
End Sub
<WorkItem(875150, "DevDiv/Personal")>
<Fact()>
Public Sub BC30089ERR_ObsoleteWhileWend()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
While True
Wend
End Sub
End Module
]]>,
<errors>
<error id="30809"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30091ERR_LoopNoMatchingDo_ParseDoWithErrors()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
loop
do while true
loop until true
do goo
loop
do
end sub
End Module
]]>,
<errors>
<error id="30091"/>
<error id="30238"/>
<error id="30035"/>
<error id="30083"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30095ERR_ExpectedEndSelect()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
if true then
select i
case 0
case 1
case 2
end if
end sub
End Module
]]>,
<errors>
<error id="30095"/>
</errors>)
' ERRID.ERR_ExpectedEndSelect
End Sub
<WorkItem(877929, "DevDiv/Personal")>
<Fact()>
Public Sub BC30198ERR_ExpectedRparen_If()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
If(1,2)
End If
End Sub
End Module
]]>)
End Sub
<WorkItem(884863, "DevDiv/Personal")>
<Fact()>
Public Sub BC30199ERR_ExpectedLparen_ParseWrongNameUsedForOperatorToBeOverloadedErrors()
ParseAndVerify(<![CDATA[
Class c3
'COMPILEERROR: BC30199, "\\"
shared Operator /\(ByVal x As c3, ByVal y As c3) As Boolean
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
</errors>)
End Sub
<WorkItem(885650, "DevDiv/Personal")>
<Fact()>
Public Sub BC30203ERR_ExpectedIdentifier()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
With New Object
.
End With
End Sub
End Module
]]>,
<errors>
<error id="30203"/>
</errors>)
End Sub
'Parse a line if followed by dangling elseif
<Fact()>
Public Sub BC30205ERR_ExpectedEOS_ParseLineIfDanglingElseIf()
ParseAndVerify(<![CDATA[
class c
sub goo()
if true then elseif
end sub
end class
]]>,
<errors>
<error id="30205" message="End of statement expected." start="68" end="74"/>
<error id="30201" message="Expression expected." start="74" end="74"/>
</errors>)
End Sub
<WorkItem(885705, "DevDiv/Personal")>
<Fact()>
Public Sub BC30205ERR_ExpectedEOS_MismatchExpectedEOSVSSyntax()
ParseAndVerify(<![CDATA[
Class Class1
Delegate Sub del()
Public Custom Event e As del
AddHandler(ByVal value As del) as Integer
End AddHandler
RemoveHandler(ByVal value As del) as Integer
End RemoveHandler
RaiseEvent() as Integer
End RaiseEvent
End Event
End Class
]]>,
<errors>
<error id="30205"/>
<error id="30205"/>
<error id="30205"/>
</errors>)
End Sub
<WorkItem(879284, "DevDiv/Personal")>
<Fact()>
Public Sub BC30239ERR_ExpectedRelational_ParseLeftShift()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x
x=4 <>>< 2
'Comment
x = Class1 << 4
End Sub
End Module
]]>,
<errors>
<error id="30201"/>
<error id="30239"/>
</errors>)
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x
x=4 <>>< 2
'COMPILEERROR: BC30108, "Class1"
x = Class1 << 4
End Sub
End Module
]]>,
<errors>
<error id="30201"/>
<error id="30239"/>
</errors>)
End Sub
<WorkItem(875155, "DevDiv/Personal")>
<Fact()>
Public Sub BC30249ERR_ExpectedEQ_ParseFor()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
for x,y as Integer = 1 to 100
Next
End Sub
End Module
]]>,
<errors>
<error id="30249"/>
<error id="30035"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30289ERR_InvInsideEndsProc_ParseSingleLineLambdaWithClass()
ParseAndVerify(<![CDATA[
Module M1
Sub Goo()
Try
Dim x1 = Sub(y) Class C
End Try
End Sub
End Module
]]>,
<errors>
<error id="30289"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30321ERR_CaseAfterCaseElse()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
select i
case 0
case 1
case 2
case else
case 3
end select
end sub
End Module
]]>,
<errors>
<error id="30321"/>
</errors>)
' ERRID.ERR_CaseAfterCaseElse
End Sub
<Fact()>
Public Sub BC30379ERR_CatchAfterFinally()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
try
catch
finally
catch
end try
end sub
End Module
]]>,
<errors>
<error id="30379"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30381ERR_FinallyAfterFinally()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
try
catch
finally
finally
end try
end sub
End Module
]]>,
<errors>
<error id="30381"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30384ERR_ExpectedEndTry()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
try
catch
finally
end sub
End Module
]]>,
<errors>
<error id="30384"/>
</errors>)
End Sub
<WorkItem(904911, "DevDiv/Personal")>
<Fact()>
Public Sub BC30384ERR_ExpectedEndTry_ParseNestedIncompleteTryBlocks()
ParseAndVerify(<![CDATA[Namespace n1
Module m1
Public Sub bar()
Try
Try
'Catch ex As Exception
'End Try
Catch ex As Exception
End Try
End Sub
End Module
End Namespace
]]>,
<errors>
<error id="30384"/>
</errors>)
End Sub
<WorkItem(899235, "DevDiv/Personal")>
<Fact()>
Public Sub BC30429ERR_InvalidEndSub_ParseLambdaWithEndSubInsideTryBlock()
ParseAndVerify(<![CDATA[
Module M1
Sub Goo()
Try
Dim x1 = Sub(y) End Sub
End Try
End Sub
End Module
]]>,
<errors>
<error id="30429"/>
</errors>)
End Sub
<WorkItem(904910, "DevDiv/Personal")>
<Fact()>
Public Sub BC30370ERR_ExpectedRbrace_CollectionInitializer()
ParseAndVerify(<![CDATA[Module Module1
Sub Main()
Dim b1c = {1"", 2, 3}
End Sub
End Module]]>,
<errors>
<error id="30370"/>
</errors>)
End Sub
<WorkItem(880374, "DevDiv/Personal")>
<Fact()>
Public Sub BC30670ERR_RedimNoSizes()
' NOTE: the test has been changed to check for NO ERROR because error 30670
' was moved from parser to initial binding phase
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim Obj()
ReDim Obj
ReDim Obj()
End Sub
End Module
]]>)
End Sub
<Fact()>
Public Sub BC30670ERR_RedimNoSizes_02()
' NOTE: the test has been changed to only check for error 30205 because error 30670
' was moved from parser to initial binding phase
ParseAndVerify(<![CDATA[
class c1
sub s
redim a 1 + 2 'Dev 10 reports 30205
end sub
end class
]]>,
<errors>
<error id="30205"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30781ERR_ExpectedContinueKind()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
do
continue
loop
while true
continue
end while
for i = 0 to 10
continue
next
end sub
End Module
]]>,
<errors>
<error id="30781"/>
<error id="30781"/>
<error id="30781"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30800ERR_ObsoleteArgumentsNeedParens()
ParseAndVerify(<![CDATA[
class c1
sub s
i 1,2
end sub
end class
]]>,
<errors>
<error id="30800"/>
</errors>)
End Sub
<WorkItem(880397, "DevDiv/Personal")>
<Fact()>
Public Sub BC30801ERR_ObsoleteLineNumbersAreLabels_LambdaLineTerminator()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim s1a = Function () : 1 + x
End Sub
End Module
]]>,
<errors>
<error id="30201"/>
<error id="30035"/>
</errors>
)
End Sub
<Fact()>
Public Sub BC30807ERR_ObsoleteLetSetNotNeeded()
ParseAndVerify(<![CDATA[
class c1
sub s
let i = 0
set j = i
end sub
end class
]]>,
<errors>
<error id="30807"/>
<error id="30807"/>
</errors>)
End Sub
<WorkItem(875171, "DevDiv/Personal")>
<Fact()>
Public Sub BC30814ERR_ObsoleteGosub()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
GoSub 1000
1000:
End Sub
End Module
]]>,
<errors>
<error id="30814"/>
</errors>)
End Sub
<WorkItem(873634, "DevDiv/Personal")>
<Fact()>
Public Sub BC30924ERR_NoConstituentArraySizes_ParseArrayInitializer()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim FixedRankArray As Short()
FixedRankArray = New Short() ({1, 2})
End Sub
End Module
]]>,
<errors>
<error id="30987"/>
<error id="32014"/>
</errors>)
End Sub
<WorkItem(885229, "DevDiv/Personal")>
<Fact()>
Public Sub BC31135ERR_SpecifiersInvOnEventMethod_AddHandler()
ParseAndVerify(<![CDATA[
Class Cls
Friend Delegate Sub EH(ByRef x As Integer)
Custom Event e1 As EH
MustOverride AddHandler(ByVal value As EH)
End AddHandler
RemoveHandler(ByVal value As EH)
End RemoveHandler
RaiseEvent(ByRef x As Integer)
End RaiseEvent
End Event
End Class
]]>,
<errors>
<error id="31135"/>
</errors>)
End Sub
<WorkItem(885655, "DevDiv/Personal")>
<Fact()>
Public Sub BC31395ERR_NoTypecharInLabel()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Label$:
End Sub
End Module
]]>,
<errors>
<error id="31395"/>
</errors>)
End Sub
<WorkItem(917, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub BC31427ERR_BadCCExpression_ConditionalCompilationExpr()
ParseAndVerify(<![CDATA[
Class Class1
#If 1 like Nothing Then
#End If
End Class
]]>,
<errors>
<error id="31427"/>
</errors>)
End Sub
<WorkItem(527019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527019")>
<Fact()>
Public Sub BC31427ERR_BadCCExpression_ParseErrorMismatchExpectedEOSVSBadCCExpressionExpected()
ParseAndVerify(<![CDATA[
Class Class1
'COMPILEERROR: BC31427, "global"
#if global.ns1 then
#End If
End Class
]]>,
<errors>
<error id="31427"/>
</errors>)
End Sub
<WorkItem(536271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536271")>
<Fact()>
Public Sub BC32020ERR_ExpectedAssignmentOperator()
ParseAndVerify(<![CDATA[
Module Module1
Dim ele As XElement = <e/>
Sub Main()
ele.@h = From i in New String(){"a", "b","c"} let ele.@h = i
End Sub
End Module
]]>,
<errors>
<error id="32020"/>
</errors>)
End Sub
<WorkItem(879334, "DevDiv/Personal")>
<Fact()>
Public Sub BC32065ERR_GenericParamsOnInvalidMember_Lambda()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = Function(Of T)(x As T) x
End Sub
End Module
]]>,
<errors>
<error id="32065"/>
</errors>)
End Sub
<WorkItem(881553, "DevDiv/Personal")>
<Fact()>
Public Sub BC32093ERR_OfExpected_ParseGenericTypeInstantiation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim c1 As New Class1(String)()
End Sub
End Module
]]>,
<errors>
<error id="32093"/>
</errors>)
End Sub
<WorkItem(877226, "DevDiv/Personal")>
<WorkItem(881641, "DevDiv/Personal")>
<Fact()>
Public Sub BC33104ERR_IllegalOperandInIIFCount()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x1 = If()
Dim x2 = If(True)
Dim x3 = If(True, False, True, False)
End Sub
End Module
]]>,
<errors>
<error id="33104"/>
<error id="33104"/>
<error id="33104"/>
</errors>)
End Sub
<WorkItem(883303, "DevDiv/Personal")>
<Fact()>
Public Sub BC33105ERR_IllegalOperandInIIFName_TernaryIf()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim s2_a = If(Expression:=True, truepart:=1, falsepart:=2)
End Sub
End Module
]]>,
<errors>
<error id="33105"/>
<error id="33105"/>
<error id="33105"/>
</errors>)
End Sub
<WorkItem(875159, "DevDiv/Personal")>
<Fact()>
Public Sub BC36005ERR_ElseIfNoMatchingIf()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
If True Then
Else
elseif
End If
End Sub
End Module
]]>,
<errors>
<error id="36005"/>
<error id="30201"/>
</errors>)
End Sub
<WorkItem(875202, "DevDiv/Personal")>
<Fact()>
Public Sub BC36607ERR_ExpectedIn_ParseForEachControlVariable()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
For each x() as Integer {1,2,3} in New Integer()() {New Integer(){1,2}
Next
End Sub
End Module
]]>,
<errors>
<error id="30035"/>
<error id="36607"/>
</errors>)
End Sub
<Fact()>
Public Sub BC36008ERR_ExpectedEndUsing()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
using e0
end sub
End Module
]]>,
<errors>
<error id="36008"/>
</errors>)
End Sub
<WorkItem(880150, "DevDiv/Personal")>
<Fact()>
Public Sub BC36620ERR_ExpectedAnd_ParseQueryJoinConditionAndAlso()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim q4 = From i In col1 Join j In col1 On i Equals j AndAlso i Equals j
End Sub
End Module
]]>,
<errors>
<error id="36620"/>
</errors>)
End Sub
<WorkItem(881620, "DevDiv/Personal")>
<Fact()>
Public Sub BC36620ERR_ExpectedAnd_ParseQueryJoinOnOr()
ParseAndVerify(<![CDATA[
Module JoinOnInvalid
Sub JoinOnInvalid()
Dim col1 As IQueryable
Dim q3 = From i In col1 Join j In col1 On i Equals j OR i Equals j
End Sub
End Module
]]>,
<errors>
<error id="36620"/>
</errors>)
End Sub
<WorkItem(527028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527028")>
<Fact()>
Public Sub BC36631ERR_ExpectedJoin()
ParseAndVerify(<![CDATA[
Class Class1
Dim l = From pers In {1, 2}
Group
Join pet In {3, 4} On pers Equals pet Into PetList = Group
End Class
]]>,
<errors>
<error id="36605"/>
<error id="36615"/>
</errors>)
End Sub
<WorkItem(904984, "DevDiv/Personal")>
<Fact()>
Public Sub BC36668ERR_MultilineLambdasCannotContainOnError()
' Note, the BC36668 is now reported during binding.
ParseAndVerify(<![CDATA[
Module M1
Dim a = Sub()
On Error Resume Next
End Sub
Dim b = Sub() On Error GoTo 1
Dim c = Function()
Resume
End Function
End Module
]]>)
End Sub
<WorkItem(880300, "DevDiv/Personal")>
<Fact()>
Public Sub BC36672ERR_StaticInLambda()
' Roslyn reports this error during binding.
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim y = Sub()
Static a As Integer = 2
End Sub
End Sub
End Module
]]>)
End Sub
<WorkItem(884259, "DevDiv/Personal")>
<Fact()>
Public Sub BC36673ERR_MultilineLambdaMissingSub()
ParseAndVerify(<![CDATA[
Module M1
Sub Goo()
If True Then
'COMPILEERROR : BC36673, "Sub()"
Dim x = Sub()
End If
'COMPILEERROR : BC30429, "End Sub"
End Sub
'COMPILEERROR : BC30289, "End Module"
End Module
]]>,
<errors>
<error id="36673"/>
</errors>)
End Sub
<WorkItem(885258, "DevDiv/Personal")>
<WorkItem(888613, "DevDiv/Personal")>
<Fact()>
Public Sub BC36714ERR_InitializedExpandedProperty()
ParseAndVerify(<![CDATA[
Class Class1
Public MustOverride Property Goo() As Date = Now
End Class
]]>,
<errors>
<error id="36714"/>
</errors>)
ParseAndVerify(<![CDATA[
Public Interface IFPropertyAssign
Property Scenario2Array() As Integer() = {1,2,3}
Property Scenario2List() As List(Of Integer) = NEW List(Of Integer) FROM {1,2,3}
End Interface
]]>,
<errors>
<error id="36714"/>
<error id="36714"/>
</errors>)
End Sub
<WorkItem(885375, "DevDiv/Personal")>
<Fact>
Public Sub ParseExpectedEndSelect()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
Dim q = From x In {1, 2, 3} _
Where True _
'Comment
Select 2
End Sub
End Class
]]>,
<errors>
<error id="30095" message="'Select Case' must end with a matching 'End Select'."/>
</errors>)
End Sub
<WorkItem(885379, "DevDiv/Personal")>
<Fact>
Public Sub ParseObsoleteArgumentsNeedParensAndArgumentSyntax()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
Dim q = From x In {1, 2} _
'Comment
Where true _
Select 2
End Sub
End Class
]]>,
<errors>
<error id="30800" message="Method arguments must be enclosed in parentheses."/>
<error id="32017" message="Comma, ')', or a valid expression continuation expected."/>
</errors>)
End Sub
<WorkItem(881643, "DevDiv/Personal")>
<Fact()>
Public Sub BC36720ERR_CantCombineInitializers()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x0 = New List(Of Integer) FROM {2,3} with {.capacity=2}
Dim a As New C2() From {"Hello World!"} with {.a = "goo"}
Dim b As New C2() with {.a = "goo"} From {"Hello World!"}
Dim c as C2 = New C2() From {"Hello World!"} with {.a = "goo"}
Dim d as c2 = New C2() with {.a = "goo"} From {"Hello World!"}
End Sub
End Module
]]>, Diagnostic(ERRID.ERR_CantCombineInitializers, "FROM {2,3}"),
Diagnostic(ERRID.ERR_CantCombineInitializers, "with"),
Diagnostic(ERRID.ERR_CantCombineInitializers, "From"),
Diagnostic(ERRID.ERR_CantCombineInitializers, "From {""Hello World!""}"),
Diagnostic(ERRID.ERR_CantCombineInitializers, "with {.a = ""goo""}"))
End Sub
<Fact()>
Public Sub BC30431ERR_InvalidEndProperty_Bug869732()
'Tree loses text when declaring a property Let/End Let
ParseAndVerify(<![CDATA[
Class Class1
Property Goo() as Single
Let
End Let
Get
End Get
Set
End Set
End Property
End Class
]]>,
Diagnostic(ERRID.ERR_ObsoleteLetSetNotNeeded, "Let"),
Diagnostic(ERRID.ERR_UnrecognizedEnd, "End"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Get"),
Diagnostic(ERRID.ERR_InvalidEndGet, "End Get"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Set"),
Diagnostic(ERRID.ERR_InvalidEndSet, "End Set"),
Diagnostic(ERRID.ERR_InvalidEndProperty, "End Property"))
End Sub
<WorkItem(536268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536268")>
<Fact()>
Public Sub ParseExpectedXmlNameAndIllegalChar()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim l = <
<%= "e"%> />
End Sub
End Module
]]>, Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, Environment.NewLine),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "))
End Sub
<WorkItem(536270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536270")>
<Fact()>
Public Sub ParseExpectedXmlnsAndExpectedEQAndExpectedXmlName()
ParseAndVerify(<![CDATA[
Imports < xmlns:ns3="goo">
Imports <xmlns :ns4="goo">
Imports <xmlns: ns5="goo">
Imports < xmlns="goo">
Module Module1
Sub Main()
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedXmlns, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, "xmlns"),
Diagnostic(ERRID.ERR_ExpectedXmlns, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, "xmlns"),
Diagnostic(ERRID.ERR_ExpectedXmlName, "ns5"),
Diagnostic(ERRID.ERR_ExpectedXmlns, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, "xmlns"))
End Sub
<WorkItem(880138, "DevDiv/Personal")>
<Fact()>
Public Sub ParseLambda_ERR_ExpectedIdentifier()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim s6 = Function ((x) (x + 1))
End Sub
End Module
]]>,
<errors>
<error id="30203"/>
<error id="30638"/>
<error id="32014"/>
<error id="36674"/>
</errors>)
End Sub
<WorkItem(880140, "DevDiv/Personal")>
<Fact()>
Public Sub BC32017_ParseObjectMemberInitializer()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
ObjTest!New ClsCustomer With {.ID = 106, .Name = "test 106"}
End Sub
End Module
]]>,
<errors>
<error id="30800"/>
<error id="32017"/>
<error id="32017"/>
</errors>)
End Sub
<WorkItem(880155, "DevDiv/Personal")>
<Fact()>
Public Sub ParseObjectMemberInitializer_ERR_ExpectedEOS()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim c3 as customer = new customer with {.x=5 : .y=6}
End Sub
End Module
]]>,
<errors>
<error id="30370"/>
<error id="30205"/>
</errors>)
End Sub
<WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")>
<WorkItem(894062, "DevDiv/Personal")>
<Fact()>
Public Sub BC30287ERR_ExpectedDot_ParseVariant()
ParseAndVerify(<![CDATA[
If VarType(a1.GetValue(x)) > Variant 'Dev10/11 report expected '.' but Roslyn allows this. Grammar says its OK.
]]>,
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If VarType(a1.GetValue(x)) > Variant"),
Diagnostic(ERRID.ERR_ObsoleteObjectNotVariant, "Variant"))
End Sub
<WorkItem(896842, "DevDiv/Personal")>
<Fact()>
Public Sub ParseIncompleteWithBlocks()
ParseAndVerify(<![CDATA[
Dim x3 = Function(y As Long)
With]]>,
<errors>
<error id="30085"/>
<error id="30201"/>
<error id="36674"/>
</errors>)
ParseAndVerify(<![CDATA[
Dim x3 =Sub()
If]]>,
<errors>
<error id="30081"/>
<error id="30201"/>
<error id="36673"/>
</errors>)
End Sub
<WorkItem(897824, "DevDiv/Personal")>
<Fact()>
Public Sub ParseExplicitLCs()
ParseAndVerify(<![CDATA[
Namespace RegressDev10660280
Sub Goo1(ByVal x As Integer, _
ByVal y As Integer _
)
apCompare(2, x, "Value of goo1")
End Sub
Sub Goo2( _
_
]]>,
<errors>
<error id="30026"/>
<error id="30198"/>
<error id="30203"/>
<error id="30626"/>
</errors>)
End Sub
<WorkItem(888562, "DevDiv/Personal")>
<Fact()>
Public Sub ParseMoreErrorExpectedRparen()
ParseAndVerify(<![CDATA[
Module M
Sub Test()
Dim i As Object
i = ctype(new Cust1 with {.x=6} , new cust1 with {.x =3})
End Sub
Class Cust1
Public x As Integer
End Class
End Module
]]>,
<errors>
<error id="30200"/>
<error id="30198"/>
</errors>)
End Sub
<WorkItem(887788, "DevDiv/Personal")>
<Fact()>
Public Sub ParseMoreErrorExpectedEOS()
ParseAndVerify(<![CDATA[
Module m1
Sub Test()
Try
Catch ex As Exception When New Object With (5) {.x = 9}
End Try
End Sub
End Module
]]>,
<errors>
<error id="30987"/>
</errors>)
End Sub
<WorkItem(887790, "DevDiv/Personal")>
<Fact()>
Public Sub BC31412ERR_HandlesSyntaxInClass_ExpectedIdentifierAndExpectedDot()
ParseAndVerify(<![CDATA[
Class c1
sub test handles new customer with {.x = 5, .y = "6"}
End Sub
End Class
Class customer : End Class
]]>,
<errors>
<error id="30183"/>
<error id="30287"/>
<error id="30203"/>
</errors>)
End Sub
<WorkItem(904917, "DevDiv/Personal")>
<Fact()>
Public Sub ParseErrorInTryInSub()
ParseAndVerify(<![CDATA[Namespace n1
Module m1
public sub bar()
try
dim j =2
dim k =4
public sub goo
End sub
End Module
End Namespace
]]>,
<errors>
<error id="30289"/>
<error id="30384"/>
<error id="30026"/>
</errors>)
End Sub
<WorkItem(924035, "DevDiv/Personal")>
<Fact()>
Public Sub BC36674ERR_MultilineLambdaMissingFunction_ParseLambdaCustomEvent()
ParseAndVerify(<![CDATA[
Structure Scen16
Dim i = Function()
Custom Event ev
End Structure
]]>,
<errors>
<error id="36674"/>
<error id="31122"/>
</errors>)
End Sub
<WorkItem(927100, "DevDiv/Personal")>
<Fact()>
Public Sub BC32005ERR_BogusWithinLineIf()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
For i = 1 To 10
If True Then Console.WriteLine() : Next
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="32005"/>
</errors>)
End Sub
<WorkItem(539208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539208")>
<Fact()>
Public Sub BC32005ERR_BogusWithinLineIf_2()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
If True : If False Then Console.WriteLine(1) : End If
If True : If False Then Else Console.WriteLine(1) : End If
End Sub
End Module
]]>, Diagnostic(ERRID.ERR_ExpectedEndIf, "If True"),
Diagnostic(ERRID.ERR_BogusWithinLineIf, "End If"),
Diagnostic(ERRID.ERR_ExpectedEndIf, "If True"),
Diagnostic(ERRID.ERR_BogusWithinLineIf, "End If")
)
End Sub
<WorkItem(914635, "DevDiv/Personal")>
<Fact()>
Public Sub BC36615ERR_ExpectedInto()
ParseAndVerify(<![CDATA[
Module P
Sub M()
Dim q = from x in y group x by
End Sub
End Module
]]>,
<errors>
<error id="30201"/>
<error id="36615"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30016ERR_InvOutsideProc()
ParseAndVerify(<![CDATA[
Module P
100:
Interface i1
200:
End Interface
structure s1
300:
end structure
enum e
300:
end enum
End Module
]]>,
Diagnostic(ERRID.ERR_InvOutsideProc, "100:"),
Diagnostic(ERRID.ERR_InvOutsideProc, "200:"),
Diagnostic(ERRID.ERR_InvOutsideProc, "300:"),
Diagnostic(ERRID.ERR_InvInsideEnum, "300:"))
End Sub
<WorkItem(539182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539182")>
<Fact()>
Public Sub ParseEmptyStatementWithBadToken()
' There should only be one error reported
ParseAndVerify(<![CDATA[
Module P
Sub main()
$
End Sub
End Module
]]>, <errors>
<error id="30037" message="Character is not valid." start="59" end="60"/>
</errors>)
End Sub
<WorkItem(539515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539515")>
<Fact()>
Public Sub ParseNestedSingleLineIfFollowedByEndIf()
' Report error for mismatched END IF.
ParseAndVerify(<![CDATA[Module M
Sub Main()
If False Then Else If True Then Else
End If
End Sub
End Module]]>,
<errors>
<error id="30087" message="'End If' must be preceded by a matching 'If'." start="88" end="94"/>
</errors>)
End Sub
<WorkItem(539515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539515")>
<Fact()>
Public Sub ParseSingleLineWithNestedMultiLineIf()
' Report error for mismatched END IF.
ParseAndVerify(<![CDATA[
Module M
Sub Main()
If False Then Else If True Then
End if
End Sub
End Module]]>, <errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="89" end="101"/>
<error id="30087" message="'End If' must be preceded by a matching 'If'." start="122" end="128"/>
</errors>)
End Sub
<Fact()>
Public Sub ParseSingleLineIfThenElseFollowedByIfThen()
' This is a single line if-then-else with a multi-line-if-then
ParseAndVerify(<![CDATA[
Module Module1
Sub goo()
If False Then Else if true then
If False Then Else if true then
end if
If False Then Else if true then : end if
End Sub
End Module]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="93" end="105"/>
<error id="30081" message="'If' must end with a matching 'End If'." start="146" end="158"/>
<error id="30087" message="'End If' must be preceded by a matching 'If'." start="199" end="205"/>
</errors>)
End Sub
<Fact()>
Public Sub ParseSingleLineIfThenFollowedByIfThen()
' This is a single line if-then-else with a multi-line-if-then
ParseAndVerify(<![CDATA[
Module Module1
Sub goo()
If False Then if true then
If False Then if true then
end if
If False Then if true then : end if
End Sub
End Module]]>, <Errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="88" end="100"/>
<error id="30081" message="'If' must end with a matching 'End If'." start="136" end="148"/>
<error id="30087" message="'End If' must be preceded by a matching 'If'." start="189" end="195"/>
</Errors>)
End Sub
<Fact()>
Public Sub ParseSingleLineIfThenElseFollowedByDo()
' This is a single line if-then-else with a multi-line-if-then
ParseAndVerify(<![CDATA[
Module Module1
Sub goo()
If False Then Else do
If False Then Else do
Loop
If False Then Else Do : Loop
End Sub
End Module]]>, <errors>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="94" end="96"/>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="139" end="141"/>
<error id="30091" message="'Loop' must be preceded by a matching 'Do'." start="183" end="187"/>
</errors>)
End Sub
<Fact()>
Public Sub ParseSingleLineIfThenFollowedByDo()
' This is a single line if-then-else with a multi-line-if-then
ParseAndVerify(<![CDATA[
Module Module1
Sub goo()
If False Then do
If False Then do
Loop
If False Then Do : Loop
End Sub
End Module]]>,
<errors>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="88" end="90"/>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="127" end="129"/>
<error id="30091" message="'Loop' must be preceded by a matching 'Do'." start="165" end="169"/>
</errors>)
End Sub
<Fact()>
Public Sub ParseMultiLineIfMissingThen()
'this is a "multi line if" missing a "then". "f()" after "true" is error as well as missing "end if
ParseAndVerify(<![CDATA[
Module Module1
sub goo()
if true f()
if true then else if true f() is an error
End Sub
End Module]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="74" end="81"/>
<error id="30205" message="End of statement expected." start="82" end="83"/>
<error id="30081" message="'If' must end with a matching 'End If'." start="125" end="132"/>
<error id="30205" message="End of statement expected." start="133" end="134"/>
</errors>)
End Sub
<Fact()>
Public Sub VarDeclWithKeywordAsIdentifier()
ParseAndVerify(<![CDATA[
Class C1
' the following usages of Dim/Const do not report parser diagnostics, they will
' be reported while binding.
Dim Sub S1()
End Sub
Const Function F1() as Integer
return 23
End Function
Dim Property P1() as Integer
Dim Public Shared Operator +(m1 as C1, m2 as C1)
return nothing
End Operator
' keyword is not an identifier, outside of method body
Public Property Namespace As String
Public Property Class As String
Const End As String
Sub Goo()
' keyword is not an identifier, inside of method body
Dim Namespace as integer
Dim Class
Const End
End Sub
' Parser: specifier invalid on this statement
dim namespace
end namespace
' binding errors, not reported here.
dim class c2
end class
End Class
' Parser: specifier invalid on this statement
dim namespace
end namespace
' binding errors, not reported here.
dim class c2
end class
dim module goo
end module
]]>, Diagnostic(ERRID.ERR_ExpectedEndClass, "Class C1").WithLocation(2, 13),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Namespace").WithLocation(19, 33),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Class").WithLocation(20, 33),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "End").WithLocation(21, 23),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Namespace").WithLocation(25, 25),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Class").WithLocation(26, 25),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "End").WithLocation(27, 27),
Diagnostic(ERRID.ERR_NamespaceNotAtNamespace, "namespace").WithLocation(31, 21),
Diagnostic(ERRID.ERR_SpecifiersInvalidOnInheritsImplOpt, "dim").WithLocation(31, 17),
Diagnostic(ERRID.ERR_ExpectedIdentifier, "").WithLocation(31, 30),
Diagnostic(ERRID.ERR_EndClassNoClass, "End Class").WithLocation(37, 13),
Diagnostic(ERRID.ERR_SpecifiersInvalidOnInheritsImplOpt, "dim").WithLocation(40, 13),
Diagnostic(ERRID.ERR_ExpectedIdentifier, "").WithLocation(40, 26))
End Sub
<WorkItem(542066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542066")>
<Fact()>
Public Sub Bug9035()
ParseAndVerify(<![CDATA[
Module Program
Sub Main()
if true then console.writeline() : ' this goes here.
' test this case in the if part of the single line if statement
If True Then try :
finally
end try
If True Then select case true :
end select
If True Then using resource As New Object() :
end using
If True Then while true :
end while
If True Then do while true :
loop
If True Then with nothing :
end with
If True Then for each x as object in nothing :
next
If True Then for x as object = 1 to 12:
next
If True Then if true :
end if
If True Then synclock new Object() :
end synclock
'
' test this case in the else part of the single line if statement
If True Then else try :
finally
end try
If True Then else select case true :
end select
If True Then else using resource As New Object() :
end using
If True Then else while true :
end while
If True Then else do while true :
loop
If True Then else with nothing :
end with
If True Then else for each x as object in nothing :
next
If True Then else for x as object = 1 to 12:
next
If True Then else if true :
end if
If True Then else synclock new Object() :
end synclock
' make sure multiline statements in a single line if still work when being written in one line.
If True Then select case 1 : case else : end select
' make sure not to break the single line lambdas
Dim s1 = Sub() If True Then Console.WriteLine(1) :
Dim s2 = Sub() If True Then Console.WriteLine(1) :: Console.WriteLine(1) ::
Dim s3 = Sub() If True Then Console.WriteLine(1) :::: Console.WriteLine(1)
Dim s4 = (Sub() If True Then Console.WriteLine(1):)
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedEndTry, "try"),
Diagnostic(ERRID.ERR_FinallyNoMatchingTry, "finally"),
Diagnostic(ERRID.ERR_EndTryNoTry, "end try"),
Diagnostic(ERRID.ERR_ExpectedEndSelect, "select case true"),
Diagnostic(ERRID.ERR_ExpectedCase, ""),
Diagnostic(ERRID.ERR_EndSelectNoSelect, "end select"),
Diagnostic(ERRID.ERR_ExpectedEndUsing, "using resource As New Object()"),
Diagnostic(ERRID.ERR_EndUsingWithoutUsing, "end using"),
Diagnostic(ERRID.ERR_ExpectedEndWhile, "while true"),
Diagnostic(ERRID.ERR_EndWhileNoWhile, "end while"),
Diagnostic(ERRID.ERR_ExpectedLoop, "do while true"),
Diagnostic(ERRID.ERR_LoopNoMatchingDo, "loop"),
Diagnostic(ERRID.ERR_ExpectedEndWith, "with nothing"),
Diagnostic(ERRID.ERR_EndWithWithoutWith, "end with"),
Diagnostic(ERRID.ERR_ExpectedNext, "for each x as object in nothing"),
Diagnostic(ERRID.ERR_NextNoMatchingFor, "next"),
Diagnostic(ERRID.ERR_ExpectedNext, "for x as object = 1 to 12"),
Diagnostic(ERRID.ERR_NextNoMatchingFor, "next"),
Diagnostic(ERRID.ERR_ExpectedEndIf, "if true"),
Diagnostic(ERRID.ERR_EndIfNoMatchingIf, "end if"),
Diagnostic(ERRID.ERR_ExpectedEndSyncLock, "synclock new Object()"),
Diagnostic(ERRID.ERR_EndSyncLockNoSyncLock, "end synclock"),
Diagnostic(ERRID.ERR_ExpectedEndTry, "try"),
Diagnostic(ERRID.ERR_FinallyNoMatchingTry, "finally"),
Diagnostic(ERRID.ERR_EndTryNoTry, "end try"),
Diagnostic(ERRID.ERR_ExpectedEndSelect, "select case true"),
Diagnostic(ERRID.ERR_ExpectedCase, ""),
Diagnostic(ERRID.ERR_EndSelectNoSelect, "end select"),
Diagnostic(ERRID.ERR_ExpectedEndUsing, "using resource As New Object()"),
Diagnostic(ERRID.ERR_EndUsingWithoutUsing, "end using"),
Diagnostic(ERRID.ERR_ExpectedEndWhile, "while true"),
Diagnostic(ERRID.ERR_EndWhileNoWhile, "end while"),
Diagnostic(ERRID.ERR_ExpectedLoop, "do while true"),
Diagnostic(ERRID.ERR_LoopNoMatchingDo, "loop"),
Diagnostic(ERRID.ERR_ExpectedEndWith, "with nothing"),
Diagnostic(ERRID.ERR_EndWithWithoutWith, "end with"),
Diagnostic(ERRID.ERR_ExpectedNext, "for each x as object in nothing"),
Diagnostic(ERRID.ERR_NextNoMatchingFor, "next"),
Diagnostic(ERRID.ERR_ExpectedNext, "for x as object = 1 to 12"),
Diagnostic(ERRID.ERR_NextNoMatchingFor, "next"),
Diagnostic(ERRID.ERR_ExpectedEndIf, "if true"),
Diagnostic(ERRID.ERR_EndIfNoMatchingIf, "end if"),
Diagnostic(ERRID.ERR_ExpectedEndSyncLock, "synclock new Object()"),
Diagnostic(ERRID.ERR_EndSyncLockNoSyncLock, "end synclock"))
End Sub
<WorkItem(543724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543724")>
<Fact()>
Public Sub ElseIfStatementOutsideMethodBody()
ParseAndVerify(<![CDATA[
Class c6
else if
End Class
]]>,
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "else if "),
Diagnostic(ERRID.ERR_ExpectedExpression, ""))
End Sub
<WorkItem(544495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544495")>
<Fact>
Public Sub CatchFinallyStatementOutsideMethodBody()
ParseAndVerify(<![CDATA[
Catch ex As Exception
Finally
]]>, Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch ex As Exception"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Finally"))
End Sub
<WorkItem(544519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544519")>
<Fact>
Public Sub TryStatementOutsideMethodBody()
ParseAndVerify(<![CDATA[
Module Program
Public _Sub Main()
Try
End Try
End Sub
End Module
]]>, Diagnostic(ERRID.ERR_ExpectedEOS, "Main"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_EndTryNoTry, "End Try"),
Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub"))
End Sub
#End Region
<WorkItem(545543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545543")>
<Fact>
Public Sub ParseInvalidUseOfBlockWithinSingleLineLambda()
Dim compilationDef =
<compilation name="LambdaTests_err">
<file name="a.vb">
Module Program
Sub Main()
For i = 1 To 10
Dim x = Sub() For j = 1 To 10
Next j, i
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedNext, "For j = 1 To 10"),
Diagnostic(ERRID.ERR_ExtraNextVariable, "i"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "j").WithArguments("j"))
End Sub
<WorkItem(545543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545543")>
<ConditionalFact(GetType(WindowsOnly))>
Public Sub ParseValidUseOfBlockWithinMultiLineLambda()
Dim compilationDef =
<compilation name="LambdaTests_err">
<file name="a.vb">
Module Program
Sub Main()
For i = 1 To 10
Dim x = Sub()
End Sub
For j = 1 To 10
Next j, i
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation)
CompilationUtils.AssertNoErrors(compilation)
Dim NodeFound = From lambdaItem In compilation.SyntaxTrees(0).GetRoot.DescendantNodes.OfType(Of MultiLineLambdaExpressionSyntax)()
Select lambdaItem
Assert.Equal(1, NodeFound.Count)
End Sub
<WorkItem(545543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545543")>
<ConditionalFact(GetType(WindowsOnly))>
Public Sub ParseValidUseOfNonBlockWithinSingleLineLambda()
Dim compilationDef =
<compilation name="LambdaTests_err">
<file name="a.vb">
Module Program
Sub Main()
Dim Item = 0
For i = 1 To 10
Dim x = Sub() Item = 1
For j = 1 To 10
Next j, i
End Sub
End Module
</file>
</compilation>
'Should be No errors and a single line lambda is in use
Dim Compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(Compilation, <expected>
</expected>)
CompileAndVerify(Compilation)
Dim NodeFound1 = From lambdaItem In Compilation.SyntaxTrees(0).GetRoot.DescendantNodes.OfType(Of SingleLineLambdaExpressionSyntax)()
Select lambdaItem
Assert.Equal(1, NodeFound1.Count)
End Sub
<WorkItem(545543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545543")>
<ConditionalFact(GetType(WindowsOnly))>
Public Sub ParseValidUseOfBlockWithinSingleLineLambda()
'Subtle Variation with Single line Statement Lambda and a Block Construct
Dim compilationDef =
<compilation name="LambdaTests_err">
<file name="a.vb">
Module Program
Sub Main()
Dim Item = 0
For i = 1 To 10
Dim x = Sub() if true Then For j = 1 To 2 : Next j
Next i
End Sub
End Module
</file>
</compilation>
'Should be No errors and a single line lambda is in use
Dim Compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(Compilation, <expected>
</expected>)
CompileAndVerify(Compilation)
Dim NodeFound1 = From lambdaItem In Compilation.SyntaxTrees(0).GetRoot.DescendantNodes.OfType(Of SingleLineLambdaExpressionSyntax)()
Select lambdaItem
Assert.Equal(1, NodeFound1.Count)
End Sub
<WorkItem(530516, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530516")>
<Fact()>
Public Sub Bug530516()
Dim tree = ParseAndVerify(<![CDATA[
Class C
Implements I(
End Class
]]>,
<errors>
<error id="32093"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Implements IA(Of A()).IB(
End Class
]]>,
<errors>
<error id="32093"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Implements I()
End Class
]]>,
<errors>
<error id="32093"/>
<error id="30182"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Implements I(Of
End Class
]]>,
<errors>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=False)
tree = ParseAndVerify(<![CDATA[
Class C
Implements I(Of)
End Class
]]>,
<errors>
<error id="30182"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=False)
' No parse errors.
tree = ParseAndVerify(<![CDATA[
Class C
Implements I(Of A(Of B()).C(Of D()).E())
End Class
]]>)
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements I(
End Class
]]>,
<errors>
<error id="30287"/>
<error id="32093"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements IA(Of A()).IB(
End Class
]]>,
<errors>
<error id="32093"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements I().P
End Class
]]>,
<errors>
<error id="32093"/>
<error id="30182"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements I(Of
End Class
]]>,
<errors>
<error id="30287"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=False)
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements I(Of).P
End Class
]]>,
<errors>
<error id="30182"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=False)
' No parse errors.
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements I(Of A(Of B()).C(Of D()).E()).P
End Class
]]>)
End Sub
Private Shared Sub CheckTokensForIncompleteImplements(tree As SyntaxTree, ofMissing As Boolean)
Dim tokens = tree.GetRoot().DescendantTokens().ToArray()
' No tokens should be skipped.
Assert.False(tokens.Any(Function(t) t.HasStructuredTrivia))
' Find last '(' token.
Dim indexOfOpenParen = -1
For i = 0 To tokens.Length - 1
If tokens(i).Kind = SyntaxKind.OpenParenToken Then
indexOfOpenParen = i
End If
Next
Assert.NotEqual(indexOfOpenParen, -1)
' Of token may have been synthesized.
Dim ofToken = tokens(indexOfOpenParen + 1)
Assert.Equal(ofToken.Kind, SyntaxKind.OfKeyword)
Assert.Equal(ofToken.IsMissing, ofMissing)
' Type identifier must have been synthesized.
Dim identifierToken = tokens(indexOfOpenParen + 2)
Assert.Equal(identifierToken.Kind, SyntaxKind.IdentifierToken)
Assert.True(identifierToken.IsMissing)
End Sub
<WorkItem(546688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546688")>
<Fact()>
Public Sub Bug16568_If()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do : Loop
End Sub
End Module
]]>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do : : Loop
End Sub
End Module
]]>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30035"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do :
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do :
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do ::
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do : :
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
End Sub
<WorkItem(546688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546688")>
<Fact()>
Public Sub Bug16568_Else()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do : Loop
End Sub
End Module
]]>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do : : Loop
End Sub
End Module
]]>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30035"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do :
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do :
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do ::
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do : :
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
End Sub
<WorkItem(546734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546734")>
<Fact()>
Public Sub Bug16688()
Dim tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 :
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 :
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 : :
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 _
:
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 End Module
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 : End Module
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
End Sub
''' <summary>
''' Trivia up to and including the last colon on the line
''' should be associated with the preceding token.
''' </summary>
<Fact()>
Public Sub ParseTriviaFollowingColon_1()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
Call M0 : ' Comment
If True Then Call M1 : : Call M2
End Sub
End Module
]]>.Value.Trim())
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node.ToFullString().NormalizeLineEndings()).ToArray()
CheckArray(tokens,
"Module ",
"M" & vbCrLf,
" Sub ",
"M",
"(",
")" & vbCrLf,
" Call ",
"M0 :",
" ' Comment" & vbCrLf & " If ",
"True ",
"Then ",
"Call ",
"M1 : :",
" Call ",
"M2" & vbCrLf,
" End ",
"Sub" & vbCrLf,
"End ",
"Module",
"")
End Sub
<Fact()>
Public Sub ParseTriviaFollowingColon_2()
Dim tree = ParseAndVerify(<![CDATA[Interface I : : End Interface : : Class A :: Implements I :: End Class]]>)
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node.ToFullString()).ToArray()
CheckArray(tokens,
"Interface ",
"I : :",
" End ",
"Interface : :",
" Class ",
"A ::",
" Implements ",
"I ::",
" End ",
"Class",
"")
End Sub
<Fact()>
Public Sub ParseTriviaFollowingColon_3()
Dim tree = ParseAndVerify(<![CDATA[
<Assembly: B>
Class B
Inherits System.Attribute
Sub M()
L1: Exit Sub
End Sub
End Class
]]>)
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node).ToArray()
Dim token = tokens.First(Function(t) t.GetValueText() = ":")
Assert.Equal(token.ToFullString(), ": ")
token = tokens.First(Function(t) t.GetValueText() = "B")
Assert.Equal(token.ToFullString(), "B")
token = tokens.Last(Function(t) t.GetValueText() = "L1")
Assert.Equal(token.ToFullString(), "L1")
token = tokens.First(Function(t) t.GetValueText() = "Exit")
Assert.Equal(token.ToFullString(), " Exit ")
End Sub
<WorkItem(531059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531059")>
<Fact()>
Public Sub ParseSingleLineLambdaInSingleLineIf()
Dim tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main1()
If True Then Dim x = Function() Sub() Console.WriteLine :
Else Return
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
<error id="30086" message="'Else' must be preceded by a matching 'If' or 'ElseIf'."/>
<error id="30205" message="End of statement expected."/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
If True Then Dim x = Function() Sub() Console.WriteLine :: Else Return
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
If True Then Dim x = Function() Sub() Console.WriteLine : : Else Return
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement." start="101" end="118"/>
</errors>)
End Sub
<WorkItem(547060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547060")>
<Fact()>
Public Sub ParseSingleLineLambdaInSingleLineIf01()
Dim tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
If True Then Dim x = Function() Sub() Console.WriteLine : Else Return
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement." start="77" end="94"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
If True Then Dim x = Function() Sub() Console.WriteLine Else Return
End Sub
End Module
]]>)
End Sub
<WorkItem(578144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578144")>
<Fact()>
Public Sub ParseStatementLambdaOnSingleLineLambdaWithColon()
Dim tree = ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = Sub() : Dim a1 = 1 : End Sub
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_SubRequiresSingleStatement, "Sub() "),
Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub"))
End Sub
<WorkItem(531086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531086")>
<Fact()>
Public Sub Bug17550()
ParseAndVerify("<!--" + vbCrLf,
<errors>
<error id="30035" message="Syntax error." start="0" end="4"/>
</errors>)
ParseAndVerify("%>" + vbCrLf,
<errors>
<error id="30035" message="Syntax error." start="0" end="2"/>
</errors>)
ParseAndVerify("<!-- :",
<errors>
<error id="30035" message="Syntax error." start="0" end="4"/>
</errors>)
ParseAndVerify("%> :",
<errors>
<error id="30035" message="Syntax error." start="0" end="2"/>
</errors>)
End Sub
<WorkItem(531102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531102")>
<Fact()>
Public Sub Bug17574_XmlAttributeAccess()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p :
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p::
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p::y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:: y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p: :
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p: :y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:'Comment
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:y
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:y:
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p: y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p : y
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.
@p
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@< ' comment
End Sub
End Module
]]>,
<errors>
<error id="31177" start="62" end="63"/>
<error id="31146" message="XML name expected." start="63" end="63"/>
<error id="30636" message="'>' expected." start="63" end="63"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:'Comment
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p::
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p::y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:: y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p: :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p: :y
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:y
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p: y
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p : y
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:y>
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.
@<p>
End Sub
End Module
]]>)
End Sub
<WorkItem(531102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531102")>
<Fact()>
Public Sub Bug17574_XmlElementAccess()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p::
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p::y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p:: y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p: :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p: :y
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p:y
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p> :
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.
<p>
End Sub
End Module
]]>)
End Sub
<WorkItem(531102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531102")>
<Fact()>
Public Sub Bug17574_XmlDescendantAccess()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...
End Sub
End Module
]]>,
<errors>
<error id="31165" message="Expected beginning '<' for an XML tag."/>
<error id="31146" message="XML name expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...:
End Sub
End Module
]]>,
<errors>
<error id="31165" message="Expected beginning '<' for an XML tag."/>
<error id="31146" message="XML name expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p::
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p::y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p:: y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p: :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p: :y
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p:y
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p> :
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...
<p>
End Sub
End Module
]]>)
End Sub
<WorkItem(531102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531102")>
<Fact()>
Public Sub Bug17574_Comment()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p 'comment
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:a Rem comment
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@Rem 'comment
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:Rem Rem comment
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@Rem:a 'comment
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<Rem:Rem> Rem comment
End Sub
End Module
]]>)
End Sub
<WorkItem(531102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531102")>
<Fact()>
Public Sub Bug17574_Other()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@Return: Return
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@xml:a: Return
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim b = <x/>.@xml:
y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="48" end="48"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = <a :Return
End Sub
End Module
]]>,
<errors>
<error id="31151" message="Element is missing an end tag." start="66" end="66"/>
<error id="31177"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
<error id="31165"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
End Sub
<WorkItem(531480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531480")>
<Fact>
Public Sub ImplicitLineContinuationAfterQuery()
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() From c In ""
Distinct
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Function() From c In ""
Distinct
)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() From c In ""
Distinct
Is Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then x = From c In ""
Distinct : Return
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then x = From c In ""
Distinct : Return
End Module
]]>)
' Breaking change: Dev11 allows implicit
' line continuation after Distinct.
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then x = From c In ""
Distinct
: Return ' Dev11: no error
End Module
]]>,
<errors>
<error id="30689" message="Statement cannot appear outside of a method body."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If Nothing Is From c In ""
Distinct Then
End If
End Sub
End Module
]]>)
' Breaking change: Dev11 allows implicit
' line continuation after Distinct.
ParseAndVerify(<![CDATA[
Module M
Sub M()
If Nothing Is From c In ""
Distinct
Then ' Dev11: no error
End If
End Sub
End Module
]]>,
<errors>
<error id="30035" message="Syntax error."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If Nothing Is From c In "" Order By c _
Then
End If
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If Nothing Is From c In "" Order By c
Then
End If
End Sub
End Module
]]>,
<errors>
<error id="30035" message="Syntax error."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then x = From c In "" Order By c Ascending _
: Return
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then x = From c In "" Order By c Ascending
: Return
End Module
]]>,
<errors>
<error id="30689" message="Statement cannot appear outside of a method body."/>
</errors>)
End Sub
<WorkItem(531632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531632")>
<Fact()>
Public Sub ColonTerminatorFollowingXmlAttributeAccess()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = <x/>.@a:b:Return
End Sub
End Module
]]>)
End Sub
<WorkItem(547195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547195")>
<Fact()>
Public Sub ColonFollowingImplicitContinuation()
ParseAndVerify(<![CDATA[
Module M
Function M(x As Object) As Object
Return x.
:
End Function
End Module
]]>,
<errors>
<error id="30203" message="Identifier expected." start="46" end="46"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Function M(x As String) As Object
Return From c In x
:
End Function
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Function M(x As String) As Object
Return From c In
:
End Function
End Module
]]>,
<errors>
<error id="30201" message="Expression expected." start="46" end="46"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = 1 +
:
End Sub
End Module
]]>,
<errors>
<error id="30201" message="Expression expected." start="46" end="46"/>
</errors>)
End Sub
<Fact()>
Public Sub ColonAtEndOfFile()
ParseAndVerify(<![CDATA[:]]>)
ParseAndVerify(<![CDATA[:::]]>)
ParseAndVerify(<![CDATA[: : :]]>)
ParseAndVerify(<![CDATA[: : : ]]>)
ParseAndVerify(<![CDATA[Module M :]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
</errors>)
ParseAndVerify(<![CDATA[Module M :::]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
</errors>)
ParseAndVerify(<![CDATA[Module M : : :]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
</errors>)
ParseAndVerify(<![CDATA[Module M : : : ]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
</errors>)
End Sub
<WorkItem(547305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547305")>
<Fact()>
Public Sub Bug547305()
ParseAndVerify(<![CDATA[
Module M
Function F() As C(
]]>,
<errors>
<error id="30625"/>
<error id="30027"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F = Function() As C(
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F = Function() As C(Of
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
' Unexpected tokens in lambda header.
ParseAndVerify(<![CDATA[
Module M
Private F = Function() As A B
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
<error id="30205"/>
</errors>)
' Unexpected tokens in lambda body.
ParseAndVerify(<![CDATA[
Module M
Private F = Function()
End Func
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
<error id="30678"/>
</errors>)
End Sub
<Fact()>
Public Sub ImplicitContinuationAfterFrom()
ParseAndVerify(<![CDATA[
Module M
Function M(x As String) As Object
Return From
c in x
End Function
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Function M(x As String) As Object
Return From
c in x
End Function
End Module
]]>,
<errors>
<error id="30800" message="Method arguments must be enclosed in parentheses." start="70" end="70"/>
<error id="30201" message="Expression expected." start="70" end="70"/>
</errors>)
End Sub
<WorkItem(552836, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552836")>
<Fact()>
Public Sub MoreNextVariablesThanBlockContexts()
ParseAndVerify(<![CDATA[
For x = 1 to 5
Next x, y,
]]>,
<errors>
<error id="30689"/>
<error id="30092"/>
<error id="30201"/>
<error id="32037"/>
</errors>)
ParseAndVerify(<![CDATA[
For Each x in Nothing
Next x, y, z
]]>,
<errors>
<error id="30689"/>
<error id="30092"/>
<error id="32037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For x = 1 to 5
For Each y In Nothing
Next y, x, w, v, u, t, s
End Sub
End Module
]]>,
<errors>
<error id="32037"/>
</errors>)
End Sub
<WorkItem(553962, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553962")>
<Fact()>
Public Sub Bug553962()
ParseAndVerify(<![CDATA[
Module M
Private F <!--
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}!--
End Module
]]>.Value, FULLWIDTH_LESS_THAN_SIGN),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F <!-- :
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F <?
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}?
End Module
]]>.Value, FULLWIDTH_LESS_THAN_SIGN),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F ?>
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}>
End Module
]]>.Value, FULLWIDTH_QUESTION_MARK),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F </
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}/
End Module
]]>.Value, FULLWIDTH_LESS_THAN_SIGN),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F %>
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}>
End Module
]]>.Value, FULLWIDTH_PERCENT_SIGN),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F <!DOCTYPE
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}!DOCTYPE
End Module
]]>.Value, FULLWIDTH_LESS_THAN_SIGN),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<source>
Module M
Private F <![CDATA[
End Module
</source>.Value,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<source>
Module M
Private F {0}![CDATA[
End Module
</source>.Value, FULLWIDTH_LESS_THAN_SIGN),
<errors>
<error id="30034"/>
<error id="30203" message="Identifier expected."/>
</errors>)
ParseAndVerify(<source>
Module M
Sub M()
:<![CDATA[
]]>
End Sub
End Module
</source>.Value,
<errors>
<error id="30035"/>
<error id="30037"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<source>
Module M
Sub M() _
Dim x = <![CDATA[
]]>
End Sub
End Module
</source>.Value,
<errors>
<error id="30205" message="End of statement expected."/>
<error id="30037"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(553962, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553962")>
<WorkItem(571807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/571807")>
<Fact()>
Public Sub Bug571807()
ParseAndVerify(<![CDATA[
Module M
Private F = <% Function()
End Function() %>
End Module
]]>,
<errors>
<error id="31151"/>
<error id="31169"/>
<error id="30249" message="'=' expected."/>
<error id="30035"/>
<error id="31165"/>
<error id="30636"/>
<error id="30430"/>
<error id="30205"/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F = <% Function()
End Function() {0}>
End Module
]]>.Value, FULLWIDTH_PERCENT_SIGN),
<errors>
<error id="31151"/>
<error id="31169"/>
<error id="30249" message="'=' expected."/>
<error id="30035"/>
<error id="31165"/>
<error id="30636"/>
<error id="30430"/>
<error id="30205"/>
</errors>)
End Sub
<WorkItem(570756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570756")>
<Fact()>
Public Sub FullWidthKeywords()
Dim source = <![CDATA[
Class C
End Class
]]>.Value.ToFullWidth()
ParseAndVerify(source)
End Sub
<WorkItem(588122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/588122")>
<WorkItem(587130, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/587130")>
<Fact()>
Public Sub FullWidthKeywords001()
Dim source = <![CDATA[
Imports System.Security
<ASSEMBLY: CLSCompliant(True)>
#Const x = CDBL(0)
Module M
Dim x = CDBL(0)
End Module
]]>.Value.ToFullWidth()
ParseAndVerify(source)
End Sub
<WorkItem(571529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/571529")>
<Fact()>
Public Sub Bug571529()
ParseAndVerify(<![CDATA[
Module M
Private F = Sub()
Async:
M.F()
End Sub
End Module
]]>)
End Sub
<WorkItem(581662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581662")>
<Fact()>
Public Sub BlankLinesFollowingUnderscore()
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
_
_
Take 1
End Module
]]>)
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In ""
_
_
Take 1
End Module
]]>)
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
_
Take 1
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
_
Take 1
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
'Comment
Take 1
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
'Comment _
Take 1
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
End Sub
<WorkItem(608214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608214")>
<Fact()>
Public Sub Bug608214()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then %
End Sub
End Module
]]>,
<errors>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Return : %
End Sub
End Module
]]>,
<errors>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Return Else %
End Sub
End Module
]]>,
<errors>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Return Else Return : %
End Sub
End Module
]]>,
<errors>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then 5 Else 6
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_Syntax, "5").WithLocation(4, 22)
)
End Sub
<WorkItem(608214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608214")>
<WorkItem(610345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610345")>
<Fact()>
Public Sub Bug608214_2()
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If True Then Return :
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If True Then Return : REM
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If True Then Return : _
: %>
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If True Then Return : _
:
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If True Then Return Else % :
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="30037" message="Character is not valid."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
End Sub
<WorkItem(608225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608225")>
<Fact()>
Public Sub Bug608225()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
End Module
]]>,
<errors>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return : _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return : End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : _
Sub M()
End Sub
End Module
]]>,
<errors>
<error id="30289"/>
<error id="30429" message="'End Sub' must be preceded by a matching 'Sub'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : _
<A> Dim y As Object
End Module
]]>,
<errors>
<error id="30660" message="Attributes cannot be applied to local variables."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() If True Then Else Return : _
Else
End If
End Sub
End Module
]]>,
<errors>
<error id="30086" message="'Else' must be preceded by a matching 'If' or 'ElseIf'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Sub() If True Then Return : _
Catch e As System.Exception
End Try
End Sub
End Module
]]>,
<errors>
<error id="30380" message="'Catch' cannot appear outside a 'Try' statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Sub() If True Then Return : _
Finally
End Try
End Sub
End Module
]]>,
<errors>
<error id="30382" message="'Finally' cannot appear outside a 'Try' statement."/>
</errors>)
End Sub
''' <summary>
''' Line continuation trivia should include the underscore only.
''' </summary>
<WorkItem(581662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581662")>
<Fact()>
Public Sub LineContinuationTrivia()
Dim source = <![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
_
_
Take 1 _
End Module
]]>.Value
' Source containing underscores and spaces.
LineContinuationTriviaCore(source, "_")
' Source containing underscores and tabs.
LineContinuationTriviaCore(source.Replace(" "c, vbTab), "_")
' Source containing full-width underscores and spaces.
LineContinuationTriviaErr(source.Replace("_"c, FULLWIDTH_LOW_LINE), "" + FULLWIDTH_LOW_LINE)
End Sub
Private Sub LineContinuationTriviaCore(source As String, charAsString As String)
Dim tree = ParseAndVerify(source)
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node).ToArray()
Dim allTrivia = tree.GetRoot().DescendantTrivia().ToArray()
For Each trivia In allTrivia
If trivia.Kind = SyntaxKind.LineContinuationTrivia Then
Assert.Equal(trivia.Width, 1)
Assert.Equal(trivia.ToString(), charAsString)
End If
Next
End Sub
Private Sub LineContinuationTriviaErr(source As String, charAsString As String)
Dim tree = ParseAndVerify(source,
Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"),
Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"),
Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"),
Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"))
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node).ToArray()
Dim allTrivia = tree.GetRoot().DescendantTrivia().ToArray()
For Each trivia In allTrivia
If trivia.Kind = SyntaxKind.LineContinuationTrivia Then
Assert.Equal(trivia.Width, 1)
Assert.Equal(trivia.ToString(), charAsString)
End If
Next
End Sub
''' <summary>
''' Each colon should be a separate trivia node.
''' </summary>
<WorkItem(612584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612584")>
<Fact()>
Public Sub ConsecutiveColonsTrivia()
Dim source = <![CDATA[
Module M
::
: :
Sub M()
10:::
20: : :
Label:::
:: M() :: : M() : ::
: : Return : :
End Sub
End Module
]]>.Value
ConsecutiveColonsTriviaCore(source, ":")
ConsecutiveColonsTriviaCore(source.Replace(":"c, FULLWIDTH_COLON), FULLWIDTH_COLON_STRING)
End Sub
Private Sub ConsecutiveColonsTriviaCore(source As String, singleColon As String)
Dim tree = ParseAndVerify(source)
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node).ToArray()
Dim allTrivia = tree.GetRoot().DescendantTrivia().ToArray()
For Each trivia In allTrivia
If trivia.Kind = SyntaxKind.ColonTrivia Then
Assert.Equal(trivia.Width, 1)
Assert.Equal(trivia.ToString(), singleColon)
End If
Next
End Sub
<Fact()>
Public Sub CanFollowExpression()
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() Return)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then Return)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then Else)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then Else Return)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then If False Then Else)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then If False Then Else : Else)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() Return, y = Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return, y = Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else, y = Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return, y = Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If False Then Else, y = Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If False Then Else : Else, y = Nothing
End Module
]]>)
End Sub
<WorkItem(619627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619627")>
<Fact()>
Public Sub OuterEndWithinMultiLineLambda()
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() As Object Else End Module]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="36674"/>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then
Else Return
End If
End Sub
End Module]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then
Else End Module]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="30081" message="'If' must end with a matching 'End If'."/>
<error id="30622"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
Else End Module]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="30086" message="'Else' must be preceded by a matching 'If' or 'ElseIf'."/>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then : Else End Module]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="30081" message="'If' must end with a matching 'End If'."/>
<error id="30622"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For Each c in ""
Dim x = Sub()
If True Then : Else Next : End If
End Sub
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="30092"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For Each c in ""
Dim x = Function()
If True Then : Else Next : End If
End Function
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="30092"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For Each c in ""
Dim x = Function()
If True Then If False Then : Else Next : End If
End Function
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For Each c in ""
Dim x = Sub() If True Then : Else Next : End If
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="30092"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Sub()
Catch
End Sub
End Try
End Sub
End Module
]]>,
<errors>
<error id="30384"/>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="30383"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Function()
Finally
End Function
End Try
End Sub
End Module
]]>,
<errors>
<error id="36674" message="Multiline lambda expression is missing 'End Function'."/>
<error id="30430"/>
</errors>)
End Sub
<WorkItem(620546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620546")>
<Fact()>
Public Sub NestedMultiLineBlocksInSingleLineIf()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else While True : Using Nothing
End Using : End While
End Sub
End Module
]]>,
<errors>
<error id="30082"/>
<error id="36008"/>
<error id="36007"/>
<error id="30090"/>
</errors>)
End Sub
<Fact()>
Public Sub SingleLineSubMultipleStatements()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() While True : End While
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() While True : End While : M()
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() M() : Using Nothing : End Using
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() Using Nothing : M() : End Using
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() Using Nothing : While True : End While : End Using
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
End Sub
<Fact()>
Public Sub MoreLambdasAndSingleLineIfs()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Dim y = Sub() If False Then Else Return Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Dim y = Sub() If False Then Else Return Else
End Module
]]>)
' Dev11 (incorrectly) reports BC30086.
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Dim y = Sub() If False Then Else Else
End Sub
End Module
]]>)
' Dev11 (incorrectly) reports BC30086.
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Dim y = Sub() If False Then Else Else
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Dim y = Sub() If False Then Else Else
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedEOS, "Else").WithLocation(4, 60))
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Dim y = Sub() If False Then Else Else
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
End Sub
<Fact()>
Public Sub IncompleteSingleLineIfs()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then E
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then End E
End Sub
End Module
]]>,
<errors>
<error id="30678" message="'End' statement not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else E
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else End E
End Sub
End Module
]]>,
<errors>
<error id="30678" message="'End' statement not valid."/>
</errors>)
End Sub
<Fact()>
Public Sub SelectOrSelectCase()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() If True Then Return Select o
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() If True Then Else Return Select o
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() If True Then Else Select o
End Sub
End Module
]]>,
<errors>
<error id="30095" message="'Select Case' must end with a matching 'End Select'."/>
</errors>)
End Sub
''' <summary>
''' See reference to Dev10#708061 for ambiguity regarding
''' "End Select" in single-line lambda.
''' </summary>
<Fact()>
Public Sub SelectOrEndSelect()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() Return Select o
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() End Select o
End Sub
End Module
]]>,
<errors>
<error id="30088" message="'End Select' must be preceded by a matching 'Select Case'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() If True Then End Select o
End Sub
End Module
]]>,
<errors>
<error id="30088" message="'End Select' must be preceded by a matching 'Select Case'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() If True Then Else End Select o
End Sub
End Module
]]>,
<errors>
<error id="30088" message="'End Select' must be preceded by a matching 'Select Case'."/>
</errors>)
End Sub
<WorkItem(622712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622712")>
<Fact()>
Public Sub ColonTerminatorWithTrailingTrivia()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : _
:
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return : _
: 'Comment
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() While True : _
: End While
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
End Sub
<WorkItem(623023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623023")>
<Fact()>
Public Sub SingleLineIfWithinNestedSingleLineBlocks()
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub() If True Then Return End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub() If True Then Return _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub() If True Then Else Return End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub() If True Then Else Return _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Dim y = Sub() If True Then Else Return End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If False Then Dim y = Sub() If True Then If False Then Else Return End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If False Then Else Dim y = Sub() If True Then If False Then Return _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Function() (Sub() If True Then Else))
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Function() (Sub() If True Then If False Then Else))
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then Else Dim y = (Sub() If True Then Else))
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Dim x = (Sub() If False Then Else) Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Dim x = (Sub() If False Then Else)
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Dim x = (Sub() If False Then If True Then Else If False Then Else) Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() (Sub() If True Then While True : If False Then Else)
End Module
]]>,
<errors>
<error id="30082" message="'While' must end with a matching 'End While'."/>
<error id="30198" message="')' expected."/>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub()
Dim y = (Sub() If True Then Else)
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub()
Dim y = Sub() If True Then Else Return _
End Sub
End Module
]]>,
<errors>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="30201" message="Expression expected."/>
</errors>)
End Sub
''' <summary>
''' Consecutive colons are handled differently by the
''' scanner if the colons are on the same line vs.
''' separate lines with line continuations.
''' </summary>
<WorkItem(634703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634703")>
<Fact>
Public Sub MultipleColons()
CheckMethodStatementsAndTrivia(<![CDATA[
Module M
Sub M()
Return : : :
End Sub
End Module
]]>,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubBlock,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ReturnStatement,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndSubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.EndModuleStatement)
CheckMethodStatementsAndTrivia(<![CDATA[
Module M
Sub M()
Return : _
: _
:
End Sub
End Module
]]>,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubBlock,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ReturnStatement,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.LineContinuationTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.LineContinuationTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndSubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.EndModuleStatement)
CheckMethodStatementsAndTrivia(<![CDATA[
Module M
Sub M()
If True Then Return : : :
End Sub
End Module
]]>,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubBlock,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SingleLineIfStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.ReturnStatement,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.EmptyStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndSubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.EndModuleStatement)
CheckMethodStatementsAndTrivia(<![CDATA[
Module M
Sub M()
If True Then Return : _
: _
:
End Sub
End Module
]]>,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubBlock,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SingleLineIfStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.ReturnStatement,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.LineContinuationTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EmptyStatement,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.LineContinuationTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EmptyStatement,
SyntaxKind.ColonTrivia,
SyntaxKind.EmptyStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndSubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.EndModuleStatement)
End Sub
Private Sub CheckMethodStatementsAndTrivia(source As Xml.Linq.XCData, ParamArray expectedStatementsAndTrivia() As SyntaxKind)
Dim tree = ParseAndVerify(source.Value.Trim())
Dim actualStatementsAndTrivia = tree.GetRoot().
DescendantNodesAndSelf().
Where(Function(n) TypeOf n Is StatementSyntax).
SelectMany(Function(s) s.GetLeadingTrivia().Select(Function(trivia) trivia.Kind()).Concat({s.Kind()}).Concat(s.GetTrailingTrivia().Select(Function(trivia) trivia.Kind()))).
ToArray()
CheckArray(actualStatementsAndTrivia, expectedStatementsAndTrivia)
End Sub
''' <summary>
''' Scanner needs to handle comment trivia at the start of a statement,
''' even when the statement is not the first on the line.
''' </summary>
<Fact()>
Public Sub CommentAtStartOfStatementNotFirstOnLine()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return :'Comment
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return :rem
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : REM Comment
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : _
REM Comment
End Module
]]>)
End Sub
<WorkItem(638187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638187")>
<Fact()>
Public Sub IsNextStatementInsideLambda()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
Return :
Sub F()
End Sub
End Module
]]>,
<errors>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
10:
Sub F()
End Sub
End Module
]]>,
<errors>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
10: Sub F()
End Sub
End Module
]]>,
<errors>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="32009"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
10
Sub F()
End Sub
End Module
]]>,
<errors>
<error id="30801"/>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return :
Sub F()
End Sub
End Module
]]>)
End Sub
<Fact()>
Public Sub IsNextStatementInsideLambda_2()
ParseAndVerify(<![CDATA[
Module M
Sub M()
For i = 0 To 5
Dim x = Sub()
10: Call M()
Next
End Sub
End Sub
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For i = 0 To 5
Dim x = Sub()
10:
Next
End Sub
End Sub
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For i = 0 To 5
Dim x = Sub()
10: Next
End Sub
End Sub
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For i = 0 To 5
Dim x = Sub()
10 Next
End Sub
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="30801"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Sub()
Finally
End Sub
End Try
End Sub
End Module
]]>,
<errors>
<error id="30384"/>
<error id="36673"/>
<error id="30383"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Sub()
10:
Finally
End Sub
End Try
End Sub
End Module
]]>,
<errors>
<error id="30384"/>
<error id="36673"/>
<error id="30383"/>
<error id="30429"/>
</errors>)
End Sub
''' <summary>
''' Should parse (and report errors in) a statement
''' following a label even if the label is invalid.
''' Currently, any statement on the same line as
''' the invalid label is ignored.
''' </summary>
<WorkItem(642558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642558")>
<Fact()>
Public Sub ErrorInStatementFollowingInvalidLabel()
ParseAndVerify(<![CDATA[
Module M
Sub M()
10
Call
End Sub
End Module
]]>,
<errors>
<error id="30801"/>
<error id="30201"/>
</errors>)
' Dev11 reports 30801 and 30201.
ParseAndVerify(<![CDATA[
Module M
Sub M()
10 Call
End Sub
End Module
]]>,
<errors>
<error id="30801"/>
</errors>)
End Sub
<Fact()>
Public Sub LabelsFollowedByStatementsWithTrivia()
ParseAndVerify(<![CDATA[
Module M
Sub M()
10: 'Comment
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
10: _
_
:
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
10'Comment
End Sub
End Module
]]>,
<errors>
<error id="30801"/>
</errors>)
End Sub
<WorkItem(640520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640520")>
<Fact()>
Public Sub Bug640520()
ParseAndVerify(<![CDATA[
Class C
Sub M()
End : Sub
Public Custom Event E
End Event
End Class
]]>,
<errors>
<error id="30026"/>
<error id="30289"/>
<error id="32009"/>
<error id="30026"/>
<error id="30203"/>
<error id="30289"/>
<error id="31122"/>
<error id="31123"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Sub M()
End : Sub
<A> Custom Event E
End Event
End Class
]]>,
<errors>
<error id="30026"/>
<error id="30289"/>
<error id="32009"/>
<error id="30026"/>
<error id="30203"/>
<error id="30289"/>
<error id="31122"/>
<error id="31123"/>
</errors>)
End Sub
<WorkItem(648998, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/648998")>
<Fact()>
Public Sub Bug648998()
Dim tree = Parse(<![CDATA[
Module M
Dim x = F(a:=False,
Dim y, z = Nothing
End Module
]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
tree.AssertTheseDiagnostics(<errors><![CDATA[
BC30201: Expression expected.
Dim y, z = Nothing
~
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
Dim y, z = Nothing
~
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
Dim y, z = Nothing
~~~~~~~~~~~
BC30198: ')' expected.
Dim y, z = Nothing
~
]]></errors>)
tree = Parse(<![CDATA[
Module M
Dim x = F(a:=False,
Dim y()
End Module
]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
tree.AssertTheseDiagnostics(<errors><![CDATA[
BC30201: Expression expected.
Dim y()
~
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
Dim y()
~
]]></errors>)
tree = Parse(<![CDATA[
Module M
Dim x = F(a:=False,
Dim y
End Module
]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
tree.AssertTheseDiagnostics(<errors><![CDATA[
BC30201: Expression expected.
Dim y
~
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
Dim y
~
BC30198: ')' expected.
Dim y
~
]]></errors>)
tree = Parse(<![CDATA[
Module M
Dim x = F(a:=False,
b True,
c:=Nothing)
End Module
]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
tree.AssertTheseDiagnostics(<errors><![CDATA[
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
b True,
~
BC32017: Comma, ')', or a valid expression continuation expected.
b True,
~~~~
BC30198: ')' expected.
b True,
~
BC30201: Expression expected.
b True,
~
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
b True,
~
BC30188: Declaration expected.
c:=Nothing)
~
]]></errors>)
End Sub
<WorkItem(649162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649162")>
<Fact()>
Public Sub Bug649162()
ParseAndVerify(<![CDATA[
Imports <xmlns:=''>, Imports <xmlns::=''>, Imports <xmlns==''>
]]>,
<errors>
<error id="31146"/>
<error id="30183"/>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <xmlns:=''>, Imports <xmlns::=''>, Imports <xmlns==''>
]]>.Value.Replace(":"c, FULLWIDTH_COLON).Replace("="c, FULLWIDTH_EQUALS_SIGN),
<errors>
<error id="31187"/>
<error id="30636"/>
<error id="31170"/>
<error id="30183"/>
<error id="30035"/>
</errors>)
End Sub
<WorkItem(650318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650318")>
<Fact()>
Public Sub Bug650318()
ParseAndVerify(<![CDATA[
Module M
Sub M()
x ::= Nothing
End Sub
End Module
]]>,
<errors>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
x : : = Nothing
End Sub
End Module
]]>,
<errors>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
x : : = Nothing
End Sub
End Module
]]>.Value.Replace(":"c, FULLWIDTH_COLON).Replace("="c, FULLWIDTH_EQUALS_SIGN),
<errors>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
::= Nothing
End Sub
End Module
]]>,
<errors>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
::= Nothing
End Sub
End Module
]]>.Value.Replace(":"c, FULLWIDTH_COLON).Replace("="c, FULLWIDTH_EQUALS_SIGN),
<errors>
<error id="30035"/>
</errors>)
End Sub
<WorkItem(671115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/671115")>
<Fact()>
Public Sub IsNewLine()
Dim sourceFormat = "Module M{0} Dim x = 1 'Comment{0}End Module{0}"
ParseAndVerify(String.Format(sourceFormat, CARRIAGE_RETURN))
ParseAndVerify(String.Format(sourceFormat, LINE_FEED))
ParseAndVerify(String.Format(sourceFormat, NEXT_LINE))
ParseAndVerify(String.Format(sourceFormat, LINE_SEPARATOR))
ParseAndVerify(String.Format(sourceFormat, PARAGRAPH_SEPARATOR))
End Sub
<WorkItem(674590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674590")>
<Fact()>
Public Sub Bug674590()
ParseAndVerify(<![CDATA[
Class C
Shared Operator</
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Shared Operator %>
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Shared Operator <!--
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Shared Operator <? 'Comment
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Shared Operator <![CDATA[ _
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Shared Operator <!DOCTYPE
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<source>
Class C
Shared Operator ]]>
End Operator
End Class
</source>.Value,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(684860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684860")>
<Fact()>
Public Sub Bug684860_SkippedTokens()
Const n = 100000
' 100000 instances of "0+" in:
' Class C
' Dim x = M(0 0+0+0+...)
' End Class
Dim builder = New System.Text.StringBuilder()
builder.AppendLine("Class C")
builder.Append(" Dim x = M(0 ")
For i = 0 To n
builder.Append("0+")
Next
builder.AppendLine(")")
builder.AppendLine("End Class")
Dim text = builder.ToString()
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim root = tree.GetRoot()
Dim walker = New TokenAndTriviaWalker()
walker.Visit(root)
Assert.True(walker.Tokens > n)
Dim tokens1 = root.DescendantTokens(descendIntoTrivia:=False).ToArray()
Dim tokens2 = root.DescendantTokens(descendIntoTrivia:=True).ToArray()
Assert.True((tokens2.Length - tokens1.Length) > n)
End Sub
<WorkItem(684860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684860")>
<Fact()>
Public Sub Bug684860_XmlText()
Const n = 100000
' 100000 instances of "<" in:
' ''' <x a="<<<..."/>
' Class C
' End Class
Dim builder = New System.Text.StringBuilder()
builder.Append("''' <x a=""")
For i = 0 To n
builder.Append("<")
Next
builder.AppendLine("""/>")
builder.AppendLine("Class C")
builder.AppendLine("End Class")
Dim text = builder.ToString()
Dim tree = VisualBasicSyntaxTree.ParseText(text, options:=New VisualBasicParseOptions(documentationMode:=DocumentationMode.Parse))
Dim root = tree.GetRoot()
Dim walker = New TokenAndTriviaWalker()
walker.Visit(root)
Assert.True(walker.Tokens > n)
Dim tokens = root.DescendantTokens(descendIntoTrivia:=True).ToArray()
Assert.True(tokens.Length > n)
End Sub
Private NotInheritable Class TokenAndTriviaWalker
Inherits VisualBasicSyntaxWalker
Public Tokens As Integer
Public Sub New()
MyBase.New(SyntaxWalkerDepth.StructuredTrivia)
End Sub
Public Overrides Sub VisitToken(token As SyntaxToken)
Tokens += 1
MyBase.VisitToken(token)
End Sub
End Class
<WorkItem(685268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685268")>
<Fact()>
Public Sub Bug685268()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then Sub M()
Return
End Sub
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
<error id="30429"/>
</errors>)
End Sub
<WorkItem(685474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685474")>
<Fact()>
Public Sub Bug685474()
ParseAndVerify(<![CDATA[
<A(Sub()
End Su
b
]]>,
<errors>
<error id="36673"/>
<error id="30678"/>
<error id="30198"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
<A(Sub()
End Su
b
'One
'Two
]]>,
<errors>
<error id="36673"/>
<error id="30678"/>
<error id="30198"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(697117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697117")>
<Fact()>
Public Sub Bug697117()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Return Function()
Declare Function F()
]]>,
<errors>
<error id="30625"/>
<error id="30026"/>
<error id="36674"/>
<error id="30289"/>
<error id="30218"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Return Function()
Delegate Function F()
]]>,
<errors>
<error id="30625"/>
<error id="30026"/>
<error id="36674"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Return Function()
Delegate Sub F()
End Module
]]>,
<errors>
<error id="30026"/>
<error id="36674"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function()
Declare Function F()
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
<error id="30218"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function()
Delegate Function F()
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() Declare Sub F()
End Module
]]>,
<errors>
<error id="30289"/>
<error id="30218"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() Delegate Sub F()
End Module
]]>,
<errors>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() Imports I
End Module
]]>,
<errors>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
Imports I
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
If True Then Imports I
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Delegate Function F()
End Module
]]>,
<errors>
<error id="30026"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub()
If True Then Delegate Function F()
End Module
]]>,
<errors>
<error id="30026"/>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Delegate Function F()
End Module
]]>,
<errors>
<error id="30026"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Delegate Sub F()
End Module
]]>,
<errors>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then Else Delegate Sub F()
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() If True Then Else Delegate Function F()
End Module
]]>,
<errors>
<error id="30026"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then Return : Event E
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
If True Then Return : Inherits I
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then Else Property P
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub() If True Then Else Implements I
End Class
]]>,
Diagnostic(ERRID.ERR_InvInsideProc, "Implements I").WithLocation(3, 37))
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
If True Then Else Imports I
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then If False Then Else Return : Private Class C
End Class
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then Else Return : _
Friend Protected Enum E
End Enum
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
If True Then Else Return : _
Option Strict On
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Function F()
Return Sub()
Return : Implements I
End Function
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
Return : _
Imports I
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Function F()
Using Nothing
Return Sub()
Return : End Using
End Sub
End Function
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Sub M()
Using Nothing
Dim x = Sub() If True Then End Using
End Sub
End Class
]]>,
<errors>
<error id="36008"/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Sub M()
Try
Dim x = Sub() If True Then Catch e
End Try
End Sub
End Class
]]>,
<errors>
<error id="30380"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Sub M()
If True Then
Dim x = Sub() Else
End If
End Sub
End Class
]]>,
<errors>
<error id="30086"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub() <A>Delegate Sub D()
End Class
]]>,
<errors>
<error id="32035"/>
<error id="30660"/>
<error id="30183"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub() If True Then Return : <A> Property P
End Class
]]>,
<errors>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub() If True Then Else <A> Property P
End Class
]]>,
Diagnostic(ERRID.ERR_InvInsideEndsProc, "<A> Property P").WithLocation(3, 37))
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
If True Then Return : _
<A>
Enum E
End Enum
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
End Sub
<WorkItem(716242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716242")>
<Fact()>
Public Sub Bug716242()
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
Select Case x
Delegate Function F()
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30095"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub() Select Case x : _
Delegate Function F()
End Class
]]>,
<errors>
<error id="30095"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
Select Case x
Option Strict On
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30095"/>
<error id="30058"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Function F()
Return Sub() If True Then Select Case x : _
Implements I
End Function
End Class
]]>,
<errors>
<error id="30095"/>
<error id="30058"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Sub M()
Using Nothing
Dim x = Sub()
Select Case x
End Using
End Sub
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30095"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
Select Case x
<A>
Enum E
End Enum
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30095"/>
</errors>)
End Sub
Private Shared Sub CheckArray(Of T)(actual As T(), ParamArray expected As T())
Assert.Equal(expected.Length, actual.Length)
For i = 0 To actual.Length - 1
Assert.Equal(expected(i), actual(i))
Next
End Sub
<WorkItem(539515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539515")>
<Fact()>
Public Sub ParseIllegaLineCont()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
_
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_LineContWithCommentOrNoPrecSpace, "_").WithLocation(4, 1)
)
End Sub
<WorkItem(539515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539515")>
<Fact()>
Public Sub ParseIllegaLineCont_1()
ParseAndVerify(
<![CDATA[
Module M
Sub Main() _
_
_
_
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_LineContWithCommentOrNoPrecSpace, "_").WithLocation(6, 1)
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithNoSpaceBeforeCommentV16()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _' Comment
= 1
End Sub
End Module
]]>, New VisualBasicParseOptions(LanguageVersion.VisualBasic16)
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithMultipleSpacesBeforeCommentV16()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _ ' Comment
= 1
End Sub
End Module
]]>, New VisualBasicParseOptions(LanguageVersion.VisualBasic16)
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithCommentV16()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _ ' Comment
= 1
End Sub
End Module
]]>, New VisualBasicParseOptions(LanguageVersion.VisualBasic16)
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithCommentV15()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _ ' Comment
= 1
End Sub
End Module
]]>, New VisualBasicParseOptions(LanguageVersion.VisualBasic15),
Diagnostic(ERRID.ERR_CommentsAfterLineContinuationNotAvailable1, "' Comment").WithLocation(4, 36).WithArguments("16")
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithCommentV15_5()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _ ' Comment
= 1
End Sub
End Module
]]>, New VisualBasicParseOptions(LanguageVersion.VisualBasic15_5),
Diagnostic(ERRID.ERR_CommentsAfterLineContinuationNotAvailable1, "' Comment").WithLocation(4, 36).WithArguments("16")
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithoutComment()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _
= 1
End Sub
End Module
]]>
)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_01()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
If val Is Nothing Then r = "null" System.Console.WriteLine(1)
If val Is Nothing Then r = Function() "null" System.Console.WriteLine(2)
If val Is Nothing Then r = "+" Else r = "-" System.Console.WriteLine(3)
If val Is Nothing Then r = "+" Else r = Function() "-" System.Console.WriteLine(4)
If val Is Nothing Then : System.Console.WriteLine(5)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then r = "null" System.Console.WriteLine(1)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = Function() "null" System.Console.WriteLine(2)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else r = "-" System.Console.WriteLine(3)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else r = Function() "-" System.Console.WriteLine(4)
~~~~~~
BC30081: 'If' must end with a matching 'End If'.
If val Is Nothing Then : System.Console.WriteLine(5)
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_02()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test2(val As Object)
Dim r As Object
If val Is Nothing Then r = "+" Else : System.Console.WriteLine(6)
r = Sub() If val Is Nothing Then r = "null" System.Console.WriteLine(7)
r = Sub() If val Is Nothing Then r = "+" Else r = "-" System.Console.WriteLine(8)
r = Sub() If val Is Nothing Then r = "null" : System.Console.WriteLine(9)
r = Sub() If val Is Nothing Then r = "+" Else r = "-" : System.Console.WriteLine(10)
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(11)
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(12) Else
If val Is Nothing Then r = Function() "+" Else r = "-" System.Console.WriteLine(13)
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(14) Else
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then r = "null" System.Console.WriteLine(7)
~~~~~~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then r = "+" Else r = "-" System.Console.WriteLine(8)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(12) Else
~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = Function() "+" Else r = "-" System.Console.WriteLine(13)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(14) Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_03()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test3(val As Object)
Dim r As Object
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
End If
End Sub
Sub Test4(val As Object)
Dim r As Object
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
~~~~
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_04()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test5(val As Object)
Dim r As Object
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(17) : Else
End If
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(18) : Else
End If
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(19)
Else
End If
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(20)
Else
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(17) : Else
~~~~
BC36918: Single-line statement lambdas must include exactly one statement.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(18) : Else
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(18) : Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_05()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test3(val As Object)
Dim r As Object
If val Is Nothing Then
ElseIf val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
End If
End Sub
Sub Test4(val As Object)
Dim r As Object
If val Is Nothing Then
ElseIf val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
~~~~
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_06()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test3(val As Object)
Dim r As Object
If val Is Nothing Then
Else
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
End If
End Sub
Sub Test4(val As Object)
Dim r As Object
If val Is Nothing Then
Else
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
~~~~
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_07()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(1) Else
End Sub
Sub Test2(val As Object)
Dim r As Object
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(2) Else
End Sub
Sub Test3(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(3) Else
End If
End Sub
Sub Test4(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(4) Else
End If
End Sub
Sub Test5(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(5) : Else
End If
End Sub
Sub Test6(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(6) : Else
End If
End Sub
Sub Test7(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(7)
Else
End If
End Sub
Sub Test8(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(8)
Else
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(1) Else
~~~~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(2) Else
~~~~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(3) Else
~~~~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(4) Else
~~~~
BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(5) : Else
~~~~
BC36918: Single-line statement lambdas must include exactly one statement.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(6) : Else
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(6) : Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_08()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
If val Is Nothing Then r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(1) Else System.Console.WriteLine(1)
If val Is Nothing Then r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(2) Else System.Console.WriteLine(2)
If val Is Nothing Then r = Sub() r = "-" Else System.Console.WriteLine(3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_09()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
If val Is Nothing Then r = Sub() System.Console.WriteLine(1) ,
If val Is Nothing Then r = Sub() If val Is Nothing Then System.Console.WriteLine(2) ,
If val Is Nothing Then r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(3) ,
r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(4) ,
r = Sub() r = Sub()
If val Is Nothing Then r = "+" Else System.Console.WriteLine(5) ,
End Sub
r = Function() Function()
If val Is Nothing Then r = "+" Else System.Console.WriteLine(6) ,
return 0
End Function
r = Sub() r = Sub()
If val Is Nothing Then System.Console.WriteLine(7) ,
End Sub
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() System.Console.WriteLine(1) ,
~
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() If val Is Nothing Then System.Console.WriteLine(2) ,
~
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(3) ,
~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(4) ,
~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else System.Console.WriteLine(5) ,
~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else System.Console.WriteLine(6) ,
~
BC30205: End of statement expected.
If val Is Nothing Then System.Console.WriteLine(7) ,
~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_10()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
If val Is Nothing Then r = Sub() System.Console.WriteLine(1) System.Console.WriteLine(1)
If val Is Nothing Then r = Sub() If val Is Nothing Then System.Console.WriteLine(2) System.Console.WriteLine(2)
If val Is Nothing Then r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(3) System.Console.WriteLine(3)
r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(4) System.Console.WriteLine(4)
r = Sub() r = Sub()
If val Is Nothing Then r = "+" Else System.Console.WriteLine(5) System.Console.WriteLine(5)
End Sub
r = Function() Function()
If val Is Nothing Then r = "+" Else System.Console.WriteLine(6) System.Console.WriteLine(6)
return 0
End Function
r = Sub() r = Sub()
If val Is Nothing Then System.Console.WriteLine(7) System.Console.WriteLine(7)
End Sub
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() System.Console.WriteLine(1) System.Console.WriteLine(1)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() If val Is Nothing Then System.Console.WriteLine(2) System.Console.WriteLine(2)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(3) System.Console.WriteLine(3)
~~~~~~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(4) System.Console.WriteLine(4)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else System.Console.WriteLine(5) System.Console.WriteLine(5)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else System.Console.WriteLine(6) System.Console.WriteLine(6)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then System.Console.WriteLine(7) System.Console.WriteLine(7)
~~~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_11()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
r = Function() Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(1) Else System.Console.WriteLine(1)
If val Is Nothing Then r = Function() Sub() If val Is Nothing Then r = "-" Else System.Console.WriteLine(2) Else System.Console.WriteLine(2)
If val Is Nothing Then If val Is Nothing Then If val Is Nothing Then If val Is Nothing Then r = "3" Else Else Else Else System.Console.WriteLine(3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
r = Function() Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(1) Else System.Console.WriteLine(1)
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_12()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim d = Test1()()
d(Nothing)
d(d)
Test2(Nothing)
Test2(d)
d = test3()
d(Nothing)
d(d)
End Sub
Function Test1() As System.Func(Of System.Action(Of Object))
Dim r As System.Func(Of System.Action(Of Object))
r = Function() Sub(val As Object)
If val Is Nothing Then System.Console.WriteLine("Then") Else Equals ("Else")
End Sub
return r
End Function
Sub Equals(x as String)
System.Console.WriteLine(x)
End Sub
Sub Test2(val As Object)
If val Is Nothing Then System.Console.WriteLine("Then 2") Else Equals ("Else 2")
End Sub
Function Test3() As System.Action(Of Object)
Dim r As System.Action(Of Object)
r = Sub(val As Object) If val Is Nothing Then System.Console.WriteLine("Then 3") Else Equals ("Else 3")
return r
End Function
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
CompileAndVerify(compilation, expectedOutput:=
"Then
Else
Then 2
Else 2
Then 3
Else 3")
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_13()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1()
Dim d1 = Function(val1) If val1 Is Nothing Then Return 1, b1 = 0
Dim d2 = Function(val2) If (val2 Is Nothing) Then Return 2, b2 = 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30199: '(' expected.
Dim d1 = Function(val1) If val1 Is Nothing Then Return 1, b1 = 0
~
BC33104: 'If' operator requires either two or three operands.
Dim d2 = Function(val2) If (val2 Is Nothing) Then Return 2, b2 = 0
~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_14()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim d1 = Function(val1) If val1 Is Nothing Then Return 1 Else Return 2, b1 = 3
Dim d2 = Function(val2) If (val2 Is Nothing) Then Return 3 Else Return 4, b2 = 5
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30199: '(' expected.
Dim d1 = Function(val1) If val1 Is Nothing Then Return 1 Else Return 2, b1 = 3
~
BC33104: 'If' operator requires either two or three operands.
Dim d2 = Function(val2) If (val2 Is Nothing) Then Return 3 Else Return 4, b2 = 5
~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_15()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Function Test1(val1) As System.Func(Of Object)
If val1 Is Nothing Then Return Function(val2) If val2 Is Nothing Then Return 1 Else Return 2 Else Return Nothing
End Function
Function Test2(val1) As System.Func(Of Object)
If val1 Is Nothing Then Return Function(val2) If (val2 Is Nothing) Then Return 1 Else Return 2 Else Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30199: '(' expected.
If val1 Is Nothing Then Return Function(val2) If val2 Is Nothing Then Return 1 Else Return 2 Else Return Nothing
~
BC42105: Function 'Test1' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
BC33104: 'If' operator requires either two or three operands.
If val1 Is Nothing Then Return Function(val2) If (val2 Is Nothing) Then Return 1 Else Return 2 Else Return Nothing
~
BC42105: Function 'Test2' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
<WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")>
Public Sub ParseLineIfWithIncompleteInterpolatedString_01()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Test1(val1 As Integer)
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'")
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30625: 'Module' statement must end with a matching 'End Module'.
Module Module1
~~~~~~~~~~~~~~
BC30026: 'End Sub' expected.
Sub Test1(val1 As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30451: 'sServiceName' is not declared. It may be inaccessible due to its protection level.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'")
~~~~~~~~~~~~
BC30370: '}' expected.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'")
~
BC30198: ')' expected.
End Module
~
]]></expected>)
End Sub
<Fact>
<WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")>
Public Sub ParseLineIfWithIncompleteInterpolatedString_02()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Test1(val1 As Integer)
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"})
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30625: 'Module' statement must end with a matching 'End Module'.
Module Module1
~~~~~~~~~~~~~~
BC30026: 'End Sub' expected.
Sub Test1(val1 As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30451: 'sServiceName' is not declared. It may be inaccessible due to its protection level.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"})
~~~~~~~~~~~~
BC30198: ')' expected.
End Module
~
]]></expected>)
End Sub
<Fact>
<WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")>
Public Sub ParseLineIfWithIncompleteInterpolatedString_03()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Test1(val1 As Integer)
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"}")
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30451: 'sServiceName' is not declared. It may be inaccessible due to its protection level.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"}")
~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact>
<WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")>
Public Sub ParseLineIfWithIncompleteInterpolatedString_04()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Test1(val1 As Integer)
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'" ")
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30451: 'sServiceName' is not declared. It may be inaccessible due to its protection level.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'" ")
~~~~~~~~~~~~
BC30370: '}' expected.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'" ")
~
]]></expected>)
End Sub
<Fact>
<WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")>
Public Sub ParseLineIfWithIncompleteInterpolatedString_05()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Test1(val1 As Integer)
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"")
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30625: 'Module' statement must end with a matching 'End Module'.
Module Module1
~~~~~~~~~~~~~~
BC30026: 'End Sub' expected.
Sub Test1(val1 As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30451: 'sServiceName' is not declared. It may be inaccessible due to its protection level.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"")
~~~~~~~~~~~~
BC30648: String constants must end with a double quote.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"")
~~~~~~
BC30198: ')' expected.
End Module
~
BC30370: '}' expected.
End Module
~
]]></expected>)
End Sub
End Class
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports Roslyn.Test.Utilities
<CLSCompliant(False)>
Public Class ParseStatements
Inherits BasicTestBase
<Fact>
Public Sub ParseIf()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
if true then f() else if true then g()
If True
End If
If True Then
End If
If True Then
Else
End If
If True Then
ElseIf False Then
End If
If True Then
ElseIf False Then
Else
End If
if true then else
if true then else :
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseDo()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
Do
Loop
do while true
loop
do until true
loop
do
loop until true
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseWhile()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
dim x = 1
while x < 1
end while
with x
end with
synclock x
end synclock
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseFor()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
for i = 0 to 100
next
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseForEach()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
for each c in "hello"
next
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseSelect()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
select i
case 0
case 1
case 2
case else
end select
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseTry()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
try
catch
finally
end try
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseUsing()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
using e0
end using
using e1 as new C, e2 as new C
end using
using e3 as new with {.goo="bar"}
end using
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseUsingMultipleVariablesInAsNew()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
dim a, b as new C
using e1, e2 as new C, e3 as new C
end using
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseContinue()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
do
continue do
loop
while true
continue do
end while
for i = 0 to 10
continue for
next
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseExit()
ParseAndVerify(<![CDATA[
Module Module1
Sub s1()
do
exit do
loop
while true
exit while
end while
for i = 0 to 10
exit for
next
select 0
case 0
exit select
end select
try
exit try
catch
end try
Exit sub
end sub
function f1() as integer
exit function
end function
readonly property p1 as integer
get
exit property
end get
end property
End Module
]]>)
End Sub
<WorkItem(538594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538594")>
<Fact>
Public Sub ParseOnErrorGoto()
ParseAndVerify(<![CDATA[
Module Module1
Sub s1()
on error goto 0
on error goto 0UL
on error goto -1
on error goto -1UL
on error goto mylabel
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseResume()
ParseAndVerify(<![CDATA[
Module Module1
Sub s1()
resume next
resume mylabel
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseCallStatement()
ParseAndVerify(<![CDATA[
Module Module1
Sub s1()
call mysub(of string)(1,2,3,4)
end sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseRedim()
ParseAndVerify(<![CDATA[
Class c1
Dim a(,) As Integer
Sub s()
Dim a() As c1
ReDim a(10)
ReDim a(0 To 10)
ReDim Preserve a(10)
ReDim Preserve a(10).a(0 To 10, 0 To 20)
' the following is actually wrong according to the grammar
' but VB10 parses it, so we will too for now.
ReDim Preserve a(0 To 10).a(0 To 10, 0 To 20)
End Sub
End Class
]]>)
End Sub
<Fact>
Public Sub ParseReturn_Bug868414()
'Bug 868414 - Exception when return is missing expression.
ParseAndVerify(<![CDATA[
Class Class1
Function Goo() As Integer
Return
End Function
End Class
]]>)
End Sub
<Fact>
Public Sub ParseAssignmentOrCall()
ParseAndVerify(<![CDATA[
class c1
sub s
i = 1
i(10)
end sub
end class
]]>)
End Sub
<WorkItem(871360, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineIfThen()
ParseAndVerify(<![CDATA[
Class Class1
Function Goo() As Boolean
Return True
End Function
Sub Bar()
If Goo() = True Then Return True
If Goo() <> True Then
Return Not True
End If
End Sub
End Class
]]>)
End Sub
<WorkItem(539194, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539194")>
<Fact>
Public Sub ParseSingleLineIfThenWithColon()
' Goo should be a call statement and not a label
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub Main()
If True Then Goo: Else
End Sub
Sub Goo()
End Sub
End Module
]]>)
Dim compUnit = tree.GetRoot()
Dim moduleM = TryCast(compUnit.ChildNodesAndTokens()(0).AsNode, TypeBlockSyntax)
Dim subMain = TryCast(moduleM.ChildNodesAndTokens()(1).AsNode, MethodBlockSyntax)
Dim ifStmt = TryCast(subMain.ChildNodesAndTokens()(1).AsNode, SingleLineIfStatementSyntax)
Dim goo = ifStmt.Statements(0)
Assert.Equal(SyntaxKind.ExpressionStatement, goo.Kind)
Assert.Equal(SyntaxKind.InvocationExpression, DirectCast(goo, ExpressionStatementSyntax).Expression.Kind)
End Sub
<Fact>
Public Sub ParseSingleLineIfThenWithElseIf()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub Main()
If True Then ElseIf True Then x = 2 end if
If True Then x = 1 elseIf true then x = 2 end if
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedEOS, "ElseIf True Then").WithLocation(4, 18),
Diagnostic(ERRID.ERR_ExpectedEOS, "x").WithLocation(4, 35),
Diagnostic(ERRID.ERR_ExpectedEOS, "elseIf").WithLocation(5, 24)
)
End Sub
<WorkItem(539204, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539204")>
<Fact>
Public Sub ParseColonLineCont()
' 2nd Else and ElseIf are dangling in the line ifs
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub Main()
' not an error
Return : _
End Sub
End Module
Module M2
Sub Main2()
' error
Return :_
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_LineContWithCommentOrNoPrecSpace, "_"))
End Sub
<WorkItem(539204, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539204")>
<Fact>
Public Sub ParseSingleLineIfThenExtraElse()
' 2nd Else and ElseIf are dangling in the line ifs
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If True Then Console.WriteLine Else Else Console.WriteLine
If True Then Console.WriteLine Else ElseIf Console.WriteLine
End Sub
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="84" end="88"/>
<error id="36005" message="'ElseIf' must be preceded by a matching 'If' or 'ElseIf'." start="152" end="176"/>
</errors>)
End Sub
<WorkItem(539205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539205")>
<Fact>
Public Sub ParseSingleLineIfWithNestedSingleLineIf()
' This is a valid nested line if in a line if
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If False Then If True Then Else Else Console.WriteLine(1)
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseSingleLineIfWithNestedMultiLineIf1()
' This is a single line if that contains an invalid multi line if.
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If False Then If True Console.WriteLine(1)
End Sub
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="62" end="69"/>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
End Sub
<Fact>
Public Sub ParseSingleLineIfWithNestedMultiLineIf2()
' This is a single line if that contains an invalid multi line if/then/else.
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If False Then If True Else Else Console.WriteLine(1)
End Sub
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="62" end="69"/>
<error id="30205" message="End of statement expected."/>
</errors>)
End Sub
<Fact>
Public Sub ParseSingleLineIfWithNestedMultiLineIf3()
' This is a single line if that contains an invalid multi line if.
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If true Then If True
Console.WriteLine(1)
end if
End Sub
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="61" end="68"/>
<error id="30087" message="'End If' must be preceded by a matching 'If'." start="112" end="118"/>
</errors>)
End Sub
<WorkItem(539207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539207")>
<Fact>
Public Sub ParseSingleLineIfWithNestedDoLoop1()
' This is a single line if that contains an invalid do .. loop
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If true Then do
End Sub
End Module
]]>,
<errors>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="61" end="63"/>
</errors>)
End Sub
<Fact>
Public Sub ParseSingleLineIfWithNestedDoLoop2()
' This is a single line if that contains an invalid do .. loop
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If true Then do
Console.WriteLine(1)
loop
End Sub
End Module
]]>,
<errors>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="61" end="63"/>
<error id="30091" message="'Loop' must be preceded by a matching 'Do'." start="105" end="109"/>
</errors>)
End Sub
<Fact>
Public Sub ParseSingleLineIfWithNestedDoLoop3()
' This is a single line if that contains a valid do loop
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If true Then do : Console.WriteLine(1) : loop
End Sub
End Module
]]>)
End Sub
<WorkItem(539209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539209")>
<Fact>
Public Sub ParseSingleLineSubWithSingleLineIfFollowedByColonComma()
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module Program
Sub Main()
Dim a = Sub() If True Then Dim b = 1 :, c = 2
End Sub
End Module
]]>)
End Sub
<WorkItem(539210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539210")>
<Fact>
Public Sub ParseSingleLineIfFollowedByColonNewLine()
' Per Dev10 the second WriteLine should NOT be part of
' the single line if. This regression was caused by scanner change
' to scan ":" after trivia. The scanner now scans in new statement state after
' the colon and eats up new lines.
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub Main()
If True Then Console.WriteLine(1) :
Console.WriteLine(2)
End Sub
End Module
]]>)
Dim compUnit = tree.GetRoot()
Dim moduleM = TryCast(compUnit.ChildNodesAndTokens()(0).AsNode, TypeBlockSyntax)
Dim subMain = TryCast(moduleM.ChildNodesAndTokens()(1).AsNode, MethodBlockSyntax)
Assert.Equal(4, subMain.ChildNodesAndTokens().Count)
Assert.Equal(SyntaxKind.SingleLineIfStatement, subMain.ChildNodesAndTokens()(1).Kind())
Assert.Equal(SyntaxKind.ExpressionStatement, subMain.ChildNodesAndTokens()(2).Kind())
Assert.Equal(SyntaxKind.InvocationExpression, DirectCast(subMain.ChildNodesAndTokens()(2).AsNode, ExpressionStatementSyntax).Expression.Kind)
End Sub
<Fact>
Public Sub ParseSingleLineIfFollowedByColonNewLine1()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub Main()
dim s1 = sub () If True Then Console.WriteLine(1) :
dim s2 = sub () If True Then Console.WriteLine(1) ::Console.WriteLine(1)::
dim s3 = sub() If True Then Console.WriteLine(1) :::: Console.WriteLine(1)
Console.WriteLine(2)
End Sub
End Module
]]>)
End Sub
<WorkItem(539211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539211")>
<Fact>
Public Sub ParseSingleLineSubWithSingleLineIfFollowedByComma()
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module Program
Sub Main()
Dim a = Sub() If True Then Console.WriteLine, b = 2
End Sub
End Module
]]>)
End Sub
<WorkItem(539211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539211")>
<Fact>
Public Sub ParseSingleLineSubWithSingleLineIfFollowedByParen()
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Module Program
Sub Main()
Dim a = (Sub() If True Then Console.WriteLine), b = 2
End Sub
End Module
]]>)
End Sub
<WorkItem(530904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530904")>
<Fact>
Public Sub SingleLineLambdaComma()
Dim tree = ParseAndVerify(<![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim a(0)
Dim b = Sub() ReDim a(1),
Return
End Sub
End Module
]]>,
<errors>
<error id="30201" message="Expression expected." start="153" end="153"/>
</errors>)
End Sub
<WorkItem(539212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539212")>
<Fact>
Public Sub ParseSingleLineSubWithSingleLineIfWithAnotherSingleLineSub()
' The second single line sub is within a var declaration after the end statement in the then clause!
Dim tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
Dim a = Sub() If True Then End _
: Dim b = Sub() If True Then End Else End Else
End Sub
End Module
]]>)
End Sub
<WorkItem(539212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539212")>
<Fact>
Public Sub ParseSingleLineSubWithIncompleteSingleLineIf()
' Dev10 reports single line if must contain one statement.
Dim tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
Dim a = Sub() If True Then
End Sub
End Module
]]>, Diagnostic(ERRID.ERR_ExpectedEndIf, "If True Then"))
End Sub
<WorkItem(539212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539212")>
<Fact>
Public Sub ParseSubLambdaWithIncompleteSingleLineIf()
' The single line if actually gets parsed as a block if in both dev10 and roslyn
Dim tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
Dim a = Sub()
If True Then
End Sub
End Module
]]>,
<errors>
<error id="30026" message="'End Sub' expected." start="18" end="28"/>
<error id="30081" message="'If' must end with a matching 'End If'." start="56" end="68"/>
</errors>)
End Sub
<WorkItem(871931, "DevDiv/Personal")>
<Fact>
Public Sub ParseErase()
ParseAndVerify(<![CDATA[
Class Class1
Public vobja() As Object
Public Sub Goo()
Erase vobja
End Sub
End Class
]]>)
End Sub
<WorkItem(872003, "DevDiv/Personal")>
<Fact>
Public Sub ParseError()
ParseAndVerify(<![CDATA[
Class Class1
Public Sub Goo()
Error 5
End Sub
End Class
]]>)
End Sub
<WorkItem(872005, "DevDiv/Personal")>
<Fact>
Public Sub ParseLabel()
ParseAndVerify(<![CDATA[
Class Class1
Public Sub Goo()
10: Dim x = 42
End Sub
End Class
]]>)
End Sub
<WorkItem(538606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538606")>
<Fact>
Public Sub LabelFollowedByMethodInvocation()
ParseAndVerify(<![CDATA[
Module M
Sub Main()
Goo : Goo : Goo()
End Sub
Sub Goo()
End Sub
End Module
]]>)
End Sub
<WorkItem(541358, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541358")>
<Fact>
Public Sub LabelRelatedToBug8037()
ParseAndVerify(<![CDATA[
Module M
Sub Main()
#if 1 < 2
label1:
#elseif 2 < 3
label2:
#elseif false
label3:
#end if
label4:
label5:
End Sub
::
#region "goo"
Sub Goo()
End Sub
::
#end region
Sub Goo_()
End Sub
''' <summary>
''' </summary>
:Sub Goo2()
:End Sub
''' <summary>
''' </summary>
Sub Goo2_()
End Sub
:<summary()>
Sub Goo3()
:End Sub
#if false
#end if
Sub Goo4()
:
:End Sub
:' nice little innocent comment
Sub Goo5()
End Sub
#garbage on
Sub Goo6()
End Sub
#Const CustomerNumber = 36
Sub Goo7()
End Sub
End Module
]]>, <errors>
<error id="32009" message="Method declaration statements must be the first statement on a logical line." start="441" end="451"/>
<error id="32009" message="Method declaration statements must be the first statement on a logical line." start="599" end="635"/>
<error id="30248" message="'If', 'ElseIf', 'Else', 'End If', 'Const', or 'Region' expected." start="853" end="854"/>
</errors>)
' doesn't work, most probably because of the line break ...
'Diagnostic(ERRID.ERR_MethodMustBeFirstStatementOnLine, "Sub Goo2()"),
'Diagnostic(ERRID.ERR_MethodMustBeFirstStatementOnLine, "<summary()>" + vbCrLf + " Sub Goo3()"),
'Diagnostic(ERRID.ERR_ExpectedConditionalDirective, "#"))
End Sub
<WorkItem(872013, "DevDiv/Personal")>
<Fact>
Public Sub ParseMid()
ParseAndVerify(<![CDATA[
Class Class1
Public Sub Goo(ByRef r As aType)
Mid$(r.S(2, 2), 1, 1) = "-"
Mid(r.S(2, 2), 1, 1) = "-"
End Sub
End Class
]]>)
End Sub
<WorkItem(542623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542623")>
<Fact>
Public Sub ParseMidIdentifier1()
ParseAndVerify(< = 33
End Sub
Public Sub Mid(p as Integer)
End Sub
End Class
]]>, Diagnostic(ERRID.ERR_ExpectedComma, ""),
Diagnostic(ERRID.ERR_ExpectedExpression, "")
)
End Sub
<WorkItem(542623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542623")>
<Fact>
Public Sub ParseMidIdentifier2()
ParseAndVerify(<
End Sub
End Class
]]>, Diagnostic(ERRID.ERR_ExpectedComma, ""),
Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_ExpectedEQ, ""),
Diagnostic(ERRID.ERR_ExpectedExpression, "")
)
End Sub
<Fact>
Public Sub ParseMidIdentifier3()
ParseAndVerify(<
End Sub
End Class
]]>, Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_ExpectedEQ, ""),
Diagnostic(ERRID.ERR_ExpectedExpression, "")
)
End Sub
<Fact>
Public Sub ParseMidIdentifier4()
ParseAndVerify(<![CDATA[
Class Mid
Public Sub Mid(p as Integer)
Mid(23, 24,
End Sub
End Class
]]>, Diagnostic(ERRID.ERR_ExpectedExpression, ""),
Diagnostic(ERRID.ERR_ExpectedRparen, ""),
Diagnostic(ERRID.ERR_ExpectedEQ, ""),
Diagnostic(ERRID.ERR_ExpectedExpression, "")
)
End Sub
<WorkItem(872018, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineIfThenElse()
ParseAndVerify(<![CDATA[
Class Class1
Sub Method1()
Dim IsSA As Short
If True Then IsSA = True Else IsSA = False
End Sub
End Class
]]>)
End Sub
<WorkItem(872030, "DevDiv/Personal")>
<Fact>
Public Sub ParseRedimClauses()
ParseAndVerify(<![CDATA[
Module Module1
Function FUN1%()
Dim C21#(), C22#(,), C23#()
ReDim C21#(1), C22#(2, 1), C23#(2)
End Function
End Module
]]>)
End Sub
<WorkItem(872034, "DevDiv/Personal")>
<Fact>
Public Sub ParseForNext()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
For i = 0 To 1
For j = 0 To 1
Next j, i
End Sub
End Module
]]>)
End Sub
<WorkItem(872042, "DevDiv/Personal")>
<Fact>
Public Sub ParseWhen()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Try
Catch e As InvalidCastException When (Bln = True)
End Try
End Sub
End Module
]]>)
End Sub
<WorkItem(873525, "DevDiv/Personal")>
<Fact>
Public Sub ParseAndAlsoInOrElseArgumentList()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo(ByVal x As Boolean)
End Sub
Function Bar() As Boolean
End Function
Sub Main()
Goo(True AndAlso Bar())
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo(ByVal x As Boolean)
End Sub
Function Bar() As Boolean
End Function
Sub Main()
Goo(False OrElse Bar())
End Sub
End Module
]]>)
End Sub
<WorkItem(873526, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineIfThenWithFollowingStatement()
ParseAndVerify(<![CDATA[
Class c1
Sub goo()
If True Then goo()
bar()
End Sub
End Class
]]>)
End Sub
<WorkItem(874045, "DevDiv/Personal")>
<Fact>
Public Sub ParseEnd()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
End
End Sub
End Module
]]>)
End Sub
<WorkItem(874054, "DevDiv/Personal")>
<Fact>
Public Sub ParseForEachControlVariableArray()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim files()() As String = {New String() {"Template0.bmp", "Template0.txt"}}
For Each fs() As String In files
Next fs
End Sub
End Module
]]>)
End Sub
<WorkItem(874067, "DevDiv/Personal")>
<Fact>
Public Sub ParseQuerySelectWithInitializerFollowedByFrom()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim q = From i In {} Select p = New Object From j In {} Select j
End Sub
End Module
]]>)
End Sub
<WorkItem(874074, "DevDiv/Personal")>
<Fact>
Public Sub ParseExtensionMethodInvokeOnLiteral()
ParseAndVerify(<![CDATA[
<System.Runtime.CompilerServices.Extension()>
Module Module1
Sub Main()
Dim r = 42.IntegerExtension()
Dim r = 42.BAD
End Sub
<System.Runtime.CompilerServices.Extension()>
Function IntegerExtension(i As Integer) As Boolean
Return True
End Function
End Module
]]>)
End Sub
<WorkItem(874120, "DevDiv/Personal")>
<Fact>
Public Sub ParseDoUntilNested()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Do Until True
Do Until True
Loop
Loop
End Sub
End Module
]]>)
End Sub
<WorkItem(874355, "DevDiv/Personal")>
<Fact>
Public Sub BC31151ERR_MissingXmlEndTag_ParseLessThan()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim a = ( < 13)
End Sub
End Module
]]>,
<errors>
<error id="30198"/>
<error id="30636"/>
<error id="31165"/>
<error id="30035"/>
<error id="31169"/>
<error id="31177"/>
<error id="31151"/>
</errors>)
End Sub
<WorkItem(875188, "DevDiv/Personal")>
<Fact>
Public Sub ParseSelectCaseClauses()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim bytevar
Select Case bytevar
Case Is < 0, Is > 255
End Select
End Sub
End Module
]]>)
End Sub
<WorkItem(875194, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineContinuationWithTrailingWhitespace()
ParseAndVerify(
"Class Class1" & vbCrLf &
" <Obsolete(True)> _ " & vbTab & vbCrLf &
" Sub AnachronisticMethod()" & vbCrLf &
" End Sub" & vbCrLf &
"End Class")
End Sub
<WorkItem(879296, "DevDiv/Personal")>
<Fact>
Public Sub ParseRightShiftEquals()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim i = &H1000
i >>= 1
End Sub
End Module
]]>)
End Sub
<WorkItem(879373, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaFollowedByColon()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = Function() 3 :
End Sub
End Module
]]>)
End Sub
<WorkItem(879385, "DevDiv/Personal")>
<Fact>
Public Sub ParseQueryGroupByIntoWithXmlLiteral()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim col1 As IQueryable = Nothing
Dim q3 = From i In col1 Group el1.<moo>.@attr1, el1.<moo> By el1...<moo> Into G=Group
End Sub
End Module
]]>)
End Sub
<WorkItem(879690, "DevDiv/Personal")>
<Fact>
Public Sub ParseThrow()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Throw
End Sub
End Module
]]>)
End Sub
<WorkItem(536076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536076")>
<Fact>
Public Sub ParseQueryFromNullableRangeVariable()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim col As New Collections.ArrayList()
Dim w3 = From i? As Integer In col
End Sub
End Module
]]>)
End Sub
<WorkItem(880312, "DevDiv/Personal")>
<Fact>
Public Sub ParseEmptyMultilineFunctionLambda()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim f = Function()
End Function
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseEmptyMultilineSubLambda()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim s = Sub()
End Sub
End Sub
End Module
]]>)
End Sub
<WorkItem(881451, "DevDiv/Personal")>
<Fact>
Public Sub ParseQueryIntoAllImplicitLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim i10 = Aggregate el In coll1 Into All(
el <= 5
)
End Sub
End Module
]]>)
End Sub
<WorkItem(881528, "DevDiv/Personal")>
<Fact>
Public Sub ParseMethodInvocationNestedImplicitLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Goo(
GetType(
Integer
)
)
End Sub
End Module
]]>)
End Sub
<WorkItem(881570, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaInvokeDeclaration()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = Function()
Return 42
End Function()
End Sub
End Module
]]>)
End Sub
<WorkItem(881585, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaBodyWithLineIfForEach()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim m1, list2() As Integer
Dim x = Sub() If True Then For Each i In list2 : m1 = i : Exit Sub : Exit For : Next
End Sub
End Module
]]>)
End Sub
<WorkItem(881590, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaDeclarationCommaSeparated()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim s1 = Sub()
End Sub, s2 = Sub() End
End Sub
End Module
]]>)
End Sub
<WorkItem(881597, "DevDiv/Personal")>
<Fact>
Public Sub ParseQueryCollectionExpressionContainsLambda()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x2 = From f In {Sub() Console.WriteLine("Hello")}
Select f
End Sub
End Module
]]>)
End Sub
<WorkItem(531540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531540")>
<Fact>
Public Sub SelectCaseInLambda()
ParseAndVerify(<![CDATA[
Module Program
Sub Main(args As String())
Dim l = Function(m) Function(m3)
Dim num = 10
Select Case num
Case Is = 10
Console.WriteLine("10")
End Select
End Function
End Sub
End Module
]]>)
End Sub
<WorkItem(530633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530633")>
<Fact>
Public Sub SubImplements()
ParseAndVerify(<![CDATA[
Interface I
Property A As Action
End Interface
Class C
Implements I
Property A As Action = Sub() Implements I.A
End Class
]]>,
<errors>
<error id="30024" message="Statement is not valid inside a method." start="112" end="126"/>
</errors>)
End Sub
<WorkItem(881603, "DevDiv/Personal")>
<Fact>
Public Sub ParseTernaryIfReturningLambda()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x2 = If(True, Nothing, Sub()
Console.WriteLine("Hi")
End Sub)
End Sub
End Module
]]>)
End Sub
<WorkItem(881606, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaMethodArgument()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo(a As Action)
End Sub
Sub Main()
Goo(Sub()
Environment.ExitCode = 42
End Sub)
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo(a As Action)
End Sub
Sub Main()
Goo(Sub(c) Console.WriteLine(c))
End Sub
End Module
]]>)
End Sub
<WorkItem(881614, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineIfThenElseIfElse()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = 0
If True Then x = 1 Else If False Then x = 2 Else x = 3
End Sub
End Module
]]>)
End Sub
<WorkItem(881640, "DevDiv/Personal")>
<Fact>
Public Sub ParseBinaryIfReturningLambdaArray()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim e1 = If({Sub()
End Sub}, {})
End Sub
End Module
]]>)
End Sub
<WorkItem(881826, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaDeclareMultipleCommaSeparated()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim m = Sub(ByRef x As String, _
y As Integer) Console.WriteLine(x & y), k = Sub(y, _
x) m(y, x), _
l = Sub(x) _
Console.WriteLine(x)
End Sub
End Module
]]>)
End Sub
<WorkItem(881827, "DevDiv/Personal")>
<Fact>
Public Sub ParseGenericNoTypeArgsImplicitLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = GetType(Action(Of
)
)
End Sub
End Module
]]>)
End Sub
<WorkItem(882391, "DevDiv/Personal")>
<Fact>
Public Sub ParseRightShiftLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = 4 >> _
1
End Sub
End Module
]]>)
End Sub
<WorkItem(882801, "DevDiv/Personal")>
<Fact>
Public Sub ParseObjectInitializerParenthesizedLambda()
ParseAndVerify(<![CDATA[
Class Class1
Sub Test()
Dim e = New With {.f = New Action(Of Integer)(Sub() If True Then Stop)}
Dim g = 3
End Sub
End Class
]]>)
End Sub
<WorkItem(883286, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaSingleLineWithFollowingStatements()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = Sub() Main()
Main()
End Sub
End Module
]]>)
End Sub
<WorkItem(882934, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaSingleLineIfInsideIfBlock()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
If True Then
Dim x = 0
Dim d = Sub() If True Then x = 1 Else x = 2
End If
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseLambdaSingleLineIfWithColon()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() If True Then :
End Sub
End Module
]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() If True Then : End If
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
End Sub
<WorkItem(546693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546693")>
<Fact()>
Public Sub ParseLambdaSingleLineIfWithColonElseIfInsideIfBlock_1()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() If True Then Return : ElseIf
Else
End If
End Sub
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
<error id="30201" message="Expression expected."/>
</errors>)
End Sub
<WorkItem(546693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546693")>
<Fact()>
Public Sub ParseLambdaSingleLineIfWithColonElseIfInsideIfBlock_2()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() If True Then Return : ElseIf False Then
End If
End Sub
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
End Sub
<Fact()>
Public Sub ParseLambdaSingleLineIfWithColonElseInsideIfBlock()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() If True Then Return : Else
End If
End Sub
End Module
]]>)
End Sub
<Fact()>
Public Sub ParseLambdaSingleLineIfWithColonElseSpaceIfInsideIfBlock()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() If True Then Return : Else If False Then Return
End If
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseLambdaSingleLineIfWithStatementColon()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() If True Then M() :
End Sub
End Module
]]>)
End Sub
<Fact>
Public Sub ParseLambdaSingleLineIfWithStatementColonElse()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() If True Then M() : Else
End Sub
End Module
]]>)
End Sub
<WorkItem(530940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530940")>
<Fact()>
Public Sub ParseSingleLineIfColon()
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then Return : Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then Return : Return Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then M() : M() Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then Return : _
Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then Return : _
Return Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
If True Then M() : _
M() Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module Program
Sub M()
Return Else
End Sub
End Module
]]>,
<errors>
<error id="30205"/>
</errors>)
End Sub
<WorkItem(601004, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601004")>
<Fact()>
Public Sub ParseSingleLineIfEmptyElse()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return Else
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Return Else
End Sub
End Module
]]>)
End Sub
''' <summary>
''' EmptyStatement following colon.
''' </summary>
<WorkItem(530966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530966")>
<Fact()>
Public Sub ParseEmptyStatementFollowingColon()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
M() :
If True Then Else M1() :
If True Then Else : M2()
If True Then Else :
10:
20::
30: M3()
L4: M4():
L5: : M5()
End Sub
End Module
]]>)
Dim root = tree.GetRoot()
' If/Else statement lists should not contain EmptyToken.
Dim tokens = root.DescendantTokens().Select(Function(t) t.Kind).ToArray()
CheckArray(tokens,
SyntaxKind.ModuleKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.SubKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.EmptyToken,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.IntegerLiteralToken,
SyntaxKind.ColonToken,
SyntaxKind.IntegerLiteralToken,
SyntaxKind.ColonToken,
SyntaxKind.IntegerLiteralToken,
SyntaxKind.ColonToken,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IdentifierToken,
SyntaxKind.ColonToken,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IdentifierToken,
SyntaxKind.ColonToken,
SyntaxKind.IdentifierToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.EndKeyword,
SyntaxKind.SubKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.ModuleKeyword,
SyntaxKind.EndOfFileToken)
End Sub
<WorkItem(531486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531486")>
<Fact()>
Public Sub ParseSingleLineIfElse()
ParseAndVerify(<![CDATA[
Module Program
Sub Main()
Dim x = Sub() If True Then ElseIf False Then
End Sub
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="66" end="82"/>
</errors>)
End Sub
<WorkItem(546910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546910")>
<Fact()>
Public Sub ParseMultiLineIfLambdaWithStatementColonElse()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() M() : Else
End If
End Sub
End Module
]]>,
<errors>
<error id="36918"/>
</errors>)
End Sub
<WorkItem(546910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546910")>
<Fact()>
Public Sub ParseSingleLineIfLambdaWithStatementColonElse()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Dim x = Sub() M() : Else
End Sub
End Module
]]>,
<errors>
<error id="36918"/>
</errors>)
End Sub
<WorkItem(882943, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaExitFunction()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim f = Function()
Exit Function
End Function
End Sub
End Module
]]>)
End Sub
<WorkItem(883063, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaSingleLineIfInPreprocessorIf()
ParseAndVerify(<![CDATA[
Class Class1
#If True Then
Dim x = 0
Dim y = Sub() If True Then x = 1 : x = 2
#End If
End Class
]]>)
End Sub
<WorkItem(883204, "DevDiv/Personal")>
<Fact>
Public Sub ParseQueryLetLineContinuation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x11 = From i In (<e e="v"></e>.<e>) Let j = i.@e _
Select j
End Sub
End Module
]]>)
End Sub
<WorkItem(883646, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaCallsEndInArrayInitializer()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim f = {Sub() End}
End Sub
End Module
]]>)
End Sub
<WorkItem(883726, "DevDiv/Personal")>
<Fact>
Public Sub ParseLambdaNestedCall()
ParseAndVerify(<![CDATA[
Class Class1
Function Goo()
Dim x = Sub() Call Sub()
Console.WriteLine("hi")
End Sub
Return True
End Function
End Class
]]>)
End Sub
<WorkItem(895166, "DevDiv/Personal")>
<Fact>
Public Sub ParseCommentWithDoubleTicks()
ParseAndVerify(<![CDATA[
''string
]]>)
End Sub
'Parse a nested line if with an else clause. Else should associate with nearest if.
<WorkItem(895059, "DevDiv/Personal")>
<Fact>
Public Sub ParseLineIfWithNestedLineIfAndElse()
ParseAndVerify(<![CDATA[
Class C
Sub s
If o1 Then If o2 Then X = 1 Else X = 2
End Sub
End Class
]]>)
End Sub
<Fact>
Public Sub ParseOneLineStatement()
Dim str = " Dim x = 3 "
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind)
End Sub
<Fact>
Public Sub ParseEndSubStatement()
Dim str = "End Sub "
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(True, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.EndSubStatement, statement.Kind)
End Sub
<Fact>
Public Sub ParseEndClassStatement()
Dim str = "End Class "
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(True, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.EndClassStatement, statement.Kind)
End Sub
<Fact>
Public Sub ParseEmptyStatement()
Dim str = ""
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.EmptyStatement, statement.Kind)
str = " "
statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.EmptyStatement, statement.Kind)
str = " " & vbCrLf & vbCrLf
statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.EmptyStatement, statement.Kind)
End Sub
<Fact>
Public Sub ParseMultiLineStatement()
Dim str =
<Q>
For i as integer = 1 to 10
While true
End While
Next
</Q>.Value
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.ForBlock, statement.Kind)
End Sub
<Fact>
Public Sub Parse2MultiLineStatement01()
Dim str =
<Q>
For i as integer = 1 to 10
While true
End While
Next
While true
End While
</Q>.Value
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(True, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.ForBlock, statement.Kind)
End Sub
<Fact>
Public Sub Parse2MultiLineStatement02()
Dim str =
<Q>
For i as integer = 1 to 10
While true
End While
Next
While true
End While
</Q>.Value
Dim statement = SyntaxFactory.ParseExecutableStatement(str, consumeFullText:=False)
Assert.Equal(False, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.ForBlock, statement.Kind)
End Sub
<Fact>
Public Sub ParseBadMultiLineStatement()
Dim str =
<Q>
For i as integer = 1 to 10
While true
End Sub
Next
While true
End While
</Q>.Value
Dim statement = SyntaxFactory.ParseExecutableStatement(str)
Assert.Equal(True, statement.ContainsDiagnostics)
Assert.Equal(SyntaxKind.ForBlock, statement.Kind)
End Sub
<WorkItem(537169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537169")>
<Fact>
Public Sub ParseGettypeNextString()
ParseAndVerify(<![CDATA[Next.goo(GetType(Func(Of A))), "")]]>,
Diagnostic(ERRID.ERR_NextNoMatchingFor, "Next.goo(GetType(Func(Of A))), """""),
Diagnostic(ERRID.ERR_ExtraNextVariable, ".goo(GetType(Func(Of A)))"))
End Sub
<WorkItem(538515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538515")>
<Fact>
Public Sub IncParseAGPower17()
Dim code As String = (<![CDATA[
Namespace AGPower17
Friend Module AGPower17mod
Sub AGPower17()
Scen242358()
Scen242359()
End Sub
Public Sub Scen242200()
Dim varLeftUInt16242200 As UInt16 = 126US
Dim varRightByteEnumAlt242200 As ByteEnumAlt = ByteEnumAlt.e1
Dim varObjLeftUInt16242200 As Object = 126US
Dim varObjRightByteEnumAlt242200 As Object = ByteEnumAlt.e1
End Sub
Public sub Scen242358()
dim varLeftUInt16242358 as UInt16 = 127US
dim varRightUlongEnumAlt242358 as UlongEnumAlt = ULongEnumAlt.e2
Dim varObjLeftUInt16242358 As Object = 127US
dim varObjRightUlongEnumAlt242358 as object = ULongEnumAlt.e2
End Sub
Public sub Scen242359()
dim varLeftUInt16242359 as UInt16 = 127US
dim varRightUlongEnumAlt242359 as UlongEnumAlt = ULongEnumAlt.e3
Dim varObjLeftUInt16242359 As Object = 127US
dim varObjRightUlongEnumAlt242359 as object = ULongEnumAlt.e3
End Sub
Enum ByteEnumAlt As Byte
e1
e2
e3
End Enum
Enum UlongEnumAlt As ULong
e1
e2
e3
End Enum
End Module
End Namespace
]]>).Value
ParseAndVerify(code)
End Sub
<WorkItem(539055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539055")>
<Fact>
Public Sub ParseReturnFollowedByComma()
ParseAndVerify(<![CDATA[
Module Module1
Dim x = Sub() Return, r = 42
End Module
]]>)
End Sub
<WorkItem(538443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538443")>
<Fact>
Public Sub ParseMultiIfThenElseOnOneLine()
ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If True Then : Else Console.WriteLine() : End If
dim x = sub ()
If True Then : Else Console.WriteLine() : End If
end sub
End Sub
End Module
]]>)
End Sub
<WorkItem(538440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538440")>
<Fact>
Public Sub ParseSingleIfElseTerminatedByColon()
Dim t = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If True Then Console.WriteLine(1) Else Console.WriteLine(2) : Console.WriteLine(3)
'Colon after the else terminates the line if
If True Then Console.WriteLine(4) Else : Console.WriteLine(5)
End Sub
End Module
]]>)
Dim moduleBlock = t.GetRoot().ChildNodesAndTokens()(1)
Dim mainBlock = moduleBlock.ChildNodesAndTokens()(1)
Dim if1 = mainBlock.ChildNodesAndTokens()(1)
Dim if2 = mainBlock.ChildNodesAndTokens()(2)
Dim wl5 = mainBlock.ChildNodesAndTokens()(3)
Assert.Equal(5, mainBlock.ChildNodesAndTokens().Count)
Assert.Equal(SyntaxKind.SingleLineIfStatement, if1.Kind())
Assert.Equal(SyntaxKind.SingleLineIfStatement, if2.Kind())
Assert.Equal(SyntaxKind.ExpressionStatement, wl5.Kind())
Assert.Equal(SyntaxKind.InvocationExpression, DirectCast(wl5.AsNode, ExpressionStatementSyntax).Expression.Kind)
End Sub
<WorkItem(4784, "DevDiv_Projects/Roslyn")>
<Fact>
Public Sub ParseSingleLineSubFollowedByComma()
Dim t = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
session.Raise(Sub(sess) AddHandler sess.SelectedSignatureChanged, Sub(s, e) Return, New SelectedSignatureChangedEventArgs(Nothing, bestMatch))
End Sub
End Module
]]>)
End Sub
<WorkItem(538481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538481")>
<Fact>
Public Sub ParseLineContAtEnd()
Dim t = ParseAndVerify(<![CDATA[
Module M
End Module
_]]>)
End Sub
<Fact>
Public Sub ParseHandlerStatements()
Dim t = ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
dim button1 = new Button()
AddHandler Button1.Click, addressof Button1_Click
RemoveHandler Button1.Click, addressof Button1_Click
End Sub
End Module
]]>)
Dim moduleBlock = t.GetRoot().ChildNodesAndTokens()(1)
Dim mainBlock = moduleBlock.ChildNodesAndTokens()(1)
Dim ah = mainBlock.ChildNodesAndTokens()(2)
Dim rh = mainBlock.ChildNodesAndTokens()(3)
Assert.Equal(ah.Kind(), SyntaxKind.AddHandlerStatement)
Assert.Equal(rh.Kind(), SyntaxKind.RemoveHandlerStatement)
End Sub
<Fact>
Public Sub Regression5150()
Dim code = <String>Module Program
Sub Main()
If True Then : Dim x = Sub() If True Then Dim y :
ElseIf True Then
Console.WriteLine()
End If
End Sub
End Module
</String>.Value
Dim compilation = SyntaxFactory.ParseCompilationUnit(code)
Assert.False(compilation.ContainsDiagnostics)
Dim ifBlock =
CType(CType(CType(compilation.Members(0), TypeBlockSyntax).Members(0), MethodBlockSyntax).Statements(0), MultiLineIfBlockSyntax)
Assert.Equal(1, ifBlock.ElseIfBlocks.Count)
Dim statements = ifBlock.ElseIfBlocks(0).Statements
Assert.Equal(1, statements.Count)
Assert.IsType(Of ExpressionStatementSyntax)(statements(0))
Assert.IsType(Of InvocationExpressionSyntax)(DirectCast(statements(0), ExpressionStatementSyntax).Expression)
Assert.Equal(1, ifBlock.Statements.Count)
Assert.IsType(Of LocalDeclarationStatementSyntax)(ifBlock.Statements(0))
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub Regression5150WithStaticLocal()
Dim code = <String>Module Program
Sub Main()
If True Then : Static x = Sub() If True Then Static y :
ElseIf True Then
Console.WriteLine()
End If
End Sub
End Module
</String>.Value
Dim compilation = SyntaxFactory.ParseCompilationUnit(code)
Assert.False(compilation.ContainsDiagnostics)
Dim ifBlock =
CType(CType(CType(compilation.Members(0), TypeBlockSyntax).Members(0), MethodBlockSyntax).Statements(0), MultiLineIfBlockSyntax)
Assert.Equal(1, ifBlock.ElseIfBlocks.Count)
Dim statements = ifBlock.ElseIfBlocks(0).Statements
Assert.Equal(1, statements.Count)
Assert.IsType(Of ExpressionStatementSyntax)(statements(0))
Assert.IsType(Of InvocationExpressionSyntax)(DirectCast(statements(0), ExpressionStatementSyntax).Expression)
Assert.Equal(1, ifBlock.Statements.Count)
Assert.IsType(Of LocalDeclarationStatementSyntax)(ifBlock.Statements(0))
End Sub
<WorkItem(540669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540669")>
<Fact>
Public Sub SingleLineIfNotTerminateByEmptyStatement()
' Verify that "::" in the else of a single line if does not terminate the single line if.
' The else contains a call, empty statement and the second single line if.
Dim code = <String>
Module Module1
Sub Main()
If True Then Goo(1) Else Goo(2) :: If True Then Goo(3) Else Goo(4) : Goo(5)
End Sub
Private Sub Goo(i As Integer)
Console.WriteLine(i)
End Sub
End Module
</String>.Value
Dim compilation = SyntaxFactory.ParseCompilationUnit(code)
Assert.False(compilation.ContainsDiagnostics)
Dim singleLineIf =
CType(CType(CType(compilation.Members(0), TypeBlockSyntax).Members(0), MethodBlockSyntax).Statements(0), SingleLineIfStatementSyntax)
Dim statements = singleLineIf.ElseClause.Statements
Assert.Equal(2, statements.Count)
Assert.IsType(Of ExpressionStatementSyntax)(statements(0))
Assert.IsType(Of InvocationExpressionSyntax)(DirectCast(statements(0), ExpressionStatementSyntax).Expression)
Assert.IsType(Of SingleLineIfStatementSyntax)(singleLineIf.ElseClause.Statements(1))
End Sub
<WorkItem(540844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540844")>
<Fact>
Public Sub TestForEachAfterOffset()
Const prefix As String = "GARBAGE"
Dim forEachText = <![CDATA['A for each statement
for each a in b
next
]]>.Value
Dim leading = SyntaxFactory.ParseLeadingTrivia(prefix + forEachText, offset:=prefix.Length)
Assert.Equal(3, leading.Count)
Assert.Equal(SyntaxKind.CommentTrivia, leading(0).Kind)
Assert.Equal(SyntaxKind.EndOfLineTrivia, leading(1).Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, leading(2).Kind)
Dim trailing = SyntaxFactory.ParseTrailingTrivia(prefix + forEachText, offset:=prefix.Length)
Assert.Equal(2, trailing.Count)
Assert.Equal(SyntaxKind.CommentTrivia, trailing(0).Kind)
Assert.Equal(SyntaxKind.EndOfLineTrivia, trailing(1).Kind)
Dim t = SyntaxFactory.ParseToken(prefix + forEachText, offset:=prefix.Length, startStatement:=True)
Assert.Equal(SyntaxKind.ForKeyword, t.Kind)
Dim tokens = SyntaxFactory.ParseTokens(prefix + forEachText, offset:=prefix.Length)
Assert.Equal(9, tokens.Count)
Assert.Equal(SyntaxKind.NextKeyword, tokens(6).Kind)
Dim statement = SyntaxFactory.ParseExecutableStatement(prefix + forEachText, offset:=prefix.Length)
Assert.NotNull(statement)
Assert.Equal(SyntaxKind.ForEachBlock, statement.Kind)
Assert.Equal(False, statement.ContainsDiagnostics)
End Sub
<WorkItem(543248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543248")>
<Fact()>
Public Sub ParseBadCollectionRangeVariableDeclaration1()
ParseAndVerify(<![CDATA[
Imports System
Class Program
Shared Sub Main(args As String())
Dim x = From y As Char i, In String.Empty
End Sub
End Class
]]>, Diagnostic(ERRID.ERR_ExpectedIn, ""),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "In"),
Diagnostic(ERRID.ERR_ExpectedIn, ""))
End Sub
<WorkItem(543364, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543364")>
<Fact()>
Public Sub ParseLabelAfterElse()
ParseAndVerify(<![CDATA[
Imports System
Module M
Sub Main()
If False Then
Else 100:
End If
End Sub
End Module]]>, Diagnostic(ERRID.ERR_Syntax, "100"))
End Sub
<WorkItem(544224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544224")>
<Fact()>
Public Sub ParsePartialSingleLineIfStatement()
Dim stmt = SyntaxFactory.ParseExecutableStatement("If True")
Assert.Equal(stmt.Kind, SyntaxKind.MultiLineIfBlock)
Assert.True(stmt.HasErrors)
stmt = SyntaxFactory.ParseExecutableStatement("If True then goo()")
Assert.Equal(stmt.Kind, SyntaxKind.SingleLineIfStatement)
Assert.False(stmt.HasErrors)
End Sub
#Region "Error Test"
<Fact()>
Public Sub BC30003ERR_MissingNext_ParseOnErrorResume()
ParseAndVerify(<![CDATA[
Module Module1
Sub s1()
on error resume
on error resume next
end sub
End Module
]]>,
<errors>
<error id="30003"/>
</errors>)
End Sub
<WorkItem(536260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536260")>
<Fact()>
Public Sub BC30012ERR_LbExpectedEndIf()
ParseAndVerify(<![CDATA[
Module Module1
#If True Then
Dim d = <aoeu>
#End If
</aoeu>
End Module
]]>,
<errors>
<error id="30012"/>
</errors>)
End Sub
<WorkItem(527095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527095")>
<Fact()>
Public Sub BC30016ERR_InvOutsideProc_Label()
ParseAndVerify(<![CDATA[
Module Module1
3
End Module
Module Module2
Goo:
End Module
]]>,
<errors>
<error id="30801"/>
<error id="30016"/>
<error id="30016"/>
</errors>)
End Sub
<WorkItem(874301, "DevDiv/Personal")>
<Fact()>
Public Sub BC30024ERR_InvInsideProc_Option()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Option Explicit On
End Sub
End Module
]]>,
<errors>
<error id="30024"/>
</errors>)
End Sub
<WorkItem(1531, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub BC30035ERR_Syntax_ParseErrorPrecededByComment()
ParseAndVerify(<![CDATA[Module M1
Sub Goo
'this is a
'long
'comment
(1).ToString
End Sub
End Module]]>,
<errors>
<error id="30035" message="Syntax error." start="45" end="46"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30058ERR_ExpectedCase()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
select i
dim j = false
case 0
case 1
case 2
case else
end select
end sub
End Module
]]>,
<errors>
<error id="30058"/>
</errors>)
' ERRID.ERR_ExpectedCase
End Sub
<WorkItem(926761, "DevDiv/Personal")>
<Fact()>
Public Sub BC30071ERR_CaseElseNoSelect()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Case Else
End Sub
End Module
]]>,
<errors>
<error id="30071"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30072ERR_CaseNoSelect()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
case 0
end sub
End Module
]]>,
<errors>
<error id="30072"/>
</errors>)
' ERRID.ERR_CaseNoSelect
End Sub
'Parse a nested line if with a block if (if is followed by eol)
<Fact()>
Public Sub BC30081ERR_ExpectedEndIf_ParseNestedLineIfWithBlockIf()
ParseAndVerify(<![CDATA[
Class C
Sub s
If o1 Then If o2
End Sub
End Class
]]>,
<errors>
<error id="30081"/>
</errors>)
End Sub
<WorkItem(878016, "DevDiv/Personal")>
<Fact()>
Public Sub BC30084ERR_ExpectedNext_For()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
For i = 1 To 10
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
</errors>)
End Sub
<WorkItem(887521, "DevDiv/Personal")>
<Fact()>
Public Sub BC30084ERR_ExpectedNext_ParseErrorCatchClosesForBlock()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
Try
For u = 0 To 2 Step 1
For i = 0 To 2 Step 1
Next
Catch
Finally
End Try
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
</errors>)
End Sub
<WorkItem(874308, "DevDiv/Personal")>
<WorkItem(879764, "DevDiv/Personal")>
<Fact()>
Public Sub BC30086ERR_ElseNoMatchingIf()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Else
End Sub
End Module
]]>,
<errors>
<error id="30086"/>
</errors>)
End Sub
<WorkItem(875150, "DevDiv/Personal")>
<Fact()>
Public Sub BC30089ERR_ObsoleteWhileWend()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
While True
Wend
End Sub
End Module
]]>,
<errors>
<error id="30809"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30091ERR_LoopNoMatchingDo_ParseDoWithErrors()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
loop
do while true
loop until true
do goo
loop
do
end sub
End Module
]]>,
<errors>
<error id="30091"/>
<error id="30238"/>
<error id="30035"/>
<error id="30083"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30095ERR_ExpectedEndSelect()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
if true then
select i
case 0
case 1
case 2
end if
end sub
End Module
]]>,
<errors>
<error id="30095"/>
</errors>)
' ERRID.ERR_ExpectedEndSelect
End Sub
<WorkItem(877929, "DevDiv/Personal")>
<Fact()>
Public Sub BC30198ERR_ExpectedRparen_If()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
If(1,2)
End If
End Sub
End Module
]]>)
End Sub
<WorkItem(884863, "DevDiv/Personal")>
<Fact()>
Public Sub BC30199ERR_ExpectedLparen_ParseWrongNameUsedForOperatorToBeOverloadedErrors()
ParseAndVerify(<![CDATA[
Class c3
'COMPILEERROR: BC30199, "\\"
shared Operator /\(ByVal x As c3, ByVal y As c3) As Boolean
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
</errors>)
End Sub
<WorkItem(885650, "DevDiv/Personal")>
<Fact()>
Public Sub BC30203ERR_ExpectedIdentifier()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
With New Object
.
End With
End Sub
End Module
]]>,
<errors>
<error id="30203"/>
</errors>)
End Sub
'Parse a line if followed by dangling elseif
<Fact()>
Public Sub BC30205ERR_ExpectedEOS_ParseLineIfDanglingElseIf()
ParseAndVerify(<![CDATA[
class c
sub goo()
if true then elseif
end sub
end class
]]>,
<errors>
<error id="30205" message="End of statement expected." start="68" end="74"/>
<error id="30201" message="Expression expected." start="74" end="74"/>
</errors>)
End Sub
<WorkItem(885705, "DevDiv/Personal")>
<Fact()>
Public Sub BC30205ERR_ExpectedEOS_MismatchExpectedEOSVSSyntax()
ParseAndVerify(<![CDATA[
Class Class1
Delegate Sub del()
Public Custom Event e As del
AddHandler(ByVal value As del) as Integer
End AddHandler
RemoveHandler(ByVal value As del) as Integer
End RemoveHandler
RaiseEvent() as Integer
End RaiseEvent
End Event
End Class
]]>,
<errors>
<error id="30205"/>
<error id="30205"/>
<error id="30205"/>
</errors>)
End Sub
<WorkItem(879284, "DevDiv/Personal")>
<Fact()>
Public Sub BC30239ERR_ExpectedRelational_ParseLeftShift()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x
x=4 <>>< 2
'Comment
x = Class1 << 4
End Sub
End Module
]]>,
<errors>
<error id="30201"/>
<error id="30239"/>
</errors>)
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x
x=4 <>>< 2
'COMPILEERROR: BC30108, "Class1"
x = Class1 << 4
End Sub
End Module
]]>,
<errors>
<error id="30201"/>
<error id="30239"/>
</errors>)
End Sub
<WorkItem(875155, "DevDiv/Personal")>
<Fact()>
Public Sub BC30249ERR_ExpectedEQ_ParseFor()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
for x,y as Integer = 1 to 100
Next
End Sub
End Module
]]>,
<errors>
<error id="30249"/>
<error id="30035"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30289ERR_InvInsideEndsProc_ParseSingleLineLambdaWithClass()
ParseAndVerify(<![CDATA[
Module M1
Sub Goo()
Try
Dim x1 = Sub(y) Class C
End Try
End Sub
End Module
]]>,
<errors>
<error id="30289"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30321ERR_CaseAfterCaseElse()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
select i
case 0
case 1
case 2
case else
case 3
end select
end sub
End Module
]]>,
<errors>
<error id="30321"/>
</errors>)
' ERRID.ERR_CaseAfterCaseElse
End Sub
<Fact()>
Public Sub BC30379ERR_CatchAfterFinally()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
try
catch
finally
catch
end try
end sub
End Module
]]>,
<errors>
<error id="30379"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30381ERR_FinallyAfterFinally()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
try
catch
finally
finally
end try
end sub
End Module
]]>,
<errors>
<error id="30381"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30384ERR_ExpectedEndTry()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
try
catch
finally
end sub
End Module
]]>,
<errors>
<error id="30384"/>
</errors>)
End Sub
<WorkItem(904911, "DevDiv/Personal")>
<Fact()>
Public Sub BC30384ERR_ExpectedEndTry_ParseNestedIncompleteTryBlocks()
ParseAndVerify(<![CDATA[Namespace n1
Module m1
Public Sub bar()
Try
Try
'Catch ex As Exception
'End Try
Catch ex As Exception
End Try
End Sub
End Module
End Namespace
]]>,
<errors>
<error id="30384"/>
</errors>)
End Sub
<WorkItem(899235, "DevDiv/Personal")>
<Fact()>
Public Sub BC30429ERR_InvalidEndSub_ParseLambdaWithEndSubInsideTryBlock()
ParseAndVerify(<![CDATA[
Module M1
Sub Goo()
Try
Dim x1 = Sub(y) End Sub
End Try
End Sub
End Module
]]>,
<errors>
<error id="30429"/>
</errors>)
End Sub
<WorkItem(904910, "DevDiv/Personal")>
<Fact()>
Public Sub BC30370ERR_ExpectedRbrace_CollectionInitializer()
ParseAndVerify(<![CDATA[Module Module1
Sub Main()
Dim b1c = {1"", 2, 3}
End Sub
End Module]]>,
<errors>
<error id="30370"/>
</errors>)
End Sub
<WorkItem(880374, "DevDiv/Personal")>
<Fact()>
Public Sub BC30670ERR_RedimNoSizes()
' NOTE: the test has been changed to check for NO ERROR because error 30670
' was moved from parser to initial binding phase
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim Obj()
ReDim Obj
ReDim Obj()
End Sub
End Module
]]>)
End Sub
<Fact()>
Public Sub BC30670ERR_RedimNoSizes_02()
' NOTE: the test has been changed to only check for error 30205 because error 30670
' was moved from parser to initial binding phase
ParseAndVerify(<![CDATA[
class c1
sub s
redim a 1 + 2 'Dev 10 reports 30205
end sub
end class
]]>,
<errors>
<error id="30205"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30781ERR_ExpectedContinueKind()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
do
continue
loop
while true
continue
end while
for i = 0 to 10
continue
next
end sub
End Module
]]>,
<errors>
<error id="30781"/>
<error id="30781"/>
<error id="30781"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30800ERR_ObsoleteArgumentsNeedParens()
ParseAndVerify(<![CDATA[
class c1
sub s
i 1,2
end sub
end class
]]>,
<errors>
<error id="30800"/>
</errors>)
End Sub
<WorkItem(880397, "DevDiv/Personal")>
<Fact()>
Public Sub BC30801ERR_ObsoleteLineNumbersAreLabels_LambdaLineTerminator()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim s1a = Function () : 1 + x
End Sub
End Module
]]>,
<errors>
<error id="30201"/>
<error id="30035"/>
</errors>
)
End Sub
<Fact()>
Public Sub BC30807ERR_ObsoleteLetSetNotNeeded()
ParseAndVerify(<![CDATA[
class c1
sub s
let i = 0
set j = i
end sub
end class
]]>,
<errors>
<error id="30807"/>
<error id="30807"/>
</errors>)
End Sub
<WorkItem(875171, "DevDiv/Personal")>
<Fact()>
Public Sub BC30814ERR_ObsoleteGosub()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
GoSub 1000
1000:
End Sub
End Module
]]>,
<errors>
<error id="30814"/>
</errors>)
End Sub
<WorkItem(873634, "DevDiv/Personal")>
<Fact()>
Public Sub BC30924ERR_NoConstituentArraySizes_ParseArrayInitializer()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim FixedRankArray As Short()
FixedRankArray = New Short() ({1, 2})
End Sub
End Module
]]>,
<errors>
<error id="30987"/>
<error id="32014"/>
</errors>)
End Sub
<WorkItem(885229, "DevDiv/Personal")>
<Fact()>
Public Sub BC31135ERR_SpecifiersInvOnEventMethod_AddHandler()
ParseAndVerify(<![CDATA[
Class Cls
Friend Delegate Sub EH(ByRef x As Integer)
Custom Event e1 As EH
MustOverride AddHandler(ByVal value As EH)
End AddHandler
RemoveHandler(ByVal value As EH)
End RemoveHandler
RaiseEvent(ByRef x As Integer)
End RaiseEvent
End Event
End Class
]]>,
<errors>
<error id="31135"/>
</errors>)
End Sub
<WorkItem(885655, "DevDiv/Personal")>
<Fact()>
Public Sub BC31395ERR_NoTypecharInLabel()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Label$:
End Sub
End Module
]]>,
<errors>
<error id="31395"/>
</errors>)
End Sub
<WorkItem(917, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub BC31427ERR_BadCCExpression_ConditionalCompilationExpr()
ParseAndVerify(<![CDATA[
Class Class1
#If 1 like Nothing Then
#End If
End Class
]]>,
<errors>
<error id="31427"/>
</errors>)
End Sub
<WorkItem(527019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527019")>
<Fact()>
Public Sub BC31427ERR_BadCCExpression_ParseErrorMismatchExpectedEOSVSBadCCExpressionExpected()
ParseAndVerify(<![CDATA[
Class Class1
'COMPILEERROR: BC31427, "global"
#if global.ns1 then
#End If
End Class
]]>,
<errors>
<error id="31427"/>
</errors>)
End Sub
<WorkItem(536271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536271")>
<Fact()>
Public Sub BC32020ERR_ExpectedAssignmentOperator()
ParseAndVerify(<![CDATA[
Module Module1
Dim ele As XElement = <e/>
Sub Main()
ele.@h = From i in New String(){"a", "b","c"} let ele.@h = i
End Sub
End Module
]]>,
<errors>
<error id="32020"/>
</errors>)
End Sub
<WorkItem(879334, "DevDiv/Personal")>
<Fact()>
Public Sub BC32065ERR_GenericParamsOnInvalidMember_Lambda()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = Function(Of T)(x As T) x
End Sub
End Module
]]>,
<errors>
<error id="32065"/>
</errors>)
End Sub
<WorkItem(881553, "DevDiv/Personal")>
<Fact()>
Public Sub BC32093ERR_OfExpected_ParseGenericTypeInstantiation()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim c1 As New Class1(String)()
End Sub
End Module
]]>,
<errors>
<error id="32093"/>
</errors>)
End Sub
<WorkItem(877226, "DevDiv/Personal")>
<WorkItem(881641, "DevDiv/Personal")>
<Fact()>
Public Sub BC33104ERR_IllegalOperandInIIFCount()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x1 = If()
Dim x2 = If(True)
Dim x3 = If(True, False, True, False)
End Sub
End Module
]]>,
<errors>
<error id="33104"/>
<error id="33104"/>
<error id="33104"/>
</errors>)
End Sub
<WorkItem(883303, "DevDiv/Personal")>
<Fact()>
Public Sub BC33105ERR_IllegalOperandInIIFName_TernaryIf()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim s2_a = If(Expression:=True, truepart:=1, falsepart:=2)
End Sub
End Module
]]>,
<errors>
<error id="33105"/>
<error id="33105"/>
<error id="33105"/>
</errors>)
End Sub
<WorkItem(875159, "DevDiv/Personal")>
<Fact()>
Public Sub BC36005ERR_ElseIfNoMatchingIf()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
If True Then
Else
elseif
End If
End Sub
End Module
]]>,
<errors>
<error id="36005"/>
<error id="30201"/>
</errors>)
End Sub
<WorkItem(875202, "DevDiv/Personal")>
<Fact()>
Public Sub BC36607ERR_ExpectedIn_ParseForEachControlVariable()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
For each x() as Integer {1,2,3} in New Integer()() {New Integer(){1,2}
Next
End Sub
End Module
]]>,
<errors>
<error id="30035"/>
<error id="36607"/>
</errors>)
End Sub
<Fact()>
Public Sub BC36008ERR_ExpectedEndUsing()
ParseAndVerify(<![CDATA[
Module Module1
Sub Goo()
using e0
end sub
End Module
]]>,
<errors>
<error id="36008"/>
</errors>)
End Sub
<WorkItem(880150, "DevDiv/Personal")>
<Fact()>
Public Sub BC36620ERR_ExpectedAnd_ParseQueryJoinConditionAndAlso()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim q4 = From i In col1 Join j In col1 On i Equals j AndAlso i Equals j
End Sub
End Module
]]>,
<errors>
<error id="36620"/>
</errors>)
End Sub
<WorkItem(881620, "DevDiv/Personal")>
<Fact()>
Public Sub BC36620ERR_ExpectedAnd_ParseQueryJoinOnOr()
ParseAndVerify(<![CDATA[
Module JoinOnInvalid
Sub JoinOnInvalid()
Dim col1 As IQueryable
Dim q3 = From i In col1 Join j In col1 On i Equals j OR i Equals j
End Sub
End Module
]]>,
<errors>
<error id="36620"/>
</errors>)
End Sub
<WorkItem(527028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527028")>
<Fact()>
Public Sub BC36631ERR_ExpectedJoin()
ParseAndVerify(<![CDATA[
Class Class1
Dim l = From pers In {1, 2}
Group
Join pet In {3, 4} On pers Equals pet Into PetList = Group
End Class
]]>,
<errors>
<error id="36605"/>
<error id="36615"/>
</errors>)
End Sub
<WorkItem(904984, "DevDiv/Personal")>
<Fact()>
Public Sub BC36668ERR_MultilineLambdasCannotContainOnError()
' Note, the BC36668 is now reported during binding.
ParseAndVerify(<![CDATA[
Module M1
Dim a = Sub()
On Error Resume Next
End Sub
Dim b = Sub() On Error GoTo 1
Dim c = Function()
Resume
End Function
End Module
]]>)
End Sub
<WorkItem(880300, "DevDiv/Personal")>
<Fact()>
Public Sub BC36672ERR_StaticInLambda()
' Roslyn reports this error during binding.
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim y = Sub()
Static a As Integer = 2
End Sub
End Sub
End Module
]]>)
End Sub
<WorkItem(884259, "DevDiv/Personal")>
<Fact()>
Public Sub BC36673ERR_MultilineLambdaMissingSub()
ParseAndVerify(<![CDATA[
Module M1
Sub Goo()
If True Then
'COMPILEERROR : BC36673, "Sub()"
Dim x = Sub()
End If
'COMPILEERROR : BC30429, "End Sub"
End Sub
'COMPILEERROR : BC30289, "End Module"
End Module
]]>,
<errors>
<error id="36673"/>
</errors>)
End Sub
<WorkItem(885258, "DevDiv/Personal")>
<WorkItem(888613, "DevDiv/Personal")>
<Fact()>
Public Sub BC36714ERR_InitializedExpandedProperty()
ParseAndVerify(<![CDATA[
Class Class1
Public MustOverride Property Goo() As Date = Now
End Class
]]>,
<errors>
<error id="36714"/>
</errors>)
ParseAndVerify(<![CDATA[
Public Interface IFPropertyAssign
Property Scenario2Array() As Integer() = {1,2,3}
Property Scenario2List() As List(Of Integer) = NEW List(Of Integer) FROM {1,2,3}
End Interface
]]>,
<errors>
<error id="36714"/>
<error id="36714"/>
</errors>)
End Sub
<WorkItem(885375, "DevDiv/Personal")>
<Fact>
Public Sub ParseExpectedEndSelect()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
Dim q = From x In {1, 2, 3} _
Where True _
'Comment
Select 2
End Sub
End Class
]]>,
<errors>
<error id="30095" message="'Select Case' must end with a matching 'End Select'."/>
</errors>)
End Sub
<WorkItem(885379, "DevDiv/Personal")>
<Fact>
Public Sub ParseObsoleteArgumentsNeedParensAndArgumentSyntax()
ParseAndVerify(<![CDATA[
Class Class1
Sub Goo()
Dim q = From x In {1, 2} _
'Comment
Where true _
Select 2
End Sub
End Class
]]>,
<errors>
<error id="30800" message="Method arguments must be enclosed in parentheses."/>
<error id="32017" message="Comma, ')', or a valid expression continuation expected."/>
</errors>)
End Sub
<WorkItem(881643, "DevDiv/Personal")>
<Fact()>
Public Sub BC36720ERR_CantCombineInitializers()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x0 = New List(Of Integer) FROM {2,3} with {.capacity=2}
Dim a As New C2() From {"Hello World!"} with {.a = "goo"}
Dim b As New C2() with {.a = "goo"} From {"Hello World!"}
Dim c as C2 = New C2() From {"Hello World!"} with {.a = "goo"}
Dim d as c2 = New C2() with {.a = "goo"} From {"Hello World!"}
End Sub
End Module
]]>, Diagnostic(ERRID.ERR_CantCombineInitializers, "FROM {2,3}"),
Diagnostic(ERRID.ERR_CantCombineInitializers, "with"),
Diagnostic(ERRID.ERR_CantCombineInitializers, "From"),
Diagnostic(ERRID.ERR_CantCombineInitializers, "From {""Hello World!""}"),
Diagnostic(ERRID.ERR_CantCombineInitializers, "with {.a = ""goo""}"))
End Sub
<Fact()>
Public Sub BC30431ERR_InvalidEndProperty_Bug869732()
'Tree loses text when declaring a property Let/End Let
ParseAndVerify(<![CDATA[
Class Class1
Property Goo() as Single
Let
End Let
Get
End Get
Set
End Set
End Property
End Class
]]>,
Diagnostic(ERRID.ERR_ObsoleteLetSetNotNeeded, "Let"),
Diagnostic(ERRID.ERR_UnrecognizedEnd, "End"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Get"),
Diagnostic(ERRID.ERR_InvalidEndGet, "End Get"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "Set"),
Diagnostic(ERRID.ERR_InvalidEndSet, "End Set"),
Diagnostic(ERRID.ERR_InvalidEndProperty, "End Property"))
End Sub
<WorkItem(536268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536268")>
<Fact()>
Public Sub ParseExpectedXmlNameAndIllegalChar()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim l = <
<%= "e"%> />
End Sub
End Module
]]>, Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, Environment.NewLine),
Diagnostic(ERRID.ERR_IllegalXmlWhiteSpace, " "))
End Sub
<WorkItem(536270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536270")>
<Fact()>
Public Sub ParseExpectedXmlnsAndExpectedEQAndExpectedXmlName()
ParseAndVerify(<![CDATA[
Imports < xmlns:ns3="goo">
Imports <xmlns :ns4="goo">
Imports <xmlns: ns5="goo">
Imports < xmlns="goo">
Module Module1
Sub Main()
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedXmlns, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, "xmlns"),
Diagnostic(ERRID.ERR_ExpectedXmlns, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, "xmlns"),
Diagnostic(ERRID.ERR_ExpectedXmlName, "ns5"),
Diagnostic(ERRID.ERR_ExpectedXmlns, ""),
Diagnostic(ERRID.ERR_ExpectedGreater, "xmlns"))
End Sub
<WorkItem(880138, "DevDiv/Personal")>
<Fact()>
Public Sub ParseLambda_ERR_ExpectedIdentifier()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim s6 = Function ((x) (x + 1))
End Sub
End Module
]]>,
<errors>
<error id="30203"/>
<error id="30638"/>
<error id="32014"/>
<error id="36674"/>
</errors>)
End Sub
<WorkItem(880140, "DevDiv/Personal")>
<Fact()>
Public Sub BC32017_ParseObjectMemberInitializer()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
ObjTest!New ClsCustomer With {.ID = 106, .Name = "test 106"}
End Sub
End Module
]]>,
<errors>
<error id="30800"/>
<error id="32017"/>
<error id="32017"/>
</errors>)
End Sub
<WorkItem(880155, "DevDiv/Personal")>
<Fact()>
Public Sub ParseObjectMemberInitializer_ERR_ExpectedEOS()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
dim c3 as customer = new customer with {.x=5 : .y=6}
End Sub
End Module
]]>,
<errors>
<error id="30370"/>
<error id="30205"/>
</errors>)
End Sub
<WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")>
<WorkItem(894062, "DevDiv/Personal")>
<Fact()>
Public Sub BC30287ERR_ExpectedDot_ParseVariant()
ParseAndVerify(<![CDATA[
If VarType(a1.GetValue(x)) > Variant 'Dev10/11 report expected '.' but Roslyn allows this. Grammar says its OK.
]]>,
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If VarType(a1.GetValue(x)) > Variant"),
Diagnostic(ERRID.ERR_ObsoleteObjectNotVariant, "Variant"))
End Sub
<WorkItem(896842, "DevDiv/Personal")>
<Fact()>
Public Sub ParseIncompleteWithBlocks()
ParseAndVerify(<![CDATA[
Dim x3 = Function(y As Long)
With]]>,
<errors>
<error id="30085"/>
<error id="30201"/>
<error id="36674"/>
</errors>)
ParseAndVerify(<![CDATA[
Dim x3 =Sub()
If]]>,
<errors>
<error id="30081"/>
<error id="30201"/>
<error id="36673"/>
</errors>)
End Sub
<WorkItem(897824, "DevDiv/Personal")>
<Fact()>
Public Sub ParseExplicitLCs()
ParseAndVerify(<![CDATA[
Namespace RegressDev10660280
Sub Goo1(ByVal x As Integer, _
ByVal y As Integer _
)
apCompare(2, x, "Value of goo1")
End Sub
Sub Goo2( _
_
]]>,
<errors>
<error id="30026"/>
<error id="30198"/>
<error id="30203"/>
<error id="30626"/>
</errors>)
End Sub
<WorkItem(888562, "DevDiv/Personal")>
<Fact()>
Public Sub ParseMoreErrorExpectedRparen()
ParseAndVerify(<![CDATA[
Module M
Sub Test()
Dim i As Object
i = ctype(new Cust1 with {.x=6} , new cust1 with {.x =3})
End Sub
Class Cust1
Public x As Integer
End Class
End Module
]]>,
<errors>
<error id="30200"/>
<error id="30198"/>
</errors>)
End Sub
<WorkItem(887788, "DevDiv/Personal")>
<Fact()>
Public Sub ParseMoreErrorExpectedEOS()
ParseAndVerify(<![CDATA[
Module m1
Sub Test()
Try
Catch ex As Exception When New Object With (5) {.x = 9}
End Try
End Sub
End Module
]]>,
<errors>
<error id="30987"/>
</errors>)
End Sub
<WorkItem(887790, "DevDiv/Personal")>
<Fact()>
Public Sub BC31412ERR_HandlesSyntaxInClass_ExpectedIdentifierAndExpectedDot()
ParseAndVerify(<![CDATA[
Class c1
sub test handles new customer with {.x = 5, .y = "6"}
End Sub
End Class
Class customer : End Class
]]>,
<errors>
<error id="30183"/>
<error id="30287"/>
<error id="30203"/>
</errors>)
End Sub
<WorkItem(904917, "DevDiv/Personal")>
<Fact()>
Public Sub ParseErrorInTryInSub()
ParseAndVerify(<![CDATA[Namespace n1
Module m1
public sub bar()
try
dim j =2
dim k =4
public sub goo
End sub
End Module
End Namespace
]]>,
<errors>
<error id="30289"/>
<error id="30384"/>
<error id="30026"/>
</errors>)
End Sub
<WorkItem(924035, "DevDiv/Personal")>
<Fact()>
Public Sub BC36674ERR_MultilineLambdaMissingFunction_ParseLambdaCustomEvent()
ParseAndVerify(<![CDATA[
Structure Scen16
Dim i = Function()
Custom Event ev
End Structure
]]>,
<errors>
<error id="36674"/>
<error id="31122"/>
</errors>)
End Sub
<WorkItem(927100, "DevDiv/Personal")>
<Fact()>
Public Sub BC32005ERR_BogusWithinLineIf()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
For i = 1 To 10
If True Then Console.WriteLine() : Next
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="32005"/>
</errors>)
End Sub
<WorkItem(539208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539208")>
<Fact()>
Public Sub BC32005ERR_BogusWithinLineIf_2()
ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
If True : If False Then Console.WriteLine(1) : End If
If True : If False Then Else Console.WriteLine(1) : End If
End Sub
End Module
]]>, Diagnostic(ERRID.ERR_ExpectedEndIf, "If True"),
Diagnostic(ERRID.ERR_BogusWithinLineIf, "End If"),
Diagnostic(ERRID.ERR_ExpectedEndIf, "If True"),
Diagnostic(ERRID.ERR_BogusWithinLineIf, "End If")
)
End Sub
<WorkItem(914635, "DevDiv/Personal")>
<Fact()>
Public Sub BC36615ERR_ExpectedInto()
ParseAndVerify(<![CDATA[
Module P
Sub M()
Dim q = from x in y group x by
End Sub
End Module
]]>,
<errors>
<error id="30201"/>
<error id="36615"/>
</errors>)
End Sub
<Fact()>
Public Sub BC30016ERR_InvOutsideProc()
ParseAndVerify(<![CDATA[
Module P
100:
Interface i1
200:
End Interface
structure s1
300:
end structure
enum e
300:
end enum
End Module
]]>,
Diagnostic(ERRID.ERR_InvOutsideProc, "100:"),
Diagnostic(ERRID.ERR_InvOutsideProc, "200:"),
Diagnostic(ERRID.ERR_InvOutsideProc, "300:"),
Diagnostic(ERRID.ERR_InvInsideEnum, "300:"))
End Sub
<WorkItem(539182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539182")>
<Fact()>
Public Sub ParseEmptyStatementWithBadToken()
' There should only be one error reported
ParseAndVerify(<![CDATA[
Module P
Sub main()
$
End Sub
End Module
]]>, <errors>
<error id="30037" message="Character is not valid." start="59" end="60"/>
</errors>)
End Sub
<WorkItem(539515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539515")>
<Fact()>
Public Sub ParseNestedSingleLineIfFollowedByEndIf()
' Report error for mismatched END IF.
ParseAndVerify(<![CDATA[Module M
Sub Main()
If False Then Else If True Then Else
End If
End Sub
End Module]]>,
<errors>
<error id="30087" message="'End If' must be preceded by a matching 'If'." start="88" end="94"/>
</errors>)
End Sub
<WorkItem(539515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539515")>
<Fact()>
Public Sub ParseSingleLineWithNestedMultiLineIf()
' Report error for mismatched END IF.
ParseAndVerify(<![CDATA[
Module M
Sub Main()
If False Then Else If True Then
End if
End Sub
End Module]]>, <errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="89" end="101"/>
<error id="30087" message="'End If' must be preceded by a matching 'If'." start="122" end="128"/>
</errors>)
End Sub
<Fact()>
Public Sub ParseSingleLineIfThenElseFollowedByIfThen()
' This is a single line if-then-else with a multi-line-if-then
ParseAndVerify(<![CDATA[
Module Module1
Sub goo()
If False Then Else if true then
If False Then Else if true then
end if
If False Then Else if true then : end if
End Sub
End Module]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="93" end="105"/>
<error id="30081" message="'If' must end with a matching 'End If'." start="146" end="158"/>
<error id="30087" message="'End If' must be preceded by a matching 'If'." start="199" end="205"/>
</errors>)
End Sub
<Fact()>
Public Sub ParseSingleLineIfThenFollowedByIfThen()
' This is a single line if-then-else with a multi-line-if-then
ParseAndVerify(<![CDATA[
Module Module1
Sub goo()
If False Then if true then
If False Then if true then
end if
If False Then if true then : end if
End Sub
End Module]]>, <Errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="88" end="100"/>
<error id="30081" message="'If' must end with a matching 'End If'." start="136" end="148"/>
<error id="30087" message="'End If' must be preceded by a matching 'If'." start="189" end="195"/>
</Errors>)
End Sub
<Fact()>
Public Sub ParseSingleLineIfThenElseFollowedByDo()
' This is a single line if-then-else with a multi-line-if-then
ParseAndVerify(<![CDATA[
Module Module1
Sub goo()
If False Then Else do
If False Then Else do
Loop
If False Then Else Do : Loop
End Sub
End Module]]>, <errors>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="94" end="96"/>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="139" end="141"/>
<error id="30091" message="'Loop' must be preceded by a matching 'Do'." start="183" end="187"/>
</errors>)
End Sub
<Fact()>
Public Sub ParseSingleLineIfThenFollowedByDo()
' This is a single line if-then-else with a multi-line-if-then
ParseAndVerify(<![CDATA[
Module Module1
Sub goo()
If False Then do
If False Then do
Loop
If False Then Do : Loop
End Sub
End Module]]>,
<errors>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="88" end="90"/>
<error id="30083" message="'Do' must end with a matching 'Loop'." start="127" end="129"/>
<error id="30091" message="'Loop' must be preceded by a matching 'Do'." start="165" end="169"/>
</errors>)
End Sub
<Fact()>
Public Sub ParseMultiLineIfMissingThen()
'this is a "multi line if" missing a "then". "f()" after "true" is error as well as missing "end if
ParseAndVerify(<![CDATA[
Module Module1
sub goo()
if true f()
if true then else if true f() is an error
End Sub
End Module]]>,
<errors>
<error id="30081" message="'If' must end with a matching 'End If'." start="74" end="81"/>
<error id="30205" message="End of statement expected." start="82" end="83"/>
<error id="30081" message="'If' must end with a matching 'End If'." start="125" end="132"/>
<error id="30205" message="End of statement expected." start="133" end="134"/>
</errors>)
End Sub
<Fact()>
Public Sub VarDeclWithKeywordAsIdentifier()
ParseAndVerify(<![CDATA[
Class C1
' the following usages of Dim/Const do not report parser diagnostics, they will
' be reported while binding.
Dim Sub S1()
End Sub
Const Function F1() as Integer
return 23
End Function
Dim Property P1() as Integer
Dim Public Shared Operator +(m1 as C1, m2 as C1)
return nothing
End Operator
' keyword is not an identifier, outside of method body
Public Property Namespace As String
Public Property Class As String
Const End As String
Sub Goo()
' keyword is not an identifier, inside of method body
Dim Namespace as integer
Dim Class
Const End
End Sub
' Parser: specifier invalid on this statement
dim namespace
end namespace
' binding errors, not reported here.
dim class c2
end class
End Class
' Parser: specifier invalid on this statement
dim namespace
end namespace
' binding errors, not reported here.
dim class c2
end class
dim module goo
end module
]]>, Diagnostic(ERRID.ERR_ExpectedEndClass, "Class C1").WithLocation(2, 13),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Namespace").WithLocation(19, 33),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Class").WithLocation(20, 33),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "End").WithLocation(21, 23),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Namespace").WithLocation(25, 25),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Class").WithLocation(26, 25),
Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "End").WithLocation(27, 27),
Diagnostic(ERRID.ERR_NamespaceNotAtNamespace, "namespace").WithLocation(31, 21),
Diagnostic(ERRID.ERR_SpecifiersInvalidOnInheritsImplOpt, "dim").WithLocation(31, 17),
Diagnostic(ERRID.ERR_ExpectedIdentifier, "").WithLocation(31, 30),
Diagnostic(ERRID.ERR_EndClassNoClass, "End Class").WithLocation(37, 13),
Diagnostic(ERRID.ERR_SpecifiersInvalidOnInheritsImplOpt, "dim").WithLocation(40, 13),
Diagnostic(ERRID.ERR_ExpectedIdentifier, "").WithLocation(40, 26))
End Sub
<WorkItem(542066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542066")>
<Fact()>
Public Sub Bug9035()
ParseAndVerify(<![CDATA[
Module Program
Sub Main()
if true then console.writeline() : ' this goes here.
' test this case in the if part of the single line if statement
If True Then try :
finally
end try
If True Then select case true :
end select
If True Then using resource As New Object() :
end using
If True Then while true :
end while
If True Then do while true :
loop
If True Then with nothing :
end with
If True Then for each x as object in nothing :
next
If True Then for x as object = 1 to 12:
next
If True Then if true :
end if
If True Then synclock new Object() :
end synclock
'
' test this case in the else part of the single line if statement
If True Then else try :
finally
end try
If True Then else select case true :
end select
If True Then else using resource As New Object() :
end using
If True Then else while true :
end while
If True Then else do while true :
loop
If True Then else with nothing :
end with
If True Then else for each x as object in nothing :
next
If True Then else for x as object = 1 to 12:
next
If True Then else if true :
end if
If True Then else synclock new Object() :
end synclock
' make sure multiline statements in a single line if still work when being written in one line.
If True Then select case 1 : case else : end select
' make sure not to break the single line lambdas
Dim s1 = Sub() If True Then Console.WriteLine(1) :
Dim s2 = Sub() If True Then Console.WriteLine(1) :: Console.WriteLine(1) ::
Dim s3 = Sub() If True Then Console.WriteLine(1) :::: Console.WriteLine(1)
Dim s4 = (Sub() If True Then Console.WriteLine(1):)
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedEndTry, "try"),
Diagnostic(ERRID.ERR_FinallyNoMatchingTry, "finally"),
Diagnostic(ERRID.ERR_EndTryNoTry, "end try"),
Diagnostic(ERRID.ERR_ExpectedEndSelect, "select case true"),
Diagnostic(ERRID.ERR_ExpectedCase, ""),
Diagnostic(ERRID.ERR_EndSelectNoSelect, "end select"),
Diagnostic(ERRID.ERR_ExpectedEndUsing, "using resource As New Object()"),
Diagnostic(ERRID.ERR_EndUsingWithoutUsing, "end using"),
Diagnostic(ERRID.ERR_ExpectedEndWhile, "while true"),
Diagnostic(ERRID.ERR_EndWhileNoWhile, "end while"),
Diagnostic(ERRID.ERR_ExpectedLoop, "do while true"),
Diagnostic(ERRID.ERR_LoopNoMatchingDo, "loop"),
Diagnostic(ERRID.ERR_ExpectedEndWith, "with nothing"),
Diagnostic(ERRID.ERR_EndWithWithoutWith, "end with"),
Diagnostic(ERRID.ERR_ExpectedNext, "for each x as object in nothing"),
Diagnostic(ERRID.ERR_NextNoMatchingFor, "next"),
Diagnostic(ERRID.ERR_ExpectedNext, "for x as object = 1 to 12"),
Diagnostic(ERRID.ERR_NextNoMatchingFor, "next"),
Diagnostic(ERRID.ERR_ExpectedEndIf, "if true"),
Diagnostic(ERRID.ERR_EndIfNoMatchingIf, "end if"),
Diagnostic(ERRID.ERR_ExpectedEndSyncLock, "synclock new Object()"),
Diagnostic(ERRID.ERR_EndSyncLockNoSyncLock, "end synclock"),
Diagnostic(ERRID.ERR_ExpectedEndTry, "try"),
Diagnostic(ERRID.ERR_FinallyNoMatchingTry, "finally"),
Diagnostic(ERRID.ERR_EndTryNoTry, "end try"),
Diagnostic(ERRID.ERR_ExpectedEndSelect, "select case true"),
Diagnostic(ERRID.ERR_ExpectedCase, ""),
Diagnostic(ERRID.ERR_EndSelectNoSelect, "end select"),
Diagnostic(ERRID.ERR_ExpectedEndUsing, "using resource As New Object()"),
Diagnostic(ERRID.ERR_EndUsingWithoutUsing, "end using"),
Diagnostic(ERRID.ERR_ExpectedEndWhile, "while true"),
Diagnostic(ERRID.ERR_EndWhileNoWhile, "end while"),
Diagnostic(ERRID.ERR_ExpectedLoop, "do while true"),
Diagnostic(ERRID.ERR_LoopNoMatchingDo, "loop"),
Diagnostic(ERRID.ERR_ExpectedEndWith, "with nothing"),
Diagnostic(ERRID.ERR_EndWithWithoutWith, "end with"),
Diagnostic(ERRID.ERR_ExpectedNext, "for each x as object in nothing"),
Diagnostic(ERRID.ERR_NextNoMatchingFor, "next"),
Diagnostic(ERRID.ERR_ExpectedNext, "for x as object = 1 to 12"),
Diagnostic(ERRID.ERR_NextNoMatchingFor, "next"),
Diagnostic(ERRID.ERR_ExpectedEndIf, "if true"),
Diagnostic(ERRID.ERR_EndIfNoMatchingIf, "end if"),
Diagnostic(ERRID.ERR_ExpectedEndSyncLock, "synclock new Object()"),
Diagnostic(ERRID.ERR_EndSyncLockNoSyncLock, "end synclock"))
End Sub
<WorkItem(543724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543724")>
<Fact()>
Public Sub ElseIfStatementOutsideMethodBody()
ParseAndVerify(<![CDATA[
Class c6
else if
End Class
]]>,
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "else if "),
Diagnostic(ERRID.ERR_ExpectedExpression, ""))
End Sub
<WorkItem(544495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544495")>
<Fact>
Public Sub CatchFinallyStatementOutsideMethodBody()
ParseAndVerify(<![CDATA[
Catch ex As Exception
Finally
]]>, Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch ex As Exception"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Finally"))
End Sub
<WorkItem(544519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544519")>
<Fact>
Public Sub TryStatementOutsideMethodBody()
ParseAndVerify(<![CDATA[
Module Program
Public _Sub Main()
Try
End Try
End Sub
End Module
]]>, Diagnostic(ERRID.ERR_ExpectedEOS, "Main"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_EndTryNoTry, "End Try"),
Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub"))
End Sub
#End Region
<WorkItem(545543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545543")>
<Fact>
Public Sub ParseInvalidUseOfBlockWithinSingleLineLambda()
Dim compilationDef =
<compilation name="LambdaTests_err">
<file name="a.vb">
Module Program
Sub Main()
For i = 1 To 10
Dim x = Sub() For j = 1 To 10
Next j, i
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedNext, "For j = 1 To 10"),
Diagnostic(ERRID.ERR_ExtraNextVariable, "i"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "j").WithArguments("j"))
End Sub
<WorkItem(545543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545543")>
<ConditionalFact(GetType(WindowsOnly))>
Public Sub ParseValidUseOfBlockWithinMultiLineLambda()
Dim compilationDef =
<compilation name="LambdaTests_err">
<file name="a.vb">
Module Program
Sub Main()
For i = 1 To 10
Dim x = Sub()
End Sub
For j = 1 To 10
Next j, i
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation)
CompilationUtils.AssertNoErrors(compilation)
Dim NodeFound = From lambdaItem In compilation.SyntaxTrees(0).GetRoot.DescendantNodes.OfType(Of MultiLineLambdaExpressionSyntax)()
Select lambdaItem
Assert.Equal(1, NodeFound.Count)
End Sub
<WorkItem(545543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545543")>
<ConditionalFact(GetType(WindowsOnly))>
Public Sub ParseValidUseOfNonBlockWithinSingleLineLambda()
Dim compilationDef =
<compilation name="LambdaTests_err">
<file name="a.vb">
Module Program
Sub Main()
Dim Item = 0
For i = 1 To 10
Dim x = Sub() Item = 1
For j = 1 To 10
Next j, i
End Sub
End Module
</file>
</compilation>
'Should be No errors and a single line lambda is in use
Dim Compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(Compilation, <expected>
</expected>)
CompileAndVerify(Compilation)
Dim NodeFound1 = From lambdaItem In Compilation.SyntaxTrees(0).GetRoot.DescendantNodes.OfType(Of SingleLineLambdaExpressionSyntax)()
Select lambdaItem
Assert.Equal(1, NodeFound1.Count)
End Sub
<WorkItem(545543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545543")>
<ConditionalFact(GetType(WindowsOnly))>
Public Sub ParseValidUseOfBlockWithinSingleLineLambda()
'Subtle Variation with Single line Statement Lambda and a Block Construct
Dim compilationDef =
<compilation name="LambdaTests_err">
<file name="a.vb">
Module Program
Sub Main()
Dim Item = 0
For i = 1 To 10
Dim x = Sub() if true Then For j = 1 To 2 : Next j
Next i
End Sub
End Module
</file>
</compilation>
'Should be No errors and a single line lambda is in use
Dim Compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(Compilation, <expected>
</expected>)
CompileAndVerify(Compilation)
Dim NodeFound1 = From lambdaItem In Compilation.SyntaxTrees(0).GetRoot.DescendantNodes.OfType(Of SingleLineLambdaExpressionSyntax)()
Select lambdaItem
Assert.Equal(1, NodeFound1.Count)
End Sub
<WorkItem(530516, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530516")>
<Fact()>
Public Sub Bug530516()
Dim tree = ParseAndVerify(<![CDATA[
Class C
Implements I(
End Class
]]>,
<errors>
<error id="32093"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Implements IA(Of A()).IB(
End Class
]]>,
<errors>
<error id="32093"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Implements I()
End Class
]]>,
<errors>
<error id="32093"/>
<error id="30182"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Implements I(Of
End Class
]]>,
<errors>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=False)
tree = ParseAndVerify(<![CDATA[
Class C
Implements I(Of)
End Class
]]>,
<errors>
<error id="30182"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=False)
' No parse errors.
tree = ParseAndVerify(<![CDATA[
Class C
Implements I(Of A(Of B()).C(Of D()).E())
End Class
]]>)
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements I(
End Class
]]>,
<errors>
<error id="30287"/>
<error id="32093"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements IA(Of A()).IB(
End Class
]]>,
<errors>
<error id="32093"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements I().P
End Class
]]>,
<errors>
<error id="32093"/>
<error id="30182"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=True)
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements I(Of
End Class
]]>,
<errors>
<error id="30287"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=False)
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements I(Of).P
End Class
]]>,
<errors>
<error id="30182"/>
</errors>)
CheckTokensForIncompleteImplements(tree, ofMissing:=False)
' No parse errors.
tree = ParseAndVerify(<![CDATA[
Class C
Property P Implements I(Of A(Of B()).C(Of D()).E()).P
End Class
]]>)
End Sub
Private Shared Sub CheckTokensForIncompleteImplements(tree As SyntaxTree, ofMissing As Boolean)
Dim tokens = tree.GetRoot().DescendantTokens().ToArray()
' No tokens should be skipped.
Assert.False(tokens.Any(Function(t) t.HasStructuredTrivia))
' Find last '(' token.
Dim indexOfOpenParen = -1
For i = 0 To tokens.Length - 1
If tokens(i).Kind = SyntaxKind.OpenParenToken Then
indexOfOpenParen = i
End If
Next
Assert.NotEqual(indexOfOpenParen, -1)
' Of token may have been synthesized.
Dim ofToken = tokens(indexOfOpenParen + 1)
Assert.Equal(ofToken.Kind, SyntaxKind.OfKeyword)
Assert.Equal(ofToken.IsMissing, ofMissing)
' Type identifier must have been synthesized.
Dim identifierToken = tokens(indexOfOpenParen + 2)
Assert.Equal(identifierToken.Kind, SyntaxKind.IdentifierToken)
Assert.True(identifierToken.IsMissing)
End Sub
<WorkItem(546688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546688")>
<Fact()>
Public Sub Bug16568_If()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do : Loop
End Sub
End Module
]]>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do : : Loop
End Sub
End Module
]]>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30035"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do :
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do :
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do ::
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Do : :
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
End Sub
<WorkItem(546688, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546688")>
<Fact()>
Public Sub Bug16568_Else()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do : Loop
End Sub
End Module
]]>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do : : Loop
End Sub
End Module
]]>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30035"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do :
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do :
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do ::
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Do : :
Loop
End Sub
End Module
]]>,
<errors>
<error id="30083"/>
<error id="30091"/>
</errors>)
End Sub
<WorkItem(546734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546734")>
<Fact()>
Public Sub Bug16688()
Dim tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 :
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 :
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 : :
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 _
:
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 End Module
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module M
#Const x = 1 : End Module
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected." start="70" end="77"/>
</errors>)
End Sub
''' <summary>
''' Trivia up to and including the last colon on the line
''' should be associated with the preceding token.
''' </summary>
<Fact()>
Public Sub ParseTriviaFollowingColon_1()
Dim tree = ParseAndVerify(<![CDATA[
Module M
Sub M()
Call M0 : ' Comment
If True Then Call M1 : : Call M2
End Sub
End Module
]]>.Value.Trim())
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node.ToFullString().NormalizeLineEndings()).ToArray()
CheckArray(tokens,
"Module ",
"M" & vbCrLf,
" Sub ",
"M",
"(",
")" & vbCrLf,
" Call ",
"M0 :",
" ' Comment" & vbCrLf & " If ",
"True ",
"Then ",
"Call ",
"M1 : :",
" Call ",
"M2" & vbCrLf,
" End ",
"Sub" & vbCrLf,
"End ",
"Module",
"")
End Sub
<Fact()>
Public Sub ParseTriviaFollowingColon_2()
Dim tree = ParseAndVerify(<![CDATA[Interface I : : End Interface : : Class A :: Implements I :: End Class]]>)
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node.ToFullString()).ToArray()
CheckArray(tokens,
"Interface ",
"I : :",
" End ",
"Interface : :",
" Class ",
"A ::",
" Implements ",
"I ::",
" End ",
"Class",
"")
End Sub
<Fact()>
Public Sub ParseTriviaFollowingColon_3()
Dim tree = ParseAndVerify(<![CDATA[
<Assembly: B>
Class B
Inherits System.Attribute
Sub M()
L1: Exit Sub
End Sub
End Class
]]>)
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node).ToArray()
Dim token = tokens.First(Function(t) t.GetValueText() = ":")
Assert.Equal(token.ToFullString(), ": ")
token = tokens.First(Function(t) t.GetValueText() = "B")
Assert.Equal(token.ToFullString(), "B")
token = tokens.Last(Function(t) t.GetValueText() = "L1")
Assert.Equal(token.ToFullString(), "L1")
token = tokens.First(Function(t) t.GetValueText() = "Exit")
Assert.Equal(token.ToFullString(), " Exit ")
End Sub
<WorkItem(531059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531059")>
<Fact()>
Public Sub ParseSingleLineLambdaInSingleLineIf()
Dim tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main1()
If True Then Dim x = Function() Sub() Console.WriteLine :
Else Return
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
<error id="30086" message="'Else' must be preceded by a matching 'If' or 'ElseIf'."/>
<error id="30205" message="End of statement expected."/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
If True Then Dim x = Function() Sub() Console.WriteLine :: Else Return
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
If True Then Dim x = Function() Sub() Console.WriteLine : : Else Return
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement." start="101" end="118"/>
</errors>)
End Sub
<WorkItem(547060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547060")>
<Fact()>
Public Sub ParseSingleLineLambdaInSingleLineIf01()
Dim tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
If True Then Dim x = Function() Sub() Console.WriteLine : Else Return
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement." start="77" end="94"/>
</errors>)
tree = ParseAndVerify(<![CDATA[
Module Program
Sub Main()
If True Then Dim x = Function() Sub() Console.WriteLine Else Return
End Sub
End Module
]]>)
End Sub
<WorkItem(578144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578144")>
<Fact()>
Public Sub ParseStatementLambdaOnSingleLineLambdaWithColon()
Dim tree = ParseAndVerify(<![CDATA[
Module Module1
Sub Main()
Dim x = Sub() : Dim a1 = 1 : End Sub
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_SubRequiresSingleStatement, "Sub() "),
Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub"))
End Sub
<WorkItem(531086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531086")>
<Fact()>
Public Sub Bug17550()
ParseAndVerify("<!--" + vbCrLf,
<errors>
<error id="30035" message="Syntax error." start="0" end="4"/>
</errors>)
ParseAndVerify("%>" + vbCrLf,
<errors>
<error id="30035" message="Syntax error." start="0" end="2"/>
</errors>)
ParseAndVerify("<!-- :",
<errors>
<error id="30035" message="Syntax error." start="0" end="4"/>
</errors>)
ParseAndVerify("%> :",
<errors>
<error id="30035" message="Syntax error." start="0" end="2"/>
</errors>)
End Sub
<WorkItem(531102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531102")>
<Fact()>
Public Sub Bug17574_XmlAttributeAccess()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p :
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p::
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p::y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:: y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p: :
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p: :y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:'Comment
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:y
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:y:
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p: y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p : y
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.
@p
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@< ' comment
End Sub
End Module
]]>,
<errors>
<error id="31177" start="62" end="63"/>
<error id="31146" message="XML name expected." start="63" end="63"/>
<error id="30636" message="'>' expected." start="63" end="63"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:'Comment
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p::
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p::y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:: y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p: :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p: :y
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:y
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p: y
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p : y
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31177"/>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<p:y>
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.
@<p>
End Sub
End Module
]]>)
End Sub
<WorkItem(531102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531102")>
<Fact()>
Public Sub Bug17574_XmlElementAccess()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p::
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p::y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p:: y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p: :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p: :y
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p:y
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.<p> :
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.
<p>
End Sub
End Module
]]>)
End Sub
<WorkItem(531102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531102")>
<Fact()>
Public Sub Bug17574_XmlDescendantAccess()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...
End Sub
End Module
]]>,
<errors>
<error id="31165" message="Expected beginning '<' for an XML tag."/>
<error id="31146" message="XML name expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...:
End Sub
End Module
]]>,
<errors>
<error id="31165" message="Expected beginning '<' for an XML tag."/>
<error id="31146" message="XML name expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p:
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p::
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p::y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p:: y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p: :
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p: :y
End Sub
End Module
]]>,
<errors>
<error id="31177"/>
<error id="31146" message="XML name expected."/>
<error id="30636" message="'>' expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p:y
End Sub
End Module
]]>,
<errors>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...<p> :
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x...
<p>
End Sub
End Module
]]>)
End Sub
<WorkItem(531102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531102")>
<Fact()>
Public Sub Bug17574_Comment()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p 'comment
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:a Rem comment
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@Rem 'comment
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@p:Rem Rem comment
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@Rem:a 'comment
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@<Rem:Rem> Rem comment
End Sub
End Module
]]>)
End Sub
<WorkItem(531102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531102")>
<Fact()>
Public Sub Bug17574_Other()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@Return: Return
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="66" end="66"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = x.@xml:a: Return
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim b = <x/>.@xml:
y
End Sub
End Module
]]>,
<errors>
<error id="31146" message="XML name expected." start="48" end="48"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = <a :Return
End Sub
End Module
]]>,
<errors>
<error id="31151" message="Element is missing an end tag." start="66" end="66"/>
<error id="31177"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
<error id="31165"/>
<error id="30636" message="'>' expected." start="66" end="66"/>
</errors>)
End Sub
<WorkItem(531480, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531480")>
<Fact>
Public Sub ImplicitLineContinuationAfterQuery()
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() From c In ""
Distinct
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Function() From c In ""
Distinct
)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() From c In ""
Distinct
Is Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then x = From c In ""
Distinct : Return
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then x = From c In ""
Distinct : Return
End Module
]]>)
' Breaking change: Dev11 allows implicit
' line continuation after Distinct.
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then x = From c In ""
Distinct
: Return ' Dev11: no error
End Module
]]>,
<errors>
<error id="30689" message="Statement cannot appear outside of a method body."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If Nothing Is From c In ""
Distinct Then
End If
End Sub
End Module
]]>)
' Breaking change: Dev11 allows implicit
' line continuation after Distinct.
ParseAndVerify(<![CDATA[
Module M
Sub M()
If Nothing Is From c In ""
Distinct
Then ' Dev11: no error
End If
End Sub
End Module
]]>,
<errors>
<error id="30035" message="Syntax error."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If Nothing Is From c In "" Order By c _
Then
End If
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If Nothing Is From c In "" Order By c
Then
End If
End Sub
End Module
]]>,
<errors>
<error id="30035" message="Syntax error."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then x = From c In "" Order By c Ascending _
: Return
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then x = From c In "" Order By c Ascending
: Return
End Module
]]>,
<errors>
<error id="30689" message="Statement cannot appear outside of a method body."/>
</errors>)
End Sub
<WorkItem(531632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531632")>
<Fact()>
Public Sub ColonTerminatorFollowingXmlAttributeAccess()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x As Object
x = <x/>.@a:b:Return
End Sub
End Module
]]>)
End Sub
<WorkItem(547195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547195")>
<Fact()>
Public Sub ColonFollowingImplicitContinuation()
ParseAndVerify(<![CDATA[
Module M
Function M(x As Object) As Object
Return x.
:
End Function
End Module
]]>,
<errors>
<error id="30203" message="Identifier expected." start="46" end="46"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Function M(x As String) As Object
Return From c In x
:
End Function
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Function M(x As String) As Object
Return From c In
:
End Function
End Module
]]>,
<errors>
<error id="30201" message="Expression expected." start="46" end="46"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M(x As Object)
x = 1 +
:
End Sub
End Module
]]>,
<errors>
<error id="30201" message="Expression expected." start="46" end="46"/>
</errors>)
End Sub
<Fact()>
Public Sub ColonAtEndOfFile()
ParseAndVerify(<![CDATA[:]]>)
ParseAndVerify(<![CDATA[:::]]>)
ParseAndVerify(<![CDATA[: : :]]>)
ParseAndVerify(<![CDATA[: : : ]]>)
ParseAndVerify(<![CDATA[Module M :]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
</errors>)
ParseAndVerify(<![CDATA[Module M :::]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
</errors>)
ParseAndVerify(<![CDATA[Module M : : :]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
</errors>)
ParseAndVerify(<![CDATA[Module M : : : ]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
</errors>)
End Sub
<WorkItem(547305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547305")>
<Fact()>
Public Sub Bug547305()
ParseAndVerify(<![CDATA[
Module M
Function F() As C(
]]>,
<errors>
<error id="30625"/>
<error id="30027"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F = Function() As C(
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F = Function() As C(Of
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
<error id="30182"/>
<error id="30198"/>
</errors>)
' Unexpected tokens in lambda header.
ParseAndVerify(<![CDATA[
Module M
Private F = Function() As A B
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
<error id="30205"/>
</errors>)
' Unexpected tokens in lambda body.
ParseAndVerify(<![CDATA[
Module M
Private F = Function()
End Func
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
<error id="30678"/>
</errors>)
End Sub
<Fact()>
Public Sub ImplicitContinuationAfterFrom()
ParseAndVerify(<![CDATA[
Module M
Function M(x As String) As Object
Return From
c in x
End Function
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Function M(x As String) As Object
Return From
c in x
End Function
End Module
]]>,
<errors>
<error id="30800" message="Method arguments must be enclosed in parentheses." start="70" end="70"/>
<error id="30201" message="Expression expected." start="70" end="70"/>
</errors>)
End Sub
<WorkItem(552836, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552836")>
<Fact()>
Public Sub MoreNextVariablesThanBlockContexts()
ParseAndVerify(<![CDATA[
For x = 1 to 5
Next x, y,
]]>,
<errors>
<error id="30689"/>
<error id="30092"/>
<error id="30201"/>
<error id="32037"/>
</errors>)
ParseAndVerify(<![CDATA[
For Each x in Nothing
Next x, y, z
]]>,
<errors>
<error id="30689"/>
<error id="30092"/>
<error id="32037"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For x = 1 to 5
For Each y In Nothing
Next y, x, w, v, u, t, s
End Sub
End Module
]]>,
<errors>
<error id="32037"/>
</errors>)
End Sub
<WorkItem(553962, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553962")>
<Fact()>
Public Sub Bug553962()
ParseAndVerify(<![CDATA[
Module M
Private F <!--
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}!--
End Module
]]>.Value, FULLWIDTH_LESS_THAN_SIGN),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F <!-- :
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F <?
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}?
End Module
]]>.Value, FULLWIDTH_LESS_THAN_SIGN),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F ?>
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}>
End Module
]]>.Value, FULLWIDTH_QUESTION_MARK),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F </
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}/
End Module
]]>.Value, FULLWIDTH_LESS_THAN_SIGN),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F %>
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}>
End Module
]]>.Value, FULLWIDTH_PERCENT_SIGN),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Private F <!DOCTYPE
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F {0}!DOCTYPE
End Module
]]>.Value, FULLWIDTH_LESS_THAN_SIGN),
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<source>
Module M
Private F <![CDATA[
End Module
</source>.Value,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(String.Format(<source>
Module M
Private F {0}![CDATA[
End Module
</source>.Value, FULLWIDTH_LESS_THAN_SIGN),
<errors>
<error id="30034"/>
<error id="30203" message="Identifier expected."/>
</errors>)
ParseAndVerify(<source>
Module M
Sub M()
:<![CDATA[
]]>
End Sub
End Module
</source>.Value,
<errors>
<error id="30035"/>
<error id="30037"/>
<error id="30037"/>
</errors>)
ParseAndVerify(<source>
Module M
Sub M() _
Dim x = <![CDATA[
]]>
End Sub
End Module
</source>.Value,
<errors>
<error id="30205" message="End of statement expected."/>
<error id="30037"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(553962, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553962")>
<WorkItem(571807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/571807")>
<Fact()>
Public Sub Bug571807()
ParseAndVerify(<![CDATA[
Module M
Private F = <% Function()
End Function() %>
End Module
]]>,
<errors>
<error id="31151"/>
<error id="31169"/>
<error id="30249" message="'=' expected."/>
<error id="30035"/>
<error id="31165"/>
<error id="30636"/>
<error id="30430"/>
<error id="30205"/>
</errors>)
ParseAndVerify(String.Format(<![CDATA[
Module M
Private F = <% Function()
End Function() {0}>
End Module
]]>.Value, FULLWIDTH_PERCENT_SIGN),
<errors>
<error id="31151"/>
<error id="31169"/>
<error id="30249" message="'=' expected."/>
<error id="30035"/>
<error id="31165"/>
<error id="30636"/>
<error id="30430"/>
<error id="30205"/>
</errors>)
End Sub
<WorkItem(570756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570756")>
<Fact()>
Public Sub FullWidthKeywords()
Dim source = <![CDATA[
Class C
End Class
]]>.Value.ToFullWidth()
ParseAndVerify(source)
End Sub
<WorkItem(588122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/588122")>
<WorkItem(587130, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/587130")>
<Fact()>
Public Sub FullWidthKeywords001()
Dim source = <![CDATA[
Imports System.Security
<ASSEMBLY: CLSCompliant(True)>
#Const x = CDBL(0)
Module M
Dim x = CDBL(0)
End Module
]]>.Value.ToFullWidth()
ParseAndVerify(source)
End Sub
<WorkItem(571529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/571529")>
<Fact()>
Public Sub Bug571529()
ParseAndVerify(<![CDATA[
Module M
Private F = Sub()
Async:
M.F()
End Sub
End Module
]]>)
End Sub
<WorkItem(581662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581662")>
<Fact()>
Public Sub BlankLinesFollowingUnderscore()
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
_
_
Take 1
End Module
]]>)
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In ""
_
_
Take 1
End Module
]]>)
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
_
Take 1
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
_
Take 1
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
'Comment
Take 1
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
'Comment _
Take 1
End Module
]]>,
<errors>
<error id="30188" message="Declaration expected."/>
</errors>)
End Sub
<WorkItem(608214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608214")>
<Fact()>
Public Sub Bug608214()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then %
End Sub
End Module
]]>,
<errors>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Return : %
End Sub
End Module
]]>,
<errors>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Return Else %
End Sub
End Module
]]>,
<errors>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Return Else Return : %
End Sub
End Module
]]>,
<errors>
<error id="30037" message="Character is not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then 5 Else 6
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_Syntax, "5").WithLocation(4, 22)
)
End Sub
<WorkItem(608214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608214")>
<WorkItem(610345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610345")>
<Fact()>
Public Sub Bug608214_2()
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If True Then Return :
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If True Then Return : REM
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If True Then Return : _
: %>
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If True Then Return : _
:
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = <%= Sub() If True Then Return Else % :
End Module
]]>,
<errors>
<error id="31172" message="An embedded expression cannot be used here."/>
<error id="30037" message="Character is not valid."/>
<error id="31159" message="Expected closing '%>' for embedded expression."/>
</errors>)
End Sub
<WorkItem(608225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608225")>
<Fact()>
Public Sub Bug608225()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
End Module
]]>,
<errors>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return : _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return : End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : _
Sub M()
End Sub
End Module
]]>,
<errors>
<error id="30289"/>
<error id="30429" message="'End Sub' must be preceded by a matching 'Sub'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : _
<A> Dim y As Object
End Module
]]>,
<errors>
<error id="30660" message="Attributes cannot be applied to local variables."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then
Dim x = Sub() If True Then Else Return : _
Else
End If
End Sub
End Module
]]>,
<errors>
<error id="30086" message="'Else' must be preceded by a matching 'If' or 'ElseIf'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Sub() If True Then Return : _
Catch e As System.Exception
End Try
End Sub
End Module
]]>,
<errors>
<error id="30380" message="'Catch' cannot appear outside a 'Try' statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Sub() If True Then Return : _
Finally
End Try
End Sub
End Module
]]>,
<errors>
<error id="30382" message="'Finally' cannot appear outside a 'Try' statement."/>
</errors>)
End Sub
''' <summary>
''' Line continuation trivia should include the underscore only.
''' </summary>
<WorkItem(581662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581662")>
<Fact()>
Public Sub LineContinuationTrivia()
Dim source = <![CDATA[
Imports System.Linq
Module M
Dim x = From c In "" _
_
_
Take 1 _
End Module
]]>.Value
' Source containing underscores and spaces.
LineContinuationTriviaCore(source, "_")
' Source containing underscores and tabs.
LineContinuationTriviaCore(source.Replace(" "c, vbTab), "_")
' Source containing full-width underscores and spaces.
LineContinuationTriviaErr(source.Replace("_"c, FULLWIDTH_LOW_LINE), "" + FULLWIDTH_LOW_LINE)
End Sub
Private Sub LineContinuationTriviaCore(source As String, charAsString As String)
Dim tree = ParseAndVerify(source)
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node).ToArray()
Dim allTrivia = tree.GetRoot().DescendantTrivia().ToArray()
For Each trivia In allTrivia
If trivia.Kind = SyntaxKind.LineContinuationTrivia Then
Assert.Equal(trivia.Width, 1)
Assert.Equal(trivia.ToString(), charAsString)
End If
Next
End Sub
Private Sub LineContinuationTriviaErr(source As String, charAsString As String)
Dim tree = ParseAndVerify(source,
Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"),
Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"),
Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"),
Diagnostic(ERRID.ERR_ExpectedIdentifier, "_"))
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node).ToArray()
Dim allTrivia = tree.GetRoot().DescendantTrivia().ToArray()
For Each trivia In allTrivia
If trivia.Kind = SyntaxKind.LineContinuationTrivia Then
Assert.Equal(trivia.Width, 1)
Assert.Equal(trivia.ToString(), charAsString)
End If
Next
End Sub
''' <summary>
''' Each colon should be a separate trivia node.
''' </summary>
<WorkItem(612584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612584")>
<Fact()>
Public Sub ConsecutiveColonsTrivia()
Dim source = <![CDATA[
Module M
::
: :
Sub M()
10:::
20: : :
Label:::
:: M() :: : M() : ::
: : Return : :
End Sub
End Module
]]>.Value
ConsecutiveColonsTriviaCore(source, ":")
ConsecutiveColonsTriviaCore(source.Replace(":"c, FULLWIDTH_COLON), FULLWIDTH_COLON_STRING)
End Sub
Private Sub ConsecutiveColonsTriviaCore(source As String, singleColon As String)
Dim tree = ParseAndVerify(source)
Dim tokens = tree.GetRoot().DescendantTokens().Select(Function(t) t.Node).ToArray()
Dim allTrivia = tree.GetRoot().DescendantTrivia().ToArray()
For Each trivia In allTrivia
If trivia.Kind = SyntaxKind.ColonTrivia Then
Assert.Equal(trivia.Width, 1)
Assert.Equal(trivia.ToString(), singleColon)
End If
Next
End Sub
<Fact()>
Public Sub CanFollowExpression()
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() Return)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then Return)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then Else)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then Else Return)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then If False Then Else)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then If False Then Else : Else)
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() Return, y = Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return, y = Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else, y = Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return, y = Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If False Then Else, y = Nothing
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If False Then Else : Else, y = Nothing
End Module
]]>)
End Sub
<WorkItem(619627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619627")>
<Fact()>
Public Sub OuterEndWithinMultiLineLambda()
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() As Object Else End Module]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="36674"/>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then
Else Return
End If
End Sub
End Module]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then
Else End Module]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="30081" message="'If' must end with a matching 'End If'."/>
<error id="30622"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
Else End Module]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="30086" message="'Else' must be preceded by a matching 'If' or 'ElseIf'."/>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then : Else End Module]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="30081" message="'If' must end with a matching 'End If'."/>
<error id="30622"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For Each c in ""
Dim x = Sub()
If True Then : Else Next : End If
End Sub
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="30092"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For Each c in ""
Dim x = Function()
If True Then : Else Next : End If
End Function
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="30092"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For Each c in ""
Dim x = Function()
If True Then If False Then : Else Next : End If
End Function
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For Each c in ""
Dim x = Sub() If True Then : Else Next : End If
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="30092"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Sub()
Catch
End Sub
End Try
End Sub
End Module
]]>,
<errors>
<error id="30384"/>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="30383"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Function()
Finally
End Function
End Try
End Sub
End Module
]]>,
<errors>
<error id="36674" message="Multiline lambda expression is missing 'End Function'."/>
<error id="30430"/>
</errors>)
End Sub
<WorkItem(620546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620546")>
<Fact()>
Public Sub NestedMultiLineBlocksInSingleLineIf()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else While True : Using Nothing
End Using : End While
End Sub
End Module
]]>,
<errors>
<error id="30082"/>
<error id="36008"/>
<error id="36007"/>
<error id="30090"/>
</errors>)
End Sub
<Fact()>
Public Sub SingleLineSubMultipleStatements()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() While True : End While
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() While True : End While : M()
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() M() : Using Nothing : End Using
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() Using Nothing : M() : End Using
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() Using Nothing : While True : End While : End Using
End Sub
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
End Sub
<Fact()>
Public Sub MoreLambdasAndSingleLineIfs()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Dim y = Sub() If False Then Else Return Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Dim y = Sub() If False Then Else Return Else
End Module
]]>)
' Dev11 (incorrectly) reports BC30086.
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Dim y = Sub() If False Then Else Else
End Sub
End Module
]]>)
' Dev11 (incorrectly) reports BC30086.
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Dim y = Sub() If False Then Else Else
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Dim y = Sub() If False Then Else Else
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_ExpectedEOS, "Else").WithLocation(4, 60))
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Dim y = Sub() If False Then Else Else
End Module
]]>,
<errors>
<error id="30205" message="End of statement expected."/>
</errors>)
End Sub
<Fact()>
Public Sub IncompleteSingleLineIfs()
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then E
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then End E
End Sub
End Module
]]>,
<errors>
<error id="30678" message="'End' statement not valid."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else E
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else End E
End Sub
End Module
]]>,
<errors>
<error id="30678" message="'End' statement not valid."/>
</errors>)
End Sub
<Fact()>
Public Sub SelectOrSelectCase()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() If True Then Return Select o
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() If True Then Else Return Select o
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() If True Then Else Select o
End Sub
End Module
]]>,
<errors>
<error id="30095" message="'Select Case' must end with a matching 'End Select'."/>
</errors>)
End Sub
''' <summary>
''' See reference to Dev10#708061 for ambiguity regarding
''' "End Select" in single-line lambda.
''' </summary>
<Fact()>
Public Sub SelectOrEndSelect()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() Return Select o
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() End Select o
End Sub
End Module
]]>,
<errors>
<error id="30088" message="'End Select' must be preceded by a matching 'Select Case'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() If True Then End Select o
End Sub
End Module
]]>,
<errors>
<error id="30088" message="'End Select' must be preceded by a matching 'Select Case'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = From o In Sub() If True Then Else End Select o
End Sub
End Module
]]>,
<errors>
<error id="30088" message="'End Select' must be preceded by a matching 'Select Case'."/>
</errors>)
End Sub
<WorkItem(622712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622712")>
<Fact()>
Public Sub ColonTerminatorWithTrailingTrivia()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : _
:
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Else Return : _
: 'Comment
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() While True : _
: End While
End Module
]]>,
<errors>
<error id="36918" message="Single-line statement lambdas must include exactly one statement."/>
</errors>)
End Sub
<WorkItem(623023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/623023")>
<Fact()>
Public Sub SingleLineIfWithinNestedSingleLineBlocks()
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub() If True Then Return End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub() If True Then Return _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub() If True Then Else Return End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub() If True Then Else Return _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Dim y = Sub() If True Then Else Return End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If False Then Dim y = Sub() If True Then If False Then Else Return End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then If False Then Else Dim y = Sub() If True Then If False Then Return _
End Module
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'."/>
<error id="30201" message="Expression expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Function() (Sub() If True Then Else))
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Function() (Sub() If True Then If False Then Else))
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = (Sub() If True Then Else Dim y = (Sub() If True Then Else))
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Dim x = (Sub() If False Then Else) Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Dim x = (Sub() If False Then Else)
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Dim x = (Sub() If False Then If True Then Else If False Then Else) Else
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() (Sub() If True Then While True : If False Then Else)
End Module
]]>,
<errors>
<error id="30082" message="'While' must end with a matching 'End While'."/>
<error id="30198" message="')' expected."/>
<error id="30205" message="End of statement expected."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub()
Dim y = (Sub() If True Then Else)
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function() Sub()
Dim y = Sub() If True Then Else Return _
End Sub
End Module
]]>,
<errors>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="30201" message="Expression expected."/>
</errors>)
End Sub
''' <summary>
''' Consecutive colons are handled differently by the
''' scanner if the colons are on the same line vs.
''' separate lines with line continuations.
''' </summary>
<WorkItem(634703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634703")>
<Fact>
Public Sub MultipleColons()
CheckMethodStatementsAndTrivia(<![CDATA[
Module M
Sub M()
Return : : :
End Sub
End Module
]]>,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubBlock,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ReturnStatement,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndSubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.EndModuleStatement)
CheckMethodStatementsAndTrivia(<![CDATA[
Module M
Sub M()
Return : _
: _
:
End Sub
End Module
]]>,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubBlock,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ReturnStatement,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.LineContinuationTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.LineContinuationTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndSubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.EndModuleStatement)
CheckMethodStatementsAndTrivia(<![CDATA[
Module M
Sub M()
If True Then Return : : :
End Sub
End Module
]]>,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubBlock,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SingleLineIfStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.ReturnStatement,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.EmptyStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndSubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.EndModuleStatement)
CheckMethodStatementsAndTrivia(<![CDATA[
Module M
Sub M()
If True Then Return : _
: _
:
End Sub
End Module
]]>,
SyntaxKind.ModuleBlock,
SyntaxKind.ModuleStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubBlock,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.SingleLineIfStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.ReturnStatement,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.LineContinuationTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EmptyStatement,
SyntaxKind.ColonTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.LineContinuationTrivia,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EmptyStatement,
SyntaxKind.ColonTrivia,
SyntaxKind.EmptyStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.WhitespaceTrivia,
SyntaxKind.EndSubStatement,
SyntaxKind.EndOfLineTrivia,
SyntaxKind.EndModuleStatement)
End Sub
Private Sub CheckMethodStatementsAndTrivia(source As Xml.Linq.XCData, ParamArray expectedStatementsAndTrivia() As SyntaxKind)
Dim tree = ParseAndVerify(source.Value.Trim())
Dim actualStatementsAndTrivia = tree.GetRoot().
DescendantNodesAndSelf().
Where(Function(n) TypeOf n Is StatementSyntax).
SelectMany(Function(s) s.GetLeadingTrivia().Select(Function(trivia) trivia.Kind()).Concat({s.Kind()}).Concat(s.GetTrailingTrivia().Select(Function(trivia) trivia.Kind()))).
ToArray()
CheckArray(actualStatementsAndTrivia, expectedStatementsAndTrivia)
End Sub
''' <summary>
''' Scanner needs to handle comment trivia at the start of a statement,
''' even when the statement is not the first on the line.
''' </summary>
<Fact()>
Public Sub CommentAtStartOfStatementNotFirstOnLine()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return :'Comment
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return :rem
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : REM Comment
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return : _
REM Comment
End Module
]]>)
End Sub
<WorkItem(638187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638187")>
<Fact()>
Public Sub IsNextStatementInsideLambda()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
Return :
Sub F()
End Sub
End Module
]]>,
<errors>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
10:
Sub F()
End Sub
End Module
]]>,
<errors>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
10: Sub F()
End Sub
End Module
]]>,
<errors>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
<error id="32009"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
10
Sub F()
End Sub
End Module
]]>,
<errors>
<error id="30801"/>
<error id="36673" message="Multiline lambda expression is missing 'End Sub'."/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Return :
Sub F()
End Sub
End Module
]]>)
End Sub
<Fact()>
Public Sub IsNextStatementInsideLambda_2()
ParseAndVerify(<![CDATA[
Module M
Sub M()
For i = 0 To 5
Dim x = Sub()
10: Call M()
Next
End Sub
End Sub
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For i = 0 To 5
Dim x = Sub()
10:
Next
End Sub
End Sub
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For i = 0 To 5
Dim x = Sub()
10: Next
End Sub
End Sub
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
For i = 0 To 5
Dim x = Sub()
10 Next
End Sub
End Sub
End Module
]]>,
<errors>
<error id="30084"/>
<error id="30801"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Sub()
Finally
End Sub
End Try
End Sub
End Module
]]>,
<errors>
<error id="30384"/>
<error id="36673"/>
<error id="30383"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Try
Dim x = Sub()
10:
Finally
End Sub
End Try
End Sub
End Module
]]>,
<errors>
<error id="30384"/>
<error id="36673"/>
<error id="30383"/>
<error id="30429"/>
</errors>)
End Sub
''' <summary>
''' Should parse (and report errors in) a statement
''' following a label even if the label is invalid.
''' Currently, any statement on the same line as
''' the invalid label is ignored.
''' </summary>
<WorkItem(642558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642558")>
<Fact()>
Public Sub ErrorInStatementFollowingInvalidLabel()
ParseAndVerify(<![CDATA[
Module M
Sub M()
10
Call
End Sub
End Module
]]>,
<errors>
<error id="30801"/>
<error id="30201"/>
</errors>)
' Dev11 reports 30801 and 30201.
ParseAndVerify(<![CDATA[
Module M
Sub M()
10 Call
End Sub
End Module
]]>,
<errors>
<error id="30801"/>
</errors>)
End Sub
<Fact()>
Public Sub LabelsFollowedByStatementsWithTrivia()
ParseAndVerify(<![CDATA[
Module M
Sub M()
10: 'Comment
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
10: _
_
:
End Sub
End Module
]]>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
10'Comment
End Sub
End Module
]]>,
<errors>
<error id="30801"/>
</errors>)
End Sub
<WorkItem(640520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640520")>
<Fact()>
Public Sub Bug640520()
ParseAndVerify(<![CDATA[
Class C
Sub M()
End : Sub
Public Custom Event E
End Event
End Class
]]>,
<errors>
<error id="30026"/>
<error id="30289"/>
<error id="32009"/>
<error id="30026"/>
<error id="30203"/>
<error id="30289"/>
<error id="31122"/>
<error id="31123"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Sub M()
End : Sub
<A> Custom Event E
End Event
End Class
]]>,
<errors>
<error id="30026"/>
<error id="30289"/>
<error id="32009"/>
<error id="30026"/>
<error id="30203"/>
<error id="30289"/>
<error id="31122"/>
<error id="31123"/>
</errors>)
End Sub
<WorkItem(648998, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/648998")>
<Fact()>
Public Sub Bug648998()
Dim tree = Parse(<![CDATA[
Module M
Dim x = F(a:=False,
Dim y, z = Nothing
End Module
]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
tree.AssertTheseDiagnostics(<errors><![CDATA[
BC30201: Expression expected.
Dim y, z = Nothing
~
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
Dim y, z = Nothing
~
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
Dim y, z = Nothing
~~~~~~~~~~~
BC30198: ')' expected.
Dim y, z = Nothing
~
]]></errors>)
tree = Parse(<![CDATA[
Module M
Dim x = F(a:=False,
Dim y()
End Module
]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
tree.AssertTheseDiagnostics(<errors><![CDATA[
BC30201: Expression expected.
Dim y()
~
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
Dim y()
~
]]></errors>)
tree = Parse(<![CDATA[
Module M
Dim x = F(a:=False,
Dim y
End Module
]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
tree.AssertTheseDiagnostics(<errors><![CDATA[
BC30201: Expression expected.
Dim y
~
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
Dim y
~
BC30198: ')' expected.
Dim y
~
]]></errors>)
tree = Parse(<![CDATA[
Module M
Dim x = F(a:=False,
b True,
c:=Nothing)
End Module
]]>, options:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3))
tree.AssertTheseDiagnostics(<errors><![CDATA[
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
b True,
~
BC32017: Comma, ')', or a valid expression continuation expected.
b True,
~~~~
BC30198: ')' expected.
b True,
~
BC30201: Expression expected.
b True,
~
BC30241: Named argument expected. Please use language version 15.5 or greater to use non-trailing named arguments.
b True,
~
BC30188: Declaration expected.
c:=Nothing)
~
]]></errors>)
End Sub
<WorkItem(649162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649162")>
<Fact()>
Public Sub Bug649162()
ParseAndVerify(<![CDATA[
Imports <xmlns:=''>, Imports <xmlns::=''>, Imports <xmlns==''>
]]>,
<errors>
<error id="31146"/>
<error id="30183"/>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Imports <xmlns:=''>, Imports <xmlns::=''>, Imports <xmlns==''>
]]>.Value.Replace(":"c, FULLWIDTH_COLON).Replace("="c, FULLWIDTH_EQUALS_SIGN),
<errors>
<error id="31187"/>
<error id="30636"/>
<error id="31170"/>
<error id="30183"/>
<error id="30035"/>
</errors>)
End Sub
<WorkItem(650318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650318")>
<Fact()>
Public Sub Bug650318()
ParseAndVerify(<![CDATA[
Module M
Sub M()
x ::= Nothing
End Sub
End Module
]]>,
<errors>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
x : : = Nothing
End Sub
End Module
]]>,
<errors>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
x : : = Nothing
End Sub
End Module
]]>.Value.Replace(":"c, FULLWIDTH_COLON).Replace("="c, FULLWIDTH_EQUALS_SIGN),
<errors>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
::= Nothing
End Sub
End Module
]]>,
<errors>
<error id="30035"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
::= Nothing
End Sub
End Module
]]>.Value.Replace(":"c, FULLWIDTH_COLON).Replace("="c, FULLWIDTH_EQUALS_SIGN),
<errors>
<error id="30035"/>
</errors>)
End Sub
<WorkItem(671115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/671115")>
<Fact()>
Public Sub IsNewLine()
Dim sourceFormat = "Module M{0} Dim x = 1 'Comment{0}End Module{0}"
ParseAndVerify(String.Format(sourceFormat, CARRIAGE_RETURN))
ParseAndVerify(String.Format(sourceFormat, LINE_FEED))
ParseAndVerify(String.Format(sourceFormat, NEXT_LINE))
ParseAndVerify(String.Format(sourceFormat, LINE_SEPARATOR))
ParseAndVerify(String.Format(sourceFormat, PARAGRAPH_SEPARATOR))
End Sub
<WorkItem(674590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674590")>
<Fact()>
Public Sub Bug674590()
ParseAndVerify(<![CDATA[
Class C
Shared Operator</
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Shared Operator %>
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Shared Operator <!--
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Shared Operator <? 'Comment
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Shared Operator <![CDATA[ _
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Shared Operator <!DOCTYPE
End Operator
End Class
]]>,
<errors>
<error id="30199"/>
<error id="30198"/>
</errors>)
ParseAndVerify(<source>
Class C
Shared Operator ]]>
End Operator
End Class
</source>.Value,
<errors>
<error id="30199"/>
<error id="30198"/>
<error id="33000"/>
<error id="30037"/>
</errors>)
End Sub
<WorkItem(684860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684860")>
<Fact()>
Public Sub Bug684860_SkippedTokens()
Const n = 100000
' 100000 instances of "0+" in:
' Class C
' Dim x = M(0 0+0+0+...)
' End Class
Dim builder = New System.Text.StringBuilder()
builder.AppendLine("Class C")
builder.Append(" Dim x = M(0 ")
For i = 0 To n
builder.Append("0+")
Next
builder.AppendLine(")")
builder.AppendLine("End Class")
Dim text = builder.ToString()
Dim tree = VisualBasicSyntaxTree.ParseText(text)
Dim root = tree.GetRoot()
Dim walker = New TokenAndTriviaWalker()
walker.Visit(root)
Assert.True(walker.Tokens > n)
Dim tokens1 = root.DescendantTokens(descendIntoTrivia:=False).ToArray()
Dim tokens2 = root.DescendantTokens(descendIntoTrivia:=True).ToArray()
Assert.True((tokens2.Length - tokens1.Length) > n)
End Sub
<WorkItem(684860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684860")>
<Fact()>
Public Sub Bug684860_XmlText()
Const n = 100000
' 100000 instances of "<" in:
' ''' <x a="<<<..."/>
' Class C
' End Class
Dim builder = New System.Text.StringBuilder()
builder.Append("''' <x a=""")
For i = 0 To n
builder.Append("<")
Next
builder.AppendLine("""/>")
builder.AppendLine("Class C")
builder.AppendLine("End Class")
Dim text = builder.ToString()
Dim tree = VisualBasicSyntaxTree.ParseText(text, options:=New VisualBasicParseOptions(documentationMode:=DocumentationMode.Parse))
Dim root = tree.GetRoot()
Dim walker = New TokenAndTriviaWalker()
walker.Visit(root)
Assert.True(walker.Tokens > n)
Dim tokens = root.DescendantTokens(descendIntoTrivia:=True).ToArray()
Assert.True(tokens.Length > n)
End Sub
Private NotInheritable Class TokenAndTriviaWalker
Inherits VisualBasicSyntaxWalker
Public Tokens As Integer
Public Sub New()
MyBase.New(SyntaxWalkerDepth.StructuredTrivia)
End Sub
Public Overrides Sub VisitToken(token As SyntaxToken)
Tokens += 1
MyBase.VisitToken(token)
End Sub
End Class
<WorkItem(685268, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685268")>
<Fact()>
Public Sub Bug685268()
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then Sub M()
Return
End Sub
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
<error id="30429"/>
</errors>)
End Sub
<WorkItem(685474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685474")>
<Fact()>
Public Sub Bug685474()
ParseAndVerify(<![CDATA[
<A(Sub()
End Su
b
]]>,
<errors>
<error id="36673"/>
<error id="30678"/>
<error id="30198"/>
<error id="30636"/>
</errors>)
ParseAndVerify(<![CDATA[
<A(Sub()
End Su
b
'One
'Two
]]>,
<errors>
<error id="36673"/>
<error id="30678"/>
<error id="30198"/>
<error id="30636"/>
</errors>)
End Sub
<WorkItem(697117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697117")>
<Fact()>
Public Sub Bug697117()
ParseAndVerify(<![CDATA[
Module M
Sub M()
Return Function()
Declare Function F()
]]>,
<errors>
<error id="30625"/>
<error id="30026"/>
<error id="36674"/>
<error id="30289"/>
<error id="30218"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Return Function()
Delegate Function F()
]]>,
<errors>
<error id="30625"/>
<error id="30026"/>
<error id="36674"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Return Function()
Delegate Sub F()
End Module
]]>,
<errors>
<error id="30026"/>
<error id="36674"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function()
Declare Function F()
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
<error id="30218"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Function()
Delegate Function F()
]]>,
<errors>
<error id="30625"/>
<error id="36674"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() Declare Sub F()
End Module
]]>,
<errors>
<error id="30289"/>
<error id="30218"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() Delegate Sub F()
End Module
]]>,
<errors>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() Imports I
End Module
]]>,
<errors>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
Imports I
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
If True Then Imports I
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Delegate Function F()
End Module
]]>,
<errors>
<error id="30026"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub()
If True Then Delegate Function F()
End Module
]]>,
<errors>
<error id="30026"/>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
If True Then Else Delegate Function F()
End Module
]]>,
<errors>
<error id="30026"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub() If True Then Delegate Sub F()
End Module
]]>,
<errors>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then Else Delegate Sub F()
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Sub M()
Dim x = Sub() If True Then Else Delegate Function F()
End Module
]]>,
<errors>
<error id="30026"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then Return : Event E
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
If True Then Return : Inherits I
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then Else Property P
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub() If True Then Else Implements I
End Class
]]>,
Diagnostic(ERRID.ERR_InvInsideProc, "Implements I").WithLocation(3, 37))
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
If True Then Else Imports I
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then If False Then Else Return : Private Class C
End Class
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Module M
Dim x = Sub()
If True Then Else Return : _
Friend Protected Enum E
End Enum
End Module
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
If True Then Else Return : _
Option Strict On
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Function F()
Return Sub()
Return : Implements I
End Function
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
Return : _
Imports I
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Function F()
Using Nothing
Return Sub()
Return : End Using
End Sub
End Function
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30429"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Sub M()
Using Nothing
Dim x = Sub() If True Then End Using
End Sub
End Class
]]>,
<errors>
<error id="36008"/>
<error id="32005"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Sub M()
Try
Dim x = Sub() If True Then Catch e
End Try
End Sub
End Class
]]>,
<errors>
<error id="30380"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Sub M()
If True Then
Dim x = Sub() Else
End If
End Sub
End Class
]]>,
<errors>
<error id="30086"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub() <A>Delegate Sub D()
End Class
]]>,
<errors>
<error id="32035"/>
<error id="30660"/>
<error id="30183"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub() If True Then Return : <A> Property P
End Class
]]>,
<errors>
<error id="30289"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub() If True Then Else <A> Property P
End Class
]]>,
Diagnostic(ERRID.ERR_InvInsideEndsProc, "<A> Property P").WithLocation(3, 37))
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
If True Then Return : _
<A>
Enum E
End Enum
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30289"/>
</errors>)
End Sub
<WorkItem(716242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716242")>
<Fact()>
Public Sub Bug716242()
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
Select Case x
Delegate Function F()
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30095"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub() Select Case x : _
Delegate Function F()
End Class
]]>,
<errors>
<error id="30095"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
Select Case x
Option Strict On
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30095"/>
<error id="30058"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Function F()
Return Sub() If True Then Select Case x : _
Implements I
End Function
End Class
]]>,
<errors>
<error id="30095"/>
<error id="30058"/>
<error id="30024"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Sub M()
Using Nothing
Dim x = Sub()
Select Case x
End Using
End Sub
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30095"/>
</errors>)
ParseAndVerify(<![CDATA[
Class C
Dim x = Sub()
Select Case x
<A>
Enum E
End Enum
End Class
]]>,
<errors>
<error id="36673"/>
<error id="30095"/>
</errors>)
End Sub
Private Shared Sub CheckArray(Of T)(actual As T(), ParamArray expected As T())
Assert.Equal(expected.Length, actual.Length)
For i = 0 To actual.Length - 1
Assert.Equal(expected(i), actual(i))
Next
End Sub
<WorkItem(539515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539515")>
<Fact()>
Public Sub ParseIllegaLineCont()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
_
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_LineContWithCommentOrNoPrecSpace, "_").WithLocation(4, 1)
)
End Sub
<WorkItem(539515, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539515")>
<Fact()>
Public Sub ParseIllegaLineCont_1()
ParseAndVerify(
<![CDATA[
Module M
Sub Main() _
_
_
_
End Sub
End Module
]]>,
Diagnostic(ERRID.ERR_LineContWithCommentOrNoPrecSpace, "_").WithLocation(6, 1)
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithNoSpaceBeforeCommentV16()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _' Comment
= 1
End Sub
End Module
]]>, New VisualBasicParseOptions(LanguageVersion.VisualBasic16)
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithMultipleSpacesBeforeCommentV16()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _ ' Comment
= 1
End Sub
End Module
]]>, New VisualBasicParseOptions(LanguageVersion.VisualBasic16)
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithCommentV16()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _ ' Comment
= 1
End Sub
End Module
]]>, New VisualBasicParseOptions(LanguageVersion.VisualBasic16)
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithCommentV15()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _ ' Comment
= 1
End Sub
End Module
]]>, New VisualBasicParseOptions(LanguageVersion.VisualBasic15),
Diagnostic(ERRID.ERR_CommentsAfterLineContinuationNotAvailable1, "' Comment").WithLocation(4, 36).WithArguments("16")
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithCommentV15_5()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _ ' Comment
= 1
End Sub
End Module
]]>, New VisualBasicParseOptions(LanguageVersion.VisualBasic15_5),
Diagnostic(ERRID.ERR_CommentsAfterLineContinuationNotAvailable1, "' Comment").WithLocation(4, 36).WithArguments("16")
)
End Sub
<Fact()>
<WorkItem(65, "https://github.com/dotnet/vblang/issues/65")>
Public Sub ParseLineContWithoutComment()
ParseAndVerify(
<![CDATA[
Module M
Sub Main()
Dim I As Integer _
= 1
End Sub
End Module
]]>
)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_01()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
If val Is Nothing Then r = "null" System.Console.WriteLine(1)
If val Is Nothing Then r = Function() "null" System.Console.WriteLine(2)
If val Is Nothing Then r = "+" Else r = "-" System.Console.WriteLine(3)
If val Is Nothing Then r = "+" Else r = Function() "-" System.Console.WriteLine(4)
If val Is Nothing Then : System.Console.WriteLine(5)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then r = "null" System.Console.WriteLine(1)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = Function() "null" System.Console.WriteLine(2)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else r = "-" System.Console.WriteLine(3)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else r = Function() "-" System.Console.WriteLine(4)
~~~~~~
BC30081: 'If' must end with a matching 'End If'.
If val Is Nothing Then : System.Console.WriteLine(5)
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_02()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test2(val As Object)
Dim r As Object
If val Is Nothing Then r = "+" Else : System.Console.WriteLine(6)
r = Sub() If val Is Nothing Then r = "null" System.Console.WriteLine(7)
r = Sub() If val Is Nothing Then r = "+" Else r = "-" System.Console.WriteLine(8)
r = Sub() If val Is Nothing Then r = "null" : System.Console.WriteLine(9)
r = Sub() If val Is Nothing Then r = "+" Else r = "-" : System.Console.WriteLine(10)
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(11)
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(12) Else
If val Is Nothing Then r = Function() "+" Else r = "-" System.Console.WriteLine(13)
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(14) Else
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then r = "null" System.Console.WriteLine(7)
~~~~~~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then r = "+" Else r = "-" System.Console.WriteLine(8)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(12) Else
~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = Function() "+" Else r = "-" System.Console.WriteLine(13)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(14) Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_03()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test3(val As Object)
Dim r As Object
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
End If
End Sub
Sub Test4(val As Object)
Dim r As Object
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
~~~~
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_04()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test5(val As Object)
Dim r As Object
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(17) : Else
End If
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(18) : Else
End If
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(19)
Else
End If
If val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(20)
Else
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(17) : Else
~~~~
BC36918: Single-line statement lambdas must include exactly one statement.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(18) : Else
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(18) : Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_05()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test3(val As Object)
Dim r As Object
If val Is Nothing Then
ElseIf val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
End If
End Sub
Sub Test4(val As Object)
Dim r As Object
If val Is Nothing Then
ElseIf val Is Nothing Then
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
~~~~
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_06()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test3(val As Object)
Dim r As Object
If val Is Nothing Then
Else
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
End If
End Sub
Sub Test4(val As Object)
Dim r As Object
If val Is Nothing Then
Else
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(15) Else
~~~~
BC30205: End of statement expected.
If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(16) Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_07()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(1) Else
End Sub
Sub Test2(val As Object)
Dim r As Object
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(2) Else
End Sub
Sub Test3(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(3) Else
End If
End Sub
Sub Test4(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(4) Else
End If
End Sub
Sub Test5(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(5) : Else
End If
End Sub
Sub Test6(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(6) : Else
End If
End Sub
Sub Test7(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(7)
Else
End If
End Sub
Sub Test8(val As Object)
Dim r As Object
If val Is Nothing Then
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(8)
Else
End If
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(1) Else
~~~~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(2) Else
~~~~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(3) Else
~~~~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(4) Else
~~~~
BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(5) : Else
~~~~
BC36918: Single-line statement lambdas must include exactly one statement.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(6) : Else
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'.
r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(6) : Else
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_08()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
If val Is Nothing Then r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else System.Console.WriteLine(1) Else System.Console.WriteLine(1)
If val Is Nothing Then r = Sub() If val Is Nothing Then If val Is Nothing Then r = "+" Else r = "-" Else r = Sub() System.Console.WriteLine(2) Else System.Console.WriteLine(2)
If val Is Nothing Then r = Sub() r = "-" Else System.Console.WriteLine(3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_09()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
If val Is Nothing Then r = Sub() System.Console.WriteLine(1) ,
If val Is Nothing Then r = Sub() If val Is Nothing Then System.Console.WriteLine(2) ,
If val Is Nothing Then r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(3) ,
r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(4) ,
r = Sub() r = Sub()
If val Is Nothing Then r = "+" Else System.Console.WriteLine(5) ,
End Sub
r = Function() Function()
If val Is Nothing Then r = "+" Else System.Console.WriteLine(6) ,
return 0
End Function
r = Sub() r = Sub()
If val Is Nothing Then System.Console.WriteLine(7) ,
End Sub
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() System.Console.WriteLine(1) ,
~
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() If val Is Nothing Then System.Console.WriteLine(2) ,
~
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(3) ,
~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(4) ,
~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else System.Console.WriteLine(5) ,
~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else System.Console.WriteLine(6) ,
~
BC30205: End of statement expected.
If val Is Nothing Then System.Console.WriteLine(7) ,
~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_10()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
If val Is Nothing Then r = Sub() System.Console.WriteLine(1) System.Console.WriteLine(1)
If val Is Nothing Then r = Sub() If val Is Nothing Then System.Console.WriteLine(2) System.Console.WriteLine(2)
If val Is Nothing Then r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(3) System.Console.WriteLine(3)
r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(4) System.Console.WriteLine(4)
r = Sub() r = Sub()
If val Is Nothing Then r = "+" Else System.Console.WriteLine(5) System.Console.WriteLine(5)
End Sub
r = Function() Function()
If val Is Nothing Then r = "+" Else System.Console.WriteLine(6) System.Console.WriteLine(6)
return 0
End Function
r = Sub() r = Sub()
If val Is Nothing Then System.Console.WriteLine(7) System.Console.WriteLine(7)
End Sub
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() System.Console.WriteLine(1) System.Console.WriteLine(1)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() If val Is Nothing Then System.Console.WriteLine(2) System.Console.WriteLine(2)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(3) System.Console.WriteLine(3)
~~~~~~
BC30205: End of statement expected.
r = Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(4) System.Console.WriteLine(4)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else System.Console.WriteLine(5) System.Console.WriteLine(5)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then r = "+" Else System.Console.WriteLine(6) System.Console.WriteLine(6)
~~~~~~
BC30205: End of statement expected.
If val Is Nothing Then System.Console.WriteLine(7) System.Console.WriteLine(7)
~~~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_11()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1(val As Object)
Dim r As Object
r = Function() Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(1) Else System.Console.WriteLine(1)
If val Is Nothing Then r = Function() Sub() If val Is Nothing Then r = "-" Else System.Console.WriteLine(2) Else System.Console.WriteLine(2)
If val Is Nothing Then If val Is Nothing Then If val Is Nothing Then If val Is Nothing Then r = "3" Else Else Else Else System.Console.WriteLine(3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30205: End of statement expected.
r = Function() Sub() If val Is Nothing Then r = "+" Else System.Console.WriteLine(1) Else System.Console.WriteLine(1)
~~~~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_12()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim d = Test1()()
d(Nothing)
d(d)
Test2(Nothing)
Test2(d)
d = test3()
d(Nothing)
d(d)
End Sub
Function Test1() As System.Func(Of System.Action(Of Object))
Dim r As System.Func(Of System.Action(Of Object))
r = Function() Sub(val As Object)
If val Is Nothing Then System.Console.WriteLine("Then") Else Equals ("Else")
End Sub
return r
End Function
Sub Equals(x as String)
System.Console.WriteLine(x)
End Sub
Sub Test2(val As Object)
If val Is Nothing Then System.Console.WriteLine("Then 2") Else Equals ("Else 2")
End Sub
Function Test3() As System.Action(Of Object)
Dim r As System.Action(Of Object)
r = Sub(val As Object) If val Is Nothing Then System.Console.WriteLine("Then 3") Else Equals ("Else 3")
return r
End Function
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
CompileAndVerify(compilation, expectedOutput:=
"Then
Else
Then 2
Else 2
Then 3
Else 3")
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_13()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Test1()
Dim d1 = Function(val1) If val1 Is Nothing Then Return 1, b1 = 0
Dim d2 = Function(val2) If (val2 Is Nothing) Then Return 2, b2 = 0
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30199: '(' expected.
Dim d1 = Function(val1) If val1 Is Nothing Then Return 1, b1 = 0
~
BC33104: 'If' operator requires either two or three operands.
Dim d2 = Function(val2) If (val2 Is Nothing) Then Return 2, b2 = 0
~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_14()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim d1 = Function(val1) If val1 Is Nothing Then Return 1 Else Return 2, b1 = 3
Dim d2 = Function(val2) If (val2 Is Nothing) Then Return 3 Else Return 4, b2 = 5
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30199: '(' expected.
Dim d1 = Function(val1) If val1 Is Nothing Then Return 1 Else Return 2, b1 = 3
~
BC33104: 'If' operator requires either two or three operands.
Dim d2 = Function(val2) If (val2 Is Nothing) Then Return 3 Else Return 4, b2 = 5
~
</expected>)
End Sub
<Fact>
<WorkItem(14761, "https://github.com/dotnet/roslyn/issues/14761")>
Public Sub ParseLineIfFollowedByAnotherStatement_15()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Function Test1(val1) As System.Func(Of Object)
If val1 Is Nothing Then Return Function(val2) If val2 Is Nothing Then Return 1 Else Return 2 Else Return Nothing
End Function
Function Test2(val1) As System.Func(Of Object)
If val1 Is Nothing Then Return Function(val2) If (val2 Is Nothing) Then Return 1 Else Return 2 Else Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30199: '(' expected.
If val1 Is Nothing Then Return Function(val2) If val2 Is Nothing Then Return 1 Else Return 2 Else Return Nothing
~
BC42105: Function 'Test1' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
BC33104: 'If' operator requires either two or three operands.
If val1 Is Nothing Then Return Function(val2) If (val2 Is Nothing) Then Return 1 Else Return 2 Else Return Nothing
~
BC42105: Function 'Test2' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
<WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")>
Public Sub ParseLineIfWithIncompleteInterpolatedString_01()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Test1(val1 As Integer)
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'")
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30625: 'Module' statement must end with a matching 'End Module'.
Module Module1
~~~~~~~~~~~~~~
BC30026: 'End Sub' expected.
Sub Test1(val1 As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30451: 'sServiceName' is not declared. It may be inaccessible due to its protection level.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'")
~~~~~~~~~~~~
BC30370: '}' expected.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'")
~
BC30198: ')' expected.
End Module
~
]]></expected>)
End Sub
<Fact>
<WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")>
Public Sub ParseLineIfWithIncompleteInterpolatedString_02()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Test1(val1 As Integer)
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"})
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30625: 'Module' statement must end with a matching 'End Module'.
Module Module1
~~~~~~~~~~~~~~
BC30026: 'End Sub' expected.
Sub Test1(val1 As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30451: 'sServiceName' is not declared. It may be inaccessible due to its protection level.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"})
~~~~~~~~~~~~
BC30198: ')' expected.
End Module
~
]]></expected>)
End Sub
<Fact>
<WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")>
Public Sub ParseLineIfWithIncompleteInterpolatedString_03()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Test1(val1 As Integer)
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"}")
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30451: 'sServiceName' is not declared. It may be inaccessible due to its protection level.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"}")
~~~~~~~~~~~~
]]></expected>)
End Sub
<Fact>
<WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")>
Public Sub ParseLineIfWithIncompleteInterpolatedString_04()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Test1(val1 As Integer)
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'" ")
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30451: 'sServiceName' is not declared. It may be inaccessible due to its protection level.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'" ")
~~~~~~~~~~~~
BC30370: '}' expected.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'" ")
~
]]></expected>)
End Sub
<Fact>
<WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")>
Public Sub ParseLineIfWithIncompleteInterpolatedString_05()
Dim compilationDef =
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub Test1(val1 As Integer)
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"")
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30625: 'Module' statement must end with a matching 'End Module'.
Module Module1
~~~~~~~~~~~~~~
BC30026: 'End Sub' expected.
Sub Test1(val1 As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30451: 'sServiceName' is not declared. It may be inaccessible due to its protection level.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"")
~~~~~~~~~~~~
BC30648: String constants must end with a double quote.
If val1 = 1 Then System.Console.WriteLine($"abc '{ sServiceName & "'"")
~~~~~~
BC30198: ')' expected.
End Module
~
BC30370: '}' expected.
End Module
~
]]></expected>)
End Sub
End Class
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/Core/Portable/Diagnostics/Extensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Workspaces.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static partial class Extensions
{
public static readonly CultureInfo USCultureInfo = new("en-US");
public static string GetBingHelpMessage(this Diagnostic diagnostic, OptionSet options)
{
// We use the ENU version of the message for bing search.
return options.GetOption(InternalDiagnosticsOptions.PutCustomTypeInBingSearch) ?
diagnostic.GetMessage(USCultureInfo) : diagnostic.Descriptor.GetBingHelpMessage();
}
public static string GetBingHelpMessage(this DiagnosticDescriptor descriptor)
{
// We use the ENU version of the message for bing search.
return descriptor.MessageFormat.ToString(USCultureInfo);
}
public static async Task<ImmutableArray<Diagnostic>> ToDiagnosticsAsync(this IEnumerable<DiagnosticData> diagnostics, Project project, CancellationToken cancellationToken)
{
var result = ArrayBuilder<Diagnostic>.GetInstance();
foreach (var diagnostic in diagnostics)
{
result.Add(await diagnostic.ToDiagnosticAsync(project, cancellationToken).ConfigureAwait(false));
}
return result.ToImmutableAndFree();
}
public static ValueTask<ImmutableArray<Location>> ConvertLocationsAsync(this IReadOnlyCollection<DiagnosticDataLocation> locations, Project project, CancellationToken cancellationToken)
=> locations.SelectAsArrayAsync((location, project, cancellationToken) => location.ConvertLocationAsync(project, cancellationToken), project, cancellationToken);
public static async ValueTask<Location> ConvertLocationAsync(
this DiagnosticDataLocation? dataLocation, Project project, CancellationToken cancellationToken)
{
if (dataLocation?.DocumentId == null)
{
return Location.None;
}
var textDocument = project.GetTextDocument(dataLocation.DocumentId);
if (textDocument == null)
{
return Location.None;
}
if (textDocument is Document document && document.SupportsSyntaxTree)
{
var syntacticDocument = await SyntacticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
return dataLocation.ConvertLocation(syntacticDocument);
}
return dataLocation.ConvertLocation();
}
public static Location ConvertLocation(
this DiagnosticDataLocation dataLocation, SyntacticDocument? document = null)
{
if (dataLocation?.DocumentId == null)
{
return Location.None;
}
if (document == null)
{
if (dataLocation.OriginalFilePath == null || dataLocation.SourceSpan == null)
{
return Location.None;
}
var span = dataLocation.SourceSpan.Value;
return Location.Create(dataLocation.OriginalFilePath, span, new LinePositionSpan(
new LinePosition(dataLocation.OriginalStartLine, dataLocation.OriginalStartColumn),
new LinePosition(dataLocation.OriginalEndLine, dataLocation.OriginalEndColumn)));
}
Contract.ThrowIfFalse(dataLocation.DocumentId == document.Document.Id);
var syntaxTree = document.SyntaxTree;
return syntaxTree.GetLocation(dataLocation.SourceSpan ?? DiagnosticData.GetTextSpan(dataLocation, document.Text));
}
public static string GetAnalyzerId(this DiagnosticAnalyzer analyzer)
{
// Get the unique ID for given diagnostic analyzer.
var type = analyzer.GetType();
return GetAssemblyQualifiedName(type);
}
private static string GetAssemblyQualifiedName(Type type)
{
// AnalyzerFileReference now includes things like versions, public key as part of its identity.
// so we need to consider them.
return type.AssemblyQualifiedName ?? throw ExceptionUtilities.UnexpectedValue(type);
}
public static async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResultBuilder>> ToResultBuilderMapAsync(
this AnalysisResult analysisResult,
ImmutableArray<Diagnostic> additionalPragmaSuppressionDiagnostics,
DocumentAnalysisScope? documentAnalysisScope,
Project project,
VersionStamp version,
Compilation compilation,
IEnumerable<DiagnosticAnalyzer> analyzers,
SkippedHostAnalyzersInfo skippedAnalyzersInfo,
bool includeSuppressedDiagnostics,
CancellationToken cancellationToken)
{
SyntaxTree? treeToAnalyze = null;
AdditionalText? additionalFileToAnalyze = null;
if (documentAnalysisScope != null)
{
if (documentAnalysisScope.TextDocument is Document document)
{
treeToAnalyze = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
}
else
{
additionalFileToAnalyze = documentAnalysisScope.AdditionalFile;
}
}
var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, DiagnosticAnalysisResultBuilder>();
foreach (var analyzer in analyzers)
{
cancellationToken.ThrowIfCancellationRequested();
if (skippedAnalyzersInfo.SkippedAnalyzers.Contains(analyzer))
{
continue;
}
var result = new DiagnosticAnalysisResultBuilder(project, version);
var diagnosticIdsToFilter = skippedAnalyzersInfo.FilteredDiagnosticIdsForAnalyzers.GetValueOrDefault(
analyzer,
ImmutableArray<string>.Empty);
if (documentAnalysisScope != null)
{
RoslynDebug.Assert(treeToAnalyze != null || additionalFileToAnalyze != null);
var spanToAnalyze = documentAnalysisScope.Span;
var kind = documentAnalysisScope.Kind;
ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>? diagnosticsByAnalyzerMap;
switch (kind)
{
case AnalysisKind.Syntax:
if (treeToAnalyze != null)
{
if (analysisResult.SyntaxDiagnostics.TryGetValue(treeToAnalyze, out diagnosticsByAnalyzerMap))
{
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
treeToAnalyze, additionalDocumentId: null, spanToAnalyze, AnalysisKind.Syntax, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
}
else if (analysisResult.AdditionalFileDiagnostics.TryGetValue(additionalFileToAnalyze!, out diagnosticsByAnalyzerMap))
{
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
tree: null, documentAnalysisScope.TextDocument.Id, spanToAnalyze, AnalysisKind.Syntax, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
break;
case AnalysisKind.Semantic:
if (analysisResult.SemanticDiagnostics.TryGetValue(treeToAnalyze!, out diagnosticsByAnalyzerMap))
{
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
treeToAnalyze, additionalDocumentId: null, spanToAnalyze, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
else
{
foreach (var (tree, diagnosticsByAnalyzerMap) in analysisResult.SyntaxDiagnostics)
{
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
tree, additionalDocumentId: null, span: null, AnalysisKind.Syntax, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
foreach (var (tree, diagnosticsByAnalyzerMap) in analysisResult.SemanticDiagnostics)
{
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
tree, additionalDocumentId: null, span: null, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
foreach (var (file, diagnosticsByAnalyzerMap) in analysisResult.AdditionalFileDiagnostics)
{
var additionalDocumentId = project.GetDocumentForFile(file);
var kind = additionalDocumentId != null ? AnalysisKind.Syntax : AnalysisKind.NonLocal;
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
tree: null, additionalDocumentId, span: null, kind, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
AddAnalyzerDiagnosticsToResult(analyzer, analysisResult.CompilationDiagnostics, ref result, compilation,
tree: null, additionalDocumentId: null, span: null, AnalysisKind.NonLocal, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
// Special handling for pragma suppression diagnostics.
if (!additionalPragmaSuppressionDiagnostics.IsEmpty &&
analyzer is IPragmaSuppressionsAnalyzer)
{
if (documentAnalysisScope != null)
{
if (treeToAnalyze != null)
{
var diagnostics = additionalPragmaSuppressionDiagnostics.WhereAsArray(d => d.Location.SourceTree == treeToAnalyze);
AddDiagnosticsToResult(diagnostics, ref result, compilation, treeToAnalyze, additionalDocumentId: null,
documentAnalysisScope!.Span, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
}
else
{
foreach (var group in additionalPragmaSuppressionDiagnostics.GroupBy(d => d.Location.SourceTree!))
{
AddDiagnosticsToResult(group.AsImmutable(), ref result, compilation, group.Key, additionalDocumentId: null,
span: null, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
}
additionalPragmaSuppressionDiagnostics = ImmutableArray<Diagnostic>.Empty;
}
builder.Add(analyzer, result);
}
return builder.ToImmutable();
static void AddAnalyzerDiagnosticsToResult(
DiagnosticAnalyzer analyzer,
ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>> diagnosticsByAnalyzer,
ref DiagnosticAnalysisResultBuilder result,
Compilation compilation,
SyntaxTree? tree,
DocumentId? additionalDocumentId,
TextSpan? span,
AnalysisKind kind,
ImmutableArray<string> diagnosticIdsToFilter,
bool includeSuppressedDiagnostics)
{
if (diagnosticsByAnalyzer.TryGetValue(analyzer, out var diagnostics))
{
AddDiagnosticsToResult(diagnostics, ref result, compilation,
tree, additionalDocumentId, span, kind, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
}
static void AddDiagnosticsToResult(
ImmutableArray<Diagnostic> diagnostics,
ref DiagnosticAnalysisResultBuilder result,
Compilation compilation,
SyntaxTree? tree,
DocumentId? additionalDocumentId,
TextSpan? span,
AnalysisKind kind,
ImmutableArray<string> diagnosticIdsToFilter,
bool includeSuppressedDiagnostics)
{
if (diagnostics.IsEmpty)
{
return;
}
diagnostics = diagnostics.Filter(diagnosticIdsToFilter, includeSuppressedDiagnostics, span);
Debug.Assert(diagnostics.Length == CompilationWithAnalyzers.GetEffectiveDiagnostics(diagnostics, compilation).Count());
switch (kind)
{
case AnalysisKind.Syntax:
if (tree != null)
{
Debug.Assert(diagnostics.All(d => d.Location.SourceTree == tree));
result.AddSyntaxDiagnostics(tree!, diagnostics);
}
else
{
RoslynDebug.Assert(additionalDocumentId != null);
result.AddExternalSyntaxDiagnostics(additionalDocumentId, diagnostics);
}
break;
case AnalysisKind.Semantic:
Debug.Assert(diagnostics.All(d => d.Location.SourceTree == tree));
result.AddSemanticDiagnostics(tree!, diagnostics);
break;
default:
result.AddCompilationDiagnostics(diagnostics);
break;
}
}
}
/// <summary>
/// Filters out the diagnostics with the specified <paramref name="diagnosticIdsToFilter"/>.
/// If <paramref name="includeSuppressedDiagnostics"/> is false, filters out suppressed diagnostics.
/// If <paramref name="filterSpan"/> is non-null, filters out diagnostics with location outside this span.
/// </summary>
public static ImmutableArray<Diagnostic> Filter(
this ImmutableArray<Diagnostic> diagnostics,
ImmutableArray<string> diagnosticIdsToFilter,
bool includeSuppressedDiagnostics,
TextSpan? filterSpan = null)
{
if (diagnosticIdsToFilter.IsEmpty && includeSuppressedDiagnostics && !filterSpan.HasValue)
{
return diagnostics;
}
return diagnostics.RemoveAll(diagnostic =>
diagnosticIdsToFilter.Contains(diagnostic.Id) ||
!includeSuppressedDiagnostics && diagnostic.IsSuppressed ||
filterSpan.HasValue && !filterSpan.Value.IntersectsWith(diagnostic.Location.SourceSpan));
}
public static async Task<(AnalysisResult result, ImmutableArray<Diagnostic> additionalDiagnostics)> GetAnalysisResultAsync(
this CompilationWithAnalyzers compilationWithAnalyzers,
DocumentAnalysisScope? documentAnalysisScope,
Project project,
DiagnosticAnalyzerInfoCache analyzerInfoCache,
CancellationToken cancellationToken)
{
var result = await GetAnalysisResultAsync(compilationWithAnalyzers, documentAnalysisScope, cancellationToken).ConfigureAwait(false);
var additionalDiagnostics = await compilationWithAnalyzers.GetPragmaSuppressionAnalyzerDiagnosticsAsync(
documentAnalysisScope, project, analyzerInfoCache, cancellationToken).ConfigureAwait(false);
return (result, additionalDiagnostics);
}
private static async Task<AnalysisResult> GetAnalysisResultAsync(
CompilationWithAnalyzers compilationWithAnalyzers,
DocumentAnalysisScope? documentAnalysisScope,
CancellationToken cancellationToken)
{
if (documentAnalysisScope == null)
{
return await compilationWithAnalyzers.GetAnalysisResultAsync(cancellationToken).ConfigureAwait(false);
}
Debug.Assert(documentAnalysisScope.Analyzers.ToSet().IsSubsetOf(compilationWithAnalyzers.Analyzers));
switch (documentAnalysisScope.Kind)
{
case AnalysisKind.Syntax:
if (documentAnalysisScope.TextDocument is Document document)
{
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return await compilationWithAnalyzers.GetAnalysisResultAsync(tree, documentAnalysisScope.Analyzers, cancellationToken).ConfigureAwait(false);
}
else
{
return await compilationWithAnalyzers.GetAnalysisResultAsync(documentAnalysisScope.AdditionalFile, documentAnalysisScope.Analyzers, cancellationToken).ConfigureAwait(false);
}
case AnalysisKind.Semantic:
var model = await ((Document)documentAnalysisScope.TextDocument).GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await compilationWithAnalyzers.GetAnalysisResultAsync(model, documentAnalysisScope.Span, documentAnalysisScope.Analyzers, cancellationToken).ConfigureAwait(false);
default:
throw ExceptionUtilities.UnexpectedValue(documentAnalysisScope.Kind);
}
}
private static async Task<ImmutableArray<Diagnostic>> GetPragmaSuppressionAnalyzerDiagnosticsAsync(
this CompilationWithAnalyzers compilationWithAnalyzers,
DocumentAnalysisScope? documentAnalysisScope,
Project project,
DiagnosticAnalyzerInfoCache analyzerInfoCache,
CancellationToken cancellationToken)
{
var analyzers = documentAnalysisScope?.Analyzers ?? compilationWithAnalyzers.Analyzers;
var suppressionAnalyzer = analyzers.OfType<IPragmaSuppressionsAnalyzer>().FirstOrDefault();
if (suppressionAnalyzer == null)
{
return ImmutableArray<Diagnostic>.Empty;
}
if (documentAnalysisScope != null)
{
if (!(documentAnalysisScope.TextDocument is Document document))
{
return ImmutableArray<Diagnostic>.Empty;
}
using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var diagnosticsBuilder);
await AnalyzeDocumentAsync(suppressionAnalyzer, document, documentAnalysisScope.Span, diagnosticsBuilder.Add).ConfigureAwait(false);
return diagnosticsBuilder.ToImmutable();
}
else
{
if (compilationWithAnalyzers.AnalysisOptions.ConcurrentAnalysis)
{
var bag = new ConcurrentBag<Diagnostic>();
using var _ = ArrayBuilder<Task>.GetInstance(project.DocumentIds.Count, out var tasks);
foreach (var document in project.Documents)
{
tasks.Add(AnalyzeDocumentAsync(suppressionAnalyzer, document, span: null, bag.Add));
}
await Task.WhenAll(tasks).ConfigureAwait(false);
return bag.ToImmutableArray();
}
else
{
using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var diagnosticsBuilder);
foreach (var document in project.Documents)
{
await AnalyzeDocumentAsync(suppressionAnalyzer, document, span: null, diagnosticsBuilder.Add).ConfigureAwait(false);
}
return diagnosticsBuilder.ToImmutable();
}
}
async Task AnalyzeDocumentAsync(IPragmaSuppressionsAnalyzer suppressionAnalyzer, Document document, TextSpan? span, Action<Diagnostic> reportDiagnostic)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
await suppressionAnalyzer.AnalyzeAsync(semanticModel, span, compilationWithAnalyzers,
analyzerInfoCache.GetDiagnosticDescriptors, reportDiagnostic, cancellationToken).ConfigureAwait(false);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Workspaces.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static partial class Extensions
{
public static readonly CultureInfo USCultureInfo = new("en-US");
public static string GetBingHelpMessage(this Diagnostic diagnostic, OptionSet options)
{
// We use the ENU version of the message for bing search.
return options.GetOption(InternalDiagnosticsOptions.PutCustomTypeInBingSearch) ?
diagnostic.GetMessage(USCultureInfo) : diagnostic.Descriptor.GetBingHelpMessage();
}
public static string GetBingHelpMessage(this DiagnosticDescriptor descriptor)
{
// We use the ENU version of the message for bing search.
return descriptor.MessageFormat.ToString(USCultureInfo);
}
public static async Task<ImmutableArray<Diagnostic>> ToDiagnosticsAsync(this IEnumerable<DiagnosticData> diagnostics, Project project, CancellationToken cancellationToken)
{
var result = ArrayBuilder<Diagnostic>.GetInstance();
foreach (var diagnostic in diagnostics)
{
result.Add(await diagnostic.ToDiagnosticAsync(project, cancellationToken).ConfigureAwait(false));
}
return result.ToImmutableAndFree();
}
public static ValueTask<ImmutableArray<Location>> ConvertLocationsAsync(this IReadOnlyCollection<DiagnosticDataLocation> locations, Project project, CancellationToken cancellationToken)
=> locations.SelectAsArrayAsync((location, project, cancellationToken) => location.ConvertLocationAsync(project, cancellationToken), project, cancellationToken);
public static async ValueTask<Location> ConvertLocationAsync(
this DiagnosticDataLocation? dataLocation, Project project, CancellationToken cancellationToken)
{
if (dataLocation?.DocumentId == null)
{
return Location.None;
}
var textDocument = project.GetTextDocument(dataLocation.DocumentId);
if (textDocument == null)
{
return Location.None;
}
if (textDocument is Document document && document.SupportsSyntaxTree)
{
var syntacticDocument = await SyntacticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
return dataLocation.ConvertLocation(syntacticDocument);
}
return dataLocation.ConvertLocation();
}
public static Location ConvertLocation(
this DiagnosticDataLocation dataLocation, SyntacticDocument? document = null)
{
if (dataLocation?.DocumentId == null)
{
return Location.None;
}
if (document == null)
{
if (dataLocation.OriginalFilePath == null || dataLocation.SourceSpan == null)
{
return Location.None;
}
var span = dataLocation.SourceSpan.Value;
return Location.Create(dataLocation.OriginalFilePath, span, new LinePositionSpan(
new LinePosition(dataLocation.OriginalStartLine, dataLocation.OriginalStartColumn),
new LinePosition(dataLocation.OriginalEndLine, dataLocation.OriginalEndColumn)));
}
Contract.ThrowIfFalse(dataLocation.DocumentId == document.Document.Id);
var syntaxTree = document.SyntaxTree;
return syntaxTree.GetLocation(dataLocation.SourceSpan ?? DiagnosticData.GetTextSpan(dataLocation, document.Text));
}
public static string GetAnalyzerId(this DiagnosticAnalyzer analyzer)
{
// Get the unique ID for given diagnostic analyzer.
var type = analyzer.GetType();
return GetAssemblyQualifiedName(type);
}
private static string GetAssemblyQualifiedName(Type type)
{
// AnalyzerFileReference now includes things like versions, public key as part of its identity.
// so we need to consider them.
return type.AssemblyQualifiedName ?? throw ExceptionUtilities.UnexpectedValue(type);
}
public static async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResultBuilder>> ToResultBuilderMapAsync(
this AnalysisResult analysisResult,
ImmutableArray<Diagnostic> additionalPragmaSuppressionDiagnostics,
DocumentAnalysisScope? documentAnalysisScope,
Project project,
VersionStamp version,
Compilation compilation,
IEnumerable<DiagnosticAnalyzer> analyzers,
SkippedHostAnalyzersInfo skippedAnalyzersInfo,
bool includeSuppressedDiagnostics,
CancellationToken cancellationToken)
{
SyntaxTree? treeToAnalyze = null;
AdditionalText? additionalFileToAnalyze = null;
if (documentAnalysisScope != null)
{
if (documentAnalysisScope.TextDocument is Document document)
{
treeToAnalyze = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
}
else
{
additionalFileToAnalyze = documentAnalysisScope.AdditionalFile;
}
}
var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, DiagnosticAnalysisResultBuilder>();
foreach (var analyzer in analyzers)
{
cancellationToken.ThrowIfCancellationRequested();
if (skippedAnalyzersInfo.SkippedAnalyzers.Contains(analyzer))
{
continue;
}
var result = new DiagnosticAnalysisResultBuilder(project, version);
var diagnosticIdsToFilter = skippedAnalyzersInfo.FilteredDiagnosticIdsForAnalyzers.GetValueOrDefault(
analyzer,
ImmutableArray<string>.Empty);
if (documentAnalysisScope != null)
{
RoslynDebug.Assert(treeToAnalyze != null || additionalFileToAnalyze != null);
var spanToAnalyze = documentAnalysisScope.Span;
var kind = documentAnalysisScope.Kind;
ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>? diagnosticsByAnalyzerMap;
switch (kind)
{
case AnalysisKind.Syntax:
if (treeToAnalyze != null)
{
if (analysisResult.SyntaxDiagnostics.TryGetValue(treeToAnalyze, out diagnosticsByAnalyzerMap))
{
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
treeToAnalyze, additionalDocumentId: null, spanToAnalyze, AnalysisKind.Syntax, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
}
else if (analysisResult.AdditionalFileDiagnostics.TryGetValue(additionalFileToAnalyze!, out diagnosticsByAnalyzerMap))
{
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
tree: null, documentAnalysisScope.TextDocument.Id, spanToAnalyze, AnalysisKind.Syntax, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
break;
case AnalysisKind.Semantic:
if (analysisResult.SemanticDiagnostics.TryGetValue(treeToAnalyze!, out diagnosticsByAnalyzerMap))
{
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
treeToAnalyze, additionalDocumentId: null, spanToAnalyze, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
else
{
foreach (var (tree, diagnosticsByAnalyzerMap) in analysisResult.SyntaxDiagnostics)
{
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
tree, additionalDocumentId: null, span: null, AnalysisKind.Syntax, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
foreach (var (tree, diagnosticsByAnalyzerMap) in analysisResult.SemanticDiagnostics)
{
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
tree, additionalDocumentId: null, span: null, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
foreach (var (file, diagnosticsByAnalyzerMap) in analysisResult.AdditionalFileDiagnostics)
{
var additionalDocumentId = project.GetDocumentForFile(file);
var kind = additionalDocumentId != null ? AnalysisKind.Syntax : AnalysisKind.NonLocal;
AddAnalyzerDiagnosticsToResult(analyzer, diagnosticsByAnalyzerMap, ref result, compilation,
tree: null, additionalDocumentId, span: null, kind, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
AddAnalyzerDiagnosticsToResult(analyzer, analysisResult.CompilationDiagnostics, ref result, compilation,
tree: null, additionalDocumentId: null, span: null, AnalysisKind.NonLocal, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
// Special handling for pragma suppression diagnostics.
if (!additionalPragmaSuppressionDiagnostics.IsEmpty &&
analyzer is IPragmaSuppressionsAnalyzer)
{
if (documentAnalysisScope != null)
{
if (treeToAnalyze != null)
{
var diagnostics = additionalPragmaSuppressionDiagnostics.WhereAsArray(d => d.Location.SourceTree == treeToAnalyze);
AddDiagnosticsToResult(diagnostics, ref result, compilation, treeToAnalyze, additionalDocumentId: null,
documentAnalysisScope!.Span, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
}
else
{
foreach (var group in additionalPragmaSuppressionDiagnostics.GroupBy(d => d.Location.SourceTree!))
{
AddDiagnosticsToResult(group.AsImmutable(), ref result, compilation, group.Key, additionalDocumentId: null,
span: null, AnalysisKind.Semantic, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
}
additionalPragmaSuppressionDiagnostics = ImmutableArray<Diagnostic>.Empty;
}
builder.Add(analyzer, result);
}
return builder.ToImmutable();
static void AddAnalyzerDiagnosticsToResult(
DiagnosticAnalyzer analyzer,
ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>> diagnosticsByAnalyzer,
ref DiagnosticAnalysisResultBuilder result,
Compilation compilation,
SyntaxTree? tree,
DocumentId? additionalDocumentId,
TextSpan? span,
AnalysisKind kind,
ImmutableArray<string> diagnosticIdsToFilter,
bool includeSuppressedDiagnostics)
{
if (diagnosticsByAnalyzer.TryGetValue(analyzer, out var diagnostics))
{
AddDiagnosticsToResult(diagnostics, ref result, compilation,
tree, additionalDocumentId, span, kind, diagnosticIdsToFilter, includeSuppressedDiagnostics);
}
}
static void AddDiagnosticsToResult(
ImmutableArray<Diagnostic> diagnostics,
ref DiagnosticAnalysisResultBuilder result,
Compilation compilation,
SyntaxTree? tree,
DocumentId? additionalDocumentId,
TextSpan? span,
AnalysisKind kind,
ImmutableArray<string> diagnosticIdsToFilter,
bool includeSuppressedDiagnostics)
{
if (diagnostics.IsEmpty)
{
return;
}
diagnostics = diagnostics.Filter(diagnosticIdsToFilter, includeSuppressedDiagnostics, span);
Debug.Assert(diagnostics.Length == CompilationWithAnalyzers.GetEffectiveDiagnostics(diagnostics, compilation).Count());
switch (kind)
{
case AnalysisKind.Syntax:
if (tree != null)
{
Debug.Assert(diagnostics.All(d => d.Location.SourceTree == tree));
result.AddSyntaxDiagnostics(tree!, diagnostics);
}
else
{
RoslynDebug.Assert(additionalDocumentId != null);
result.AddExternalSyntaxDiagnostics(additionalDocumentId, diagnostics);
}
break;
case AnalysisKind.Semantic:
Debug.Assert(diagnostics.All(d => d.Location.SourceTree == tree));
result.AddSemanticDiagnostics(tree!, diagnostics);
break;
default:
result.AddCompilationDiagnostics(diagnostics);
break;
}
}
}
/// <summary>
/// Filters out the diagnostics with the specified <paramref name="diagnosticIdsToFilter"/>.
/// If <paramref name="includeSuppressedDiagnostics"/> is false, filters out suppressed diagnostics.
/// If <paramref name="filterSpan"/> is non-null, filters out diagnostics with location outside this span.
/// </summary>
public static ImmutableArray<Diagnostic> Filter(
this ImmutableArray<Diagnostic> diagnostics,
ImmutableArray<string> diagnosticIdsToFilter,
bool includeSuppressedDiagnostics,
TextSpan? filterSpan = null)
{
if (diagnosticIdsToFilter.IsEmpty && includeSuppressedDiagnostics && !filterSpan.HasValue)
{
return diagnostics;
}
return diagnostics.RemoveAll(diagnostic =>
diagnosticIdsToFilter.Contains(diagnostic.Id) ||
!includeSuppressedDiagnostics && diagnostic.IsSuppressed ||
filterSpan.HasValue && !filterSpan.Value.IntersectsWith(diagnostic.Location.SourceSpan));
}
public static async Task<(AnalysisResult result, ImmutableArray<Diagnostic> additionalDiagnostics)> GetAnalysisResultAsync(
this CompilationWithAnalyzers compilationWithAnalyzers,
DocumentAnalysisScope? documentAnalysisScope,
Project project,
DiagnosticAnalyzerInfoCache analyzerInfoCache,
CancellationToken cancellationToken)
{
var result = await GetAnalysisResultAsync(compilationWithAnalyzers, documentAnalysisScope, cancellationToken).ConfigureAwait(false);
var additionalDiagnostics = await compilationWithAnalyzers.GetPragmaSuppressionAnalyzerDiagnosticsAsync(
documentAnalysisScope, project, analyzerInfoCache, cancellationToken).ConfigureAwait(false);
return (result, additionalDiagnostics);
}
private static async Task<AnalysisResult> GetAnalysisResultAsync(
CompilationWithAnalyzers compilationWithAnalyzers,
DocumentAnalysisScope? documentAnalysisScope,
CancellationToken cancellationToken)
{
if (documentAnalysisScope == null)
{
return await compilationWithAnalyzers.GetAnalysisResultAsync(cancellationToken).ConfigureAwait(false);
}
Debug.Assert(documentAnalysisScope.Analyzers.ToSet().IsSubsetOf(compilationWithAnalyzers.Analyzers));
switch (documentAnalysisScope.Kind)
{
case AnalysisKind.Syntax:
if (documentAnalysisScope.TextDocument is Document document)
{
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
return await compilationWithAnalyzers.GetAnalysisResultAsync(tree, documentAnalysisScope.Analyzers, cancellationToken).ConfigureAwait(false);
}
else
{
return await compilationWithAnalyzers.GetAnalysisResultAsync(documentAnalysisScope.AdditionalFile, documentAnalysisScope.Analyzers, cancellationToken).ConfigureAwait(false);
}
case AnalysisKind.Semantic:
var model = await ((Document)documentAnalysisScope.TextDocument).GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await compilationWithAnalyzers.GetAnalysisResultAsync(model, documentAnalysisScope.Span, documentAnalysisScope.Analyzers, cancellationToken).ConfigureAwait(false);
default:
throw ExceptionUtilities.UnexpectedValue(documentAnalysisScope.Kind);
}
}
private static async Task<ImmutableArray<Diagnostic>> GetPragmaSuppressionAnalyzerDiagnosticsAsync(
this CompilationWithAnalyzers compilationWithAnalyzers,
DocumentAnalysisScope? documentAnalysisScope,
Project project,
DiagnosticAnalyzerInfoCache analyzerInfoCache,
CancellationToken cancellationToken)
{
var analyzers = documentAnalysisScope?.Analyzers ?? compilationWithAnalyzers.Analyzers;
var suppressionAnalyzer = analyzers.OfType<IPragmaSuppressionsAnalyzer>().FirstOrDefault();
if (suppressionAnalyzer == null)
{
return ImmutableArray<Diagnostic>.Empty;
}
if (documentAnalysisScope != null)
{
if (!(documentAnalysisScope.TextDocument is Document document))
{
return ImmutableArray<Diagnostic>.Empty;
}
using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var diagnosticsBuilder);
await AnalyzeDocumentAsync(suppressionAnalyzer, document, documentAnalysisScope.Span, diagnosticsBuilder.Add).ConfigureAwait(false);
return diagnosticsBuilder.ToImmutable();
}
else
{
if (compilationWithAnalyzers.AnalysisOptions.ConcurrentAnalysis)
{
var bag = new ConcurrentBag<Diagnostic>();
using var _ = ArrayBuilder<Task>.GetInstance(project.DocumentIds.Count, out var tasks);
foreach (var document in project.Documents)
{
tasks.Add(AnalyzeDocumentAsync(suppressionAnalyzer, document, span: null, bag.Add));
}
await Task.WhenAll(tasks).ConfigureAwait(false);
return bag.ToImmutableArray();
}
else
{
using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var diagnosticsBuilder);
foreach (var document in project.Documents)
{
await AnalyzeDocumentAsync(suppressionAnalyzer, document, span: null, diagnosticsBuilder.Add).ConfigureAwait(false);
}
return diagnosticsBuilder.ToImmutable();
}
}
async Task AnalyzeDocumentAsync(IPragmaSuppressionsAnalyzer suppressionAnalyzer, Document document, TextSpan? span, Action<Diagnostic> reportDiagnostic)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
await suppressionAnalyzer.AnalyzeAsync(semanticModel, span, compilationWithAnalyzers,
analyzerInfoCache.GetDiagnosticDescriptors, reportDiagnostic, cancellationToken).ConfigureAwait(false);
}
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlightingHelpers.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
Friend Module KeywordHighlightingHelpers
Private Sub HighlightRelatedStatements(Of T As SyntaxNode)(
node As SyntaxNode,
highlights As List(Of TextSpan),
blockKind As SyntaxKind,
checkReturns As Boolean)
If blockKind <> SyntaxKind.None AndAlso TypeOf node Is ExitStatementSyntax Then
With DirectCast(node, ExitStatementSyntax)
If .BlockKeyword.Kind = blockKind Then
highlights.Add(.Span)
End If
End With
ElseIf blockKind <> SyntaxKind.None AndAlso TypeOf node Is ContinueStatementSyntax Then
With DirectCast(node, ContinueStatementSyntax)
If .BlockKeyword.Kind = blockKind Then
highlights.Add(.Span)
End If
End With
ElseIf checkReturns AndAlso TypeOf node Is ReturnStatementSyntax Then
With DirectCast(node, ReturnStatementSyntax)
highlights.Add(.ReturnKeyword.Span)
End With
Else
For Each child In node.ChildNodes()
If Not TypeOf child Is T AndAlso
Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedStatements(Of T)(child, highlights, blockKind, checkReturns)
End If
Next
End If
End Sub
<Extension()>
Friend Function GetRelatedStatementHighlights(Of T As SyntaxNode)(
node As T,
blockKind As SyntaxKind,
Optional checkReturns As Boolean = False) As IEnumerable(Of TextSpan)
Dim highlights As New List(Of TextSpan)
HighlightRelatedStatements(Of T)(node, highlights, blockKind, checkReturns)
Return highlights
End Function
<Extension()>
Friend Function IsIncorrectContinueStatement(node As SyntaxNode, expectedKind As SyntaxKind) As Boolean
Dim continueStatement = TryCast(node, ContinueStatementSyntax)
If continueStatement IsNot Nothing Then
Return continueStatement.Kind <> expectedKind
End If
Return False
End Function
<Extension()>
Friend Function IsIncorrectExitStatement(node As SyntaxNode, expectedKind As SyntaxKind) As Boolean
Dim exitStatement = TryCast(node, ExitStatementSyntax)
If exitStatement IsNot Nothing Then
Return exitStatement.Kind <> expectedKind
End If
Return False
End Function
<Extension>
Friend Sub HighlightRelatedAwaits(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
If TypeOf node Is AwaitExpressionSyntax Then
With DirectCast(node, AwaitExpressionSyntax)
' If there is already a highlight for the previous token and it is on the same line,
' we should expand the span of that highlight to include the Await keyword.
' Otherwise, just add the Await keyword span.
Dim handled = False
Dim previousToken = .AwaitKeyword.GetPreviousToken()
If Not previousToken.Span.IsEmpty Then
Dim text = node.SyntaxTree.GetText(cancellationToken)
Dim previousLine = text.Lines.IndexOf(previousToken.SpanStart)
Dim awaitLine = text.Lines.IndexOf(.AwaitKeyword.SpanStart)
If previousLine = awaitLine Then
Dim index = highlights.FindIndex(Function(s) s.Contains(previousToken.Span))
If index >= 0 Then
Dim span = highlights(index)
highlights(index) = TextSpan.FromBounds(span.Start, .AwaitKeyword.Span.End)
handled = True
End If
End If
End If
If Not handled Then
highlights.Add(.AwaitKeyword.Span)
End If
End With
End If
For Each child In node.ChildNodes()
If Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedAwaits(child, highlights, cancellationToken)
End If
Next
End Sub
Private Sub HighlightRelatedYieldStatements(Of T)(node As SyntaxNode, highlights As List(Of TextSpan))
If TypeOf node Is YieldStatementSyntax Then
With DirectCast(node, YieldStatementSyntax)
highlights.Add(.YieldKeyword.Span)
End With
Else
For Each child In node.ChildNodes()
If Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedYieldStatements(Of T)(child, highlights)
End If
Next
End If
End Sub
<Extension>
Friend Function GetRelatedYieldStatementHighlights(Of T As SyntaxNode)(node As T) As IEnumerable(Of TextSpan)
Dim highlights As New List(Of TextSpan)
HighlightRelatedYieldStatements(Of T)(node, highlights)
Return highlights
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
Friend Module KeywordHighlightingHelpers
Private Sub HighlightRelatedStatements(Of T As SyntaxNode)(
node As SyntaxNode,
highlights As List(Of TextSpan),
blockKind As SyntaxKind,
checkReturns As Boolean)
If blockKind <> SyntaxKind.None AndAlso TypeOf node Is ExitStatementSyntax Then
With DirectCast(node, ExitStatementSyntax)
If .BlockKeyword.Kind = blockKind Then
highlights.Add(.Span)
End If
End With
ElseIf blockKind <> SyntaxKind.None AndAlso TypeOf node Is ContinueStatementSyntax Then
With DirectCast(node, ContinueStatementSyntax)
If .BlockKeyword.Kind = blockKind Then
highlights.Add(.Span)
End If
End With
ElseIf checkReturns AndAlso TypeOf node Is ReturnStatementSyntax Then
With DirectCast(node, ReturnStatementSyntax)
highlights.Add(.ReturnKeyword.Span)
End With
Else
For Each child In node.ChildNodes()
If Not TypeOf child Is T AndAlso
Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedStatements(Of T)(child, highlights, blockKind, checkReturns)
End If
Next
End If
End Sub
<Extension()>
Friend Function GetRelatedStatementHighlights(Of T As SyntaxNode)(
node As T,
blockKind As SyntaxKind,
Optional checkReturns As Boolean = False) As IEnumerable(Of TextSpan)
Dim highlights As New List(Of TextSpan)
HighlightRelatedStatements(Of T)(node, highlights, blockKind, checkReturns)
Return highlights
End Function
<Extension()>
Friend Function IsIncorrectContinueStatement(node As SyntaxNode, expectedKind As SyntaxKind) As Boolean
Dim continueStatement = TryCast(node, ContinueStatementSyntax)
If continueStatement IsNot Nothing Then
Return continueStatement.Kind <> expectedKind
End If
Return False
End Function
<Extension()>
Friend Function IsIncorrectExitStatement(node As SyntaxNode, expectedKind As SyntaxKind) As Boolean
Dim exitStatement = TryCast(node, ExitStatementSyntax)
If exitStatement IsNot Nothing Then
Return exitStatement.Kind <> expectedKind
End If
Return False
End Function
<Extension>
Friend Sub HighlightRelatedAwaits(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
If TypeOf node Is AwaitExpressionSyntax Then
With DirectCast(node, AwaitExpressionSyntax)
' If there is already a highlight for the previous token and it is on the same line,
' we should expand the span of that highlight to include the Await keyword.
' Otherwise, just add the Await keyword span.
Dim handled = False
Dim previousToken = .AwaitKeyword.GetPreviousToken()
If Not previousToken.Span.IsEmpty Then
Dim text = node.SyntaxTree.GetText(cancellationToken)
Dim previousLine = text.Lines.IndexOf(previousToken.SpanStart)
Dim awaitLine = text.Lines.IndexOf(.AwaitKeyword.SpanStart)
If previousLine = awaitLine Then
Dim index = highlights.FindIndex(Function(s) s.Contains(previousToken.Span))
If index >= 0 Then
Dim span = highlights(index)
highlights(index) = TextSpan.FromBounds(span.Start, .AwaitKeyword.Span.End)
handled = True
End If
End If
End If
If Not handled Then
highlights.Add(.AwaitKeyword.Span)
End If
End With
End If
For Each child In node.ChildNodes()
If Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedAwaits(child, highlights, cancellationToken)
End If
Next
End Sub
Private Sub HighlightRelatedYieldStatements(Of T)(node As SyntaxNode, highlights As List(Of TextSpan))
If TypeOf node Is YieldStatementSyntax Then
With DirectCast(node, YieldStatementSyntax)
highlights.Add(.YieldKeyword.Span)
End With
Else
For Each child In node.ChildNodes()
If Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedYieldStatements(Of T)(child, highlights)
End If
Next
End If
End Sub
<Extension>
Friend Function GetRelatedYieldStatementHighlights(Of T As SyntaxNode)(node As T) As IEnumerable(Of TextSpan)
Dim highlights As New List(Of TextSpan)
HighlightRelatedYieldStatements(Of T)(node, highlights)
Return highlights
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicSelectionValidator.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Friend Class VisualBasicSelectionValidator
Inherits SelectionValidator
Public Sub New(document As SemanticDocument,
textSpan As TextSpan,
options As OptionSet)
MyBase.New(document, textSpan, options)
End Sub
Public Overrides Async Function GetValidSelectionAsync(cancellationToken As CancellationToken) As Task(Of SelectionResult)
If Not ContainsValidSelection Then
Return NullSelection
End If
Dim text = Me.SemanticDocument.Text
Dim root = SemanticDocument.Root
Dim model = Me.SemanticDocument.SemanticModel
Dim selectionInfo = GetInitialSelectionInfo(root)
selectionInfo = AssignInitialFinalTokens(selectionInfo, root, cancellationToken)
selectionInfo = AdjustFinalTokensBasedOnContext(selectionInfo, model, cancellationToken)
selectionInfo = AdjustFinalTokensIfNextStatement(selectionInfo, model, cancellationToken)
selectionInfo = FixUpFinalTokensAndAssignFinalSpan(selectionInfo, root, cancellationToken)
selectionInfo = CheckErrorCasesAndAppendDescriptions(selectionInfo, model, cancellationToken)
If selectionInfo.Status.Failed() Then
Return New ErrorSelectionResult(selectionInfo.Status)
End If
Dim controlFlowSpan = GetControlFlowSpan(selectionInfo)
If Not selectionInfo.SelectionInExpression Then
Dim statementRange = GetStatementRangeContainedInSpan(Of StatementSyntax)(root, controlFlowSpan, cancellationToken)
If statementRange Is Nothing Then
With selectionInfo
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.can_t_determine_valid_range_of_statements_to_extract_out)
End With
Return New ErrorSelectionResult(selectionInfo.Status)
End If
Dim isFinalSpanSemanticallyValid = IsFinalSpanSemanticallyValidSpan(model, controlFlowSpan, statementRange, cancellationToken)
If Not isFinalSpanSemanticallyValid Then
' check control flow only if we are extracting statement level, not expression level.
' you can't have goto that moves control out of scope in expression level (even in lambda)
With selectionInfo
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Not_all_code_paths_return)
End With
End If
End If
Return Await VisualBasicSelectionResult.CreateResultAsync(selectionInfo.Status,
selectionInfo.OriginalSpan,
selectionInfo.FinalSpan,
Me.Options,
selectionInfo.SelectionInExpression,
Me.SemanticDocument,
selectionInfo.FirstTokenInFinalSpan,
selectionInfo.LastTokenInFinalSpan,
cancellationToken).ConfigureAwait(False)
End Function
Private Shared Function GetControlFlowSpan(selectionInfo As SelectionInfo) As TextSpan
Return TextSpan.FromBounds(selectionInfo.FirstTokenInFinalSpan.SpanStart, selectionInfo.LastTokenInFinalSpan.Span.End)
End Function
Private Shared Function CheckErrorCasesAndAppendDescriptions(selectionInfo As SelectionInfo, semanticModel As SemanticModel, cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
If selectionInfo.FirstTokenInFinalSpan.IsMissing OrElse selectionInfo.LastTokenInFinalSpan.IsMissing Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.contains_invalid_selection)
End With
End If
' get the node that covers the selection
Dim commonNode = GetFinalTokenCommonRoot(selectionInfo)
If (selectionInfo.SelectionInExpression OrElse selectionInfo.SelectionInSingleStatement) AndAlso commonNode.HasDiagnostics() Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.the_selection_contains_syntactic_errors)
End With
End If
Dim root = semanticModel.SyntaxTree.GetRoot(cancellationToken)
Dim tokens = root.DescendantTokens(selectionInfo.FinalSpan)
If tokens.ContainPreprocessorCrossOver(selectionInfo.FinalSpan) Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Selection_can_t_be_crossed_over_preprocessors)
End With
End If
' TODO : check behavior of control flow analysis engine around exception and exception handling.
If tokens.ContainArgumentlessThrowWithoutEnclosingCatch(selectionInfo.FinalSpan) Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Selection_can_t_contain_throw_without_enclosing_catch_block)
End With
End If
If selectionInfo.SelectionInExpression AndAlso commonNode.PartOfConstantInitializerExpression() Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.Selection_can_t_be_parts_of_constant_initializer_expression)
End With
End If
If selectionInfo.SelectionInExpression AndAlso commonNode.IsArgumentForByRefParameter(semanticModel, cancellationToken) Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Argument_used_for_ByRef_parameter_can_t_be_extracted_out)
End With
End If
Dim containsAllStaticLocals = ContainsAllStaticLocalUsagesDefinedInSelectionIfExist(selectionInfo, semanticModel, cancellationToken)
If Not containsAllStaticLocals Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection)
End With
End If
' if it is multiple statement case.
If Not selectionInfo.SelectionInExpression AndAlso Not selectionInfo.SelectionInSingleStatement Then
If commonNode.GetAncestorOrThis(Of WithBlockSyntax)() IsNot Nothing Then
If commonNode.GetImplicitMemberAccessExpressions(selectionInfo.FinalSpan).Any() Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement)
End With
End If
End If
End If
If Not selectionInfo.SelectionInExpression AndAlso Not selectionInfo.SelectionInSingleStatement Then
If selectionInfo.FirstTokenInFinalSpan.GetAncestor(Of ExecutableStatementSyntax)() Is Nothing OrElse
selectionInfo.LastTokenInFinalSpan.GetAncestor(Of ExecutableStatementSyntax)() Is Nothing Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.Selection_must_be_part_of_executable_statements)
End With
End If
End If
If SelectionChanged(selectionInfo) Then
With clone
.Status = .Status.MarkSuggestion()
End With
End If
Return clone
End Function
Private Shared Function SelectionChanged(selectionInfo As SelectionInfo) As Boolean
' get final token that doesn't pointing to empty token
Dim finalFirstToken = If(selectionInfo.FirstTokenInFinalSpan.Width = 0,
selectionInfo.FirstTokenInFinalSpan.GetNextToken(),
selectionInfo.FirstTokenInFinalSpan)
Dim finalLastToken = If(selectionInfo.LastTokenInFinalSpan.Width = 0,
selectionInfo.LastTokenInFinalSpan.GetPreviousToken(),
selectionInfo.LastTokenInFinalSpan)
' adjust original tokens to point to statement terminator token if needed
Dim originalFirstToken = selectionInfo.FirstTokenInOriginalSpan
Dim originalLastToken = selectionInfo.LastTokenInOriginalSpan
Return originalFirstToken <> finalFirstToken OrElse originalLastToken <> finalLastToken
End Function
Private Shared Function ContainsAllStaticLocalUsagesDefinedInSelectionIfExist(selectionInfo As SelectionInfo,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As Boolean
If selectionInfo.FirstTokenInFinalSpan.GetAncestor(Of FieldDeclarationSyntax)() IsNot Nothing OrElse
selectionInfo.FirstTokenInFinalSpan.GetAncestor(Of PropertyStatementSyntax)() IsNot Nothing Then
' static local can't exist in field initializer
Return True
End If
Dim result As DataFlowAnalysis
If selectionInfo.SelectionInExpression Then
Dim expression = GetFinalTokenCommonRoot(selectionInfo).GetAncestorOrThis(Of ExpressionSyntax)()
result = semanticModel.AnalyzeDataFlow(expression)
Else
Dim range = GetStatementRangeContainedInSpan(Of StatementSyntax)(
semanticModel.SyntaxTree.GetRoot(cancellationToken), GetControlFlowSpan(selectionInfo), cancellationToken)
' we can't determine valid range of statements, don't bother to do the analysis
If range Is Nothing Then
Return True
End If
result = semanticModel.AnalyzeDataFlow(range.Item1, range.Item2)
End If
For Each symbol In result.VariablesDeclared
Dim local = TryCast(symbol, ILocalSymbol)
If local Is Nothing Then
Continue For
End If
If Not local.IsStatic Then
Continue For
End If
If result.WrittenOutside().Any(Function(s) Equals(s, local)) OrElse
result.ReadOutside().Any(Function(s) Equals(s, local)) Then
Return False
End If
Next
Return True
End Function
Private Shared Function GetFinalTokenCommonRoot(selection As SelectionInfo) As SyntaxNode
Return GetCommonRoot(selection.FirstTokenInFinalSpan, selection.LastTokenInFinalSpan)
End Function
Private Shared Function GetCommonRoot(token1 As SyntaxToken, token2 As SyntaxToken) As SyntaxNode
Return token1.GetCommonRoot(token2)
End Function
Private Shared Function FixUpFinalTokensAndAssignFinalSpan(selectionInfo As SelectionInfo,
root As SyntaxNode,
cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
' make sure we include statement terminator token if selection contains them
Dim firstToken = selectionInfo.FirstTokenInFinalSpan
Dim lastToken = selectionInfo.LastTokenInFinalSpan
' set final span
Dim start = If(selectionInfo.OriginalSpan.Start <= firstToken.SpanStart, selectionInfo.OriginalSpan.Start, firstToken.FullSpan.Start)
Dim [end] = If(lastToken.Span.End <= selectionInfo.OriginalSpan.End, selectionInfo.OriginalSpan.End, lastToken.Span.End)
With clone
.FinalSpan = GetAdjustedSpan(root, TextSpan.FromBounds(start, [end]))
.FirstTokenInFinalSpan = firstToken
.LastTokenInFinalSpan = lastToken
End With
Return clone
End Function
Private Shared Function AdjustFinalTokensIfNextStatement(selectionInfo As SelectionInfo,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
' if last statement is next statement, make sure its corresponding loop statement is
' included
Dim nextStatement = selectionInfo.LastTokenInFinalSpan.GetAncestor(Of NextStatementSyntax)()
If nextStatement Is Nothing OrElse nextStatement.ControlVariables.Count < 2 Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
Dim outmostControlVariable = nextStatement.ControlVariables.Last
Dim symbolInfo = semanticModel.GetSymbolInfo(outmostControlVariable, cancellationToken)
Dim symbol = symbolInfo.GetBestOrAllSymbols().FirstOrDefault()
' can't find symbol for the control variable. don't provide extract method
If symbol Is Nothing OrElse
symbol.Locations.Length <> 1 OrElse
Not symbol.Locations.First().IsInSource OrElse
symbol.Locations.First().SourceTree IsNot semanticModel.SyntaxTree Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.next_statement_control_variable_doesn_t_have_matching_declaration_statement)
End With
Return clone
End If
Dim startPosition = symbol.Locations.First().SourceSpan.Start
Dim root = semanticModel.SyntaxTree.GetRoot(cancellationToken)
Dim forBlock = root.FindToken(startPosition).GetAncestor(Of ForOrForEachBlockSyntax)()
If forBlock Is Nothing Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.next_statement_control_variable_doesn_t_have_matching_declaration_statement)
End With
Return clone
End If
Dim firstStatement = forBlock.ForOrForEachStatement
With clone
.SelectionInExpression = False
.SelectionInSingleStatement = forBlock.Span.Contains(nextStatement.Span)
.FirstTokenInFinalSpan = firstStatement.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = nextStatement.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End Function
Private Shared Function AdjustFinalTokensBasedOnContext(selectionInfo As SelectionInfo,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
' don't need to adjust anything if it is multi-statements case
If (Not selectionInfo.SelectionInExpression) AndAlso (Not selectionInfo.SelectionInSingleStatement) Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
' get the node that covers the selection
Dim node = GetFinalTokenCommonRoot(selectionInfo)
Dim validNode = Check(semanticModel, node, cancellationToken)
If validNode Then
Return selectionInfo
End If
Dim firstValidNode = node.GetAncestors(Of SyntaxNode)().FirstOrDefault(
Function(n) Check(semanticModel, n, cancellationToken))
If firstValidNode Is Nothing Then
' couldn't find any valid node
With clone
.Status = New OperationStatus(OperationStatusFlag.None, VBFeaturesResources.Selection_doesn_t_contain_any_valid_node)
.FirstTokenInFinalSpan = Nothing
.LastTokenInFinalSpan = Nothing
End With
Return clone
End If
With clone
.SelectionInExpression = TypeOf firstValidNode Is ExpressionSyntax
.SelectionInSingleStatement = TypeOf firstValidNode Is StatementSyntax
.FirstTokenInFinalSpan = firstValidNode.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = firstValidNode.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End Function
Private Shared Function AssignInitialFinalTokens(selectionInfo As SelectionInfo, root As SyntaxNode, cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
If selectionInfo.SelectionInExpression Then
' prefer outer statement or expression if two has same span
Dim outerNode = selectionInfo.CommonRootFromOriginalSpan.GetOutermostNodeWithSameSpan(Function(n) TypeOf n Is StatementSyntax OrElse TypeOf n Is ExpressionSyntax)
' simple expression case
With clone
.SelectionInExpression = TypeOf outerNode Is ExpressionSyntax
.SelectionInSingleStatement = TypeOf outerNode Is StatementSyntax
.FirstTokenInFinalSpan = outerNode.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = outerNode.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End If
Dim range = GetStatementRangeContainingSpan(Of StatementSyntax)(
root, TextSpan.FromBounds(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.LastTokenInOriginalSpan.Span.End),
cancellationToken)
If range Is Nothing Then
With clone
.Status = clone.Status.With(OperationStatusFlag.None, VBFeaturesResources.no_valid_statement_range_to_extract_out)
End With
Return clone
End If
Dim statement1 = DirectCast(range.Item1, StatementSyntax)
Dim statement2 = DirectCast(range.Item2, StatementSyntax)
If statement1 Is statement2 Then
' check one more time to see whether it is an expression case
Dim expression = selectionInfo.CommonRootFromOriginalSpan.GetAncestor(Of ExpressionSyntax)()
If expression IsNot Nothing AndAlso statement1.Span.Contains(expression.Span) Then
With clone
.SelectionInExpression = True
.FirstTokenInFinalSpan = expression.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = expression.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End If
' single statement case
' current way to find out a statement that can be extracted out
Dim singleStatement = statement1.GetAncestorsOrThis(Of StatementSyntax)().FirstOrDefault(
Function(s) s.Parent IsNot Nothing AndAlso s.Parent.IsStatementContainerNode() AndAlso s.Parent.ContainStatement(s))
If singleStatement Is Nothing Then
With clone
.Status = clone.Status.With(OperationStatusFlag.None, VBFeaturesResources.no_valid_statement_range_to_extract_out)
End With
Return clone
End If
With clone
.SelectionInSingleStatement = True
.FirstTokenInFinalSpan = singleStatement.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = singleStatement.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End If
' Special check for vb
' either statement1 or statement2 is pointing to header and end of a block node
' return the block instead of each node
If statement1.Parent.IsStatementContainerNode() Then
Dim contain1 = statement1.Parent.ContainStatement(statement1)
Dim contain2 = statement2.Parent.ContainStatement(statement2)
If Not contain1 OrElse Not contain2 Then
Dim parent = statement1.Parent _
.GetAncestorsOrThis(Of SyntaxNode)() _
.Where(Function(n) TypeOf n Is ExpressionSyntax OrElse TypeOf n Is StatementSyntax) _
.First()
' single statement case
With clone
.SelectionInExpression = TypeOf parent Is ExpressionSyntax
.SelectionInSingleStatement = TypeOf parent Is StatementSyntax
.FirstTokenInFinalSpan = parent.GetFirstToken()
.LastTokenInFinalSpan = parent.GetLastToken()
End With
Return clone
End If
End If
With clone
.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = statement2.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End Function
Private Function GetInitialSelectionInfo(root As SyntaxNode) As SelectionInfo
Dim adjustedSpan = GetAdjustedSpan(root, Me.OriginalSpan)
Dim firstTokenInSelection = root.FindTokenOnRightOfPosition(adjustedSpan.Start, includeSkipped:=False)
Dim lastTokenInSelection = root.FindTokenOnLeftOfPosition(adjustedSpan.End, includeSkipped:=False)
If firstTokenInSelection.Kind = SyntaxKind.None OrElse lastTokenInSelection.Kind = SyntaxKind.None Then
Return New SelectionInfo With {.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.Invalid_selection), .OriginalSpan = adjustedSpan}
End If
If firstTokenInSelection <> lastTokenInSelection AndAlso
firstTokenInSelection.Span.End > lastTokenInSelection.SpanStart Then
Return New SelectionInfo With {.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.Invalid_selection), .OriginalSpan = adjustedSpan}
End If
If (Not adjustedSpan.Contains(firstTokenInSelection.Span)) AndAlso (Not adjustedSpan.Contains(lastTokenInSelection.Span)) Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_does_not_contain_a_valid_token),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
If (Not firstTokenInSelection.UnderValidContext()) OrElse (Not lastTokenInSelection.UnderValidContext()) Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
Dim commonRoot = GetCommonRoot(firstTokenInSelection, lastTokenInSelection)
If commonRoot Is Nothing Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.No_common_root_node_for_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
If Not commonRoot.ContainedInValidType() Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_not_contained_inside_a_type),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
Dim selectionInExpression = TypeOf commonRoot Is ExpressionSyntax AndAlso
commonRoot.GetFirstToken(includeZeroWidth:=True) = firstTokenInSelection AndAlso
commonRoot.GetLastToken(includeZeroWidth:=True) = lastTokenInSelection
If (Not selectionInExpression) AndAlso (Not commonRoot.UnderValidContext()) Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
' make sure type block enclosing the selection exist
If commonRoot.GetAncestor(Of TypeBlockSyntax)() Is Nothing Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
Return New SelectionInfo With
{
.Status = OperationStatus.Succeeded,
.OriginalSpan = adjustedSpan,
.CommonRootFromOriginalSpan = commonRoot,
.SelectionInExpression = selectionInExpression,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End Function
Public Overrides Function ContainsNonReturnExitPointsStatements(jumpsOutOfRegion As IEnumerable(Of SyntaxNode)) As Boolean
Dim returnStatement = False
Dim exitStatement = False
For Each statement In jumpsOutOfRegion
If TypeOf statement Is ReturnStatementSyntax Then
returnStatement = True
ElseIf TypeOf statement Is ExitStatementSyntax Then
exitStatement = True
Else
Return True
End If
Next
If exitStatement Then
Return Not returnStatement
End If
Return False
End Function
Public Overrides Function GetOuterReturnStatements(commonRoot As SyntaxNode, jumpsOutOfRegionStatements As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxNode)
Dim returnStatements = jumpsOutOfRegionStatements.Where(Function(n) TypeOf n Is ReturnStatementSyntax OrElse TypeOf n Is ExitStatementSyntax)
Dim container = commonRoot.GetAncestorsOrThis(Of SyntaxNode)().Where(Function(a) a.IsReturnableConstruct()).FirstOrDefault()
If container Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Dim returnableConstructPairs = returnStatements.
Select(Function(r) Tuple.Create(r, r.GetAncestors(Of SyntaxNode)().Where(Function(a) a.IsReturnableConstruct()).FirstOrDefault())).
Where(Function(p) p.Item2 IsNot Nothing)
' now filter return statements to only include the one under outmost container
Return returnableConstructPairs.Where(Function(p) p.Item2 Is container).Select(Function(p) p.Item1)
End Function
Public Overrides Function IsFinalSpanSemanticallyValidSpan(root As SyntaxNode,
textSpan As TextSpan,
returnStatements As IEnumerable(Of SyntaxNode),
cancellationToken As CancellationToken) As Boolean
' do quick check to make sure we are under sub (no return value) container. otherwise, there is no point to anymore checks.
If returnStatements.Any(Function(s)
Return s.TypeSwitch(
Function(e As ExitStatementSyntax) e.BlockKeyword.Kind <> SyntaxKind.SubKeyword,
Function(r As ReturnStatementSyntax) r.Expression IsNot Nothing,
Function(n As SyntaxNode) True)
End Function) Then
Return False
End If
' check whether selection reaches the end of the container
Dim lastToken = root.FindToken(textSpan.End)
If lastToken.Kind = SyntaxKind.None Then
Return False
End If
Dim nextToken = lastToken.GetNextToken(includeZeroWidth:=True)
Dim container = nextToken.GetAncestors(Of SyntaxNode).Where(Function(n) n.IsReturnableConstruct()).FirstOrDefault()
If container Is Nothing Then
Return False
End If
Dim match = If(TryCast(container, MethodBlockBaseSyntax)?.EndBlockStatement.EndKeyword = nextToken, False) OrElse
If(TryCast(container, MultiLineLambdaExpressionSyntax)?.EndSubOrFunctionStatement.EndKeyword = nextToken, False)
If Not match Then
Return False
End If
If TryCast(container, MethodBlockBaseSyntax)?.BlockStatement.Kind = SyntaxKind.SubStatement Then
Return True
ElseIf TryCast(container, MultiLineLambdaExpressionSyntax)?.SubOrFunctionHeader.Kind = SyntaxKind.SubLambdaHeader Then
Return True
Else
Return False
End If
End Function
Private Shared Function GetAdjustedSpan(root As SyntaxNode, textSpan As TextSpan) As TextSpan
' quick exit
If textSpan.IsEmpty OrElse textSpan.End = 0 Then
Return textSpan
End If
' regular column 0 check
Dim line = root.GetText().Lines.GetLineFromPosition(textSpan.End)
If line.Start <> textSpan.End Then
Return textSpan
End If
' previous line
Contract.ThrowIfFalse(line.LineNumber > 0)
Dim previousLine = root.GetText().Lines(line.LineNumber - 1)
' check whether end of previous line is last token of a statement. if it is, don't do anything
If root.FindTokenOnLeftOfPosition(previousLine.End).IsLastTokenOfStatement() Then
Return textSpan
End If
' move end position of the selection
Return TextSpan.FromBounds(textSpan.Start, previousLine.End)
End Function
Private Class SelectionInfo
Public Property Status() As OperationStatus
Public Property OriginalSpan() As TextSpan
Public Property FinalSpan() As TextSpan
Public Property CommonRootFromOriginalSpan() As SyntaxNode
Public Property FirstTokenInOriginalSpan() As SyntaxToken
Public Property LastTokenInOriginalSpan() As SyntaxToken
Public Property FirstTokenInFinalSpan() As SyntaxToken
Public Property LastTokenInFinalSpan() As SyntaxToken
Public Property SelectionInExpression() As Boolean
Public Property SelectionInSingleStatement() As Boolean
Public Function Clone() As SelectionInfo
Return CType(Me.MemberwiseClone(), SelectionInfo)
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Friend Class VisualBasicSelectionValidator
Inherits SelectionValidator
Public Sub New(document As SemanticDocument,
textSpan As TextSpan,
options As OptionSet)
MyBase.New(document, textSpan, options)
End Sub
Public Overrides Async Function GetValidSelectionAsync(cancellationToken As CancellationToken) As Task(Of SelectionResult)
If Not ContainsValidSelection Then
Return NullSelection
End If
Dim text = Me.SemanticDocument.Text
Dim root = SemanticDocument.Root
Dim model = Me.SemanticDocument.SemanticModel
Dim selectionInfo = GetInitialSelectionInfo(root)
selectionInfo = AssignInitialFinalTokens(selectionInfo, root, cancellationToken)
selectionInfo = AdjustFinalTokensBasedOnContext(selectionInfo, model, cancellationToken)
selectionInfo = AdjustFinalTokensIfNextStatement(selectionInfo, model, cancellationToken)
selectionInfo = FixUpFinalTokensAndAssignFinalSpan(selectionInfo, root, cancellationToken)
selectionInfo = CheckErrorCasesAndAppendDescriptions(selectionInfo, model, cancellationToken)
If selectionInfo.Status.Failed() Then
Return New ErrorSelectionResult(selectionInfo.Status)
End If
Dim controlFlowSpan = GetControlFlowSpan(selectionInfo)
If Not selectionInfo.SelectionInExpression Then
Dim statementRange = GetStatementRangeContainedInSpan(Of StatementSyntax)(root, controlFlowSpan, cancellationToken)
If statementRange Is Nothing Then
With selectionInfo
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.can_t_determine_valid_range_of_statements_to_extract_out)
End With
Return New ErrorSelectionResult(selectionInfo.Status)
End If
Dim isFinalSpanSemanticallyValid = IsFinalSpanSemanticallyValidSpan(model, controlFlowSpan, statementRange, cancellationToken)
If Not isFinalSpanSemanticallyValid Then
' check control flow only if we are extracting statement level, not expression level.
' you can't have goto that moves control out of scope in expression level (even in lambda)
With selectionInfo
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Not_all_code_paths_return)
End With
End If
End If
Return Await VisualBasicSelectionResult.CreateResultAsync(selectionInfo.Status,
selectionInfo.OriginalSpan,
selectionInfo.FinalSpan,
Me.Options,
selectionInfo.SelectionInExpression,
Me.SemanticDocument,
selectionInfo.FirstTokenInFinalSpan,
selectionInfo.LastTokenInFinalSpan,
cancellationToken).ConfigureAwait(False)
End Function
Private Shared Function GetControlFlowSpan(selectionInfo As SelectionInfo) As TextSpan
Return TextSpan.FromBounds(selectionInfo.FirstTokenInFinalSpan.SpanStart, selectionInfo.LastTokenInFinalSpan.Span.End)
End Function
Private Shared Function CheckErrorCasesAndAppendDescriptions(selectionInfo As SelectionInfo, semanticModel As SemanticModel, cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
If selectionInfo.FirstTokenInFinalSpan.IsMissing OrElse selectionInfo.LastTokenInFinalSpan.IsMissing Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.contains_invalid_selection)
End With
End If
' get the node that covers the selection
Dim commonNode = GetFinalTokenCommonRoot(selectionInfo)
If (selectionInfo.SelectionInExpression OrElse selectionInfo.SelectionInSingleStatement) AndAlso commonNode.HasDiagnostics() Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.the_selection_contains_syntactic_errors)
End With
End If
Dim root = semanticModel.SyntaxTree.GetRoot(cancellationToken)
Dim tokens = root.DescendantTokens(selectionInfo.FinalSpan)
If tokens.ContainPreprocessorCrossOver(selectionInfo.FinalSpan) Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Selection_can_t_be_crossed_over_preprocessors)
End With
End If
' TODO : check behavior of control flow analysis engine around exception and exception handling.
If tokens.ContainArgumentlessThrowWithoutEnclosingCatch(selectionInfo.FinalSpan) Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Selection_can_t_contain_throw_without_enclosing_catch_block)
End With
End If
If selectionInfo.SelectionInExpression AndAlso commonNode.PartOfConstantInitializerExpression() Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.Selection_can_t_be_parts_of_constant_initializer_expression)
End With
End If
If selectionInfo.SelectionInExpression AndAlso commonNode.IsArgumentForByRefParameter(semanticModel, cancellationToken) Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Argument_used_for_ByRef_parameter_can_t_be_extracted_out)
End With
End If
Dim containsAllStaticLocals = ContainsAllStaticLocalUsagesDefinedInSelectionIfExist(selectionInfo, semanticModel, cancellationToken)
If Not containsAllStaticLocals Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection)
End With
End If
' if it is multiple statement case.
If Not selectionInfo.SelectionInExpression AndAlso Not selectionInfo.SelectionInSingleStatement Then
If commonNode.GetAncestorOrThis(Of WithBlockSyntax)() IsNot Nothing Then
If commonNode.GetImplicitMemberAccessExpressions(selectionInfo.FinalSpan).Any() Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement)
End With
End If
End If
End If
If Not selectionInfo.SelectionInExpression AndAlso Not selectionInfo.SelectionInSingleStatement Then
If selectionInfo.FirstTokenInFinalSpan.GetAncestor(Of ExecutableStatementSyntax)() Is Nothing OrElse
selectionInfo.LastTokenInFinalSpan.GetAncestor(Of ExecutableStatementSyntax)() Is Nothing Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.Selection_must_be_part_of_executable_statements)
End With
End If
End If
If SelectionChanged(selectionInfo) Then
With clone
.Status = .Status.MarkSuggestion()
End With
End If
Return clone
End Function
Private Shared Function SelectionChanged(selectionInfo As SelectionInfo) As Boolean
' get final token that doesn't pointing to empty token
Dim finalFirstToken = If(selectionInfo.FirstTokenInFinalSpan.Width = 0,
selectionInfo.FirstTokenInFinalSpan.GetNextToken(),
selectionInfo.FirstTokenInFinalSpan)
Dim finalLastToken = If(selectionInfo.LastTokenInFinalSpan.Width = 0,
selectionInfo.LastTokenInFinalSpan.GetPreviousToken(),
selectionInfo.LastTokenInFinalSpan)
' adjust original tokens to point to statement terminator token if needed
Dim originalFirstToken = selectionInfo.FirstTokenInOriginalSpan
Dim originalLastToken = selectionInfo.LastTokenInOriginalSpan
Return originalFirstToken <> finalFirstToken OrElse originalLastToken <> finalLastToken
End Function
Private Shared Function ContainsAllStaticLocalUsagesDefinedInSelectionIfExist(selectionInfo As SelectionInfo,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As Boolean
If selectionInfo.FirstTokenInFinalSpan.GetAncestor(Of FieldDeclarationSyntax)() IsNot Nothing OrElse
selectionInfo.FirstTokenInFinalSpan.GetAncestor(Of PropertyStatementSyntax)() IsNot Nothing Then
' static local can't exist in field initializer
Return True
End If
Dim result As DataFlowAnalysis
If selectionInfo.SelectionInExpression Then
Dim expression = GetFinalTokenCommonRoot(selectionInfo).GetAncestorOrThis(Of ExpressionSyntax)()
result = semanticModel.AnalyzeDataFlow(expression)
Else
Dim range = GetStatementRangeContainedInSpan(Of StatementSyntax)(
semanticModel.SyntaxTree.GetRoot(cancellationToken), GetControlFlowSpan(selectionInfo), cancellationToken)
' we can't determine valid range of statements, don't bother to do the analysis
If range Is Nothing Then
Return True
End If
result = semanticModel.AnalyzeDataFlow(range.Item1, range.Item2)
End If
For Each symbol In result.VariablesDeclared
Dim local = TryCast(symbol, ILocalSymbol)
If local Is Nothing Then
Continue For
End If
If Not local.IsStatic Then
Continue For
End If
If result.WrittenOutside().Any(Function(s) Equals(s, local)) OrElse
result.ReadOutside().Any(Function(s) Equals(s, local)) Then
Return False
End If
Next
Return True
End Function
Private Shared Function GetFinalTokenCommonRoot(selection As SelectionInfo) As SyntaxNode
Return GetCommonRoot(selection.FirstTokenInFinalSpan, selection.LastTokenInFinalSpan)
End Function
Private Shared Function GetCommonRoot(token1 As SyntaxToken, token2 As SyntaxToken) As SyntaxNode
Return token1.GetCommonRoot(token2)
End Function
Private Shared Function FixUpFinalTokensAndAssignFinalSpan(selectionInfo As SelectionInfo,
root As SyntaxNode,
cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
' make sure we include statement terminator token if selection contains them
Dim firstToken = selectionInfo.FirstTokenInFinalSpan
Dim lastToken = selectionInfo.LastTokenInFinalSpan
' set final span
Dim start = If(selectionInfo.OriginalSpan.Start <= firstToken.SpanStart, selectionInfo.OriginalSpan.Start, firstToken.FullSpan.Start)
Dim [end] = If(lastToken.Span.End <= selectionInfo.OriginalSpan.End, selectionInfo.OriginalSpan.End, lastToken.Span.End)
With clone
.FinalSpan = GetAdjustedSpan(root, TextSpan.FromBounds(start, [end]))
.FirstTokenInFinalSpan = firstToken
.LastTokenInFinalSpan = lastToken
End With
Return clone
End Function
Private Shared Function AdjustFinalTokensIfNextStatement(selectionInfo As SelectionInfo,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
' if last statement is next statement, make sure its corresponding loop statement is
' included
Dim nextStatement = selectionInfo.LastTokenInFinalSpan.GetAncestor(Of NextStatementSyntax)()
If nextStatement Is Nothing OrElse nextStatement.ControlVariables.Count < 2 Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
Dim outmostControlVariable = nextStatement.ControlVariables.Last
Dim symbolInfo = semanticModel.GetSymbolInfo(outmostControlVariable, cancellationToken)
Dim symbol = symbolInfo.GetBestOrAllSymbols().FirstOrDefault()
' can't find symbol for the control variable. don't provide extract method
If symbol Is Nothing OrElse
symbol.Locations.Length <> 1 OrElse
Not symbol.Locations.First().IsInSource OrElse
symbol.Locations.First().SourceTree IsNot semanticModel.SyntaxTree Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.next_statement_control_variable_doesn_t_have_matching_declaration_statement)
End With
Return clone
End If
Dim startPosition = symbol.Locations.First().SourceSpan.Start
Dim root = semanticModel.SyntaxTree.GetRoot(cancellationToken)
Dim forBlock = root.FindToken(startPosition).GetAncestor(Of ForOrForEachBlockSyntax)()
If forBlock Is Nothing Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.next_statement_control_variable_doesn_t_have_matching_declaration_statement)
End With
Return clone
End If
Dim firstStatement = forBlock.ForOrForEachStatement
With clone
.SelectionInExpression = False
.SelectionInSingleStatement = forBlock.Span.Contains(nextStatement.Span)
.FirstTokenInFinalSpan = firstStatement.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = nextStatement.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End Function
Private Shared Function AdjustFinalTokensBasedOnContext(selectionInfo As SelectionInfo,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
' don't need to adjust anything if it is multi-statements case
If (Not selectionInfo.SelectionInExpression) AndAlso (Not selectionInfo.SelectionInSingleStatement) Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
' get the node that covers the selection
Dim node = GetFinalTokenCommonRoot(selectionInfo)
Dim validNode = Check(semanticModel, node, cancellationToken)
If validNode Then
Return selectionInfo
End If
Dim firstValidNode = node.GetAncestors(Of SyntaxNode)().FirstOrDefault(
Function(n) Check(semanticModel, n, cancellationToken))
If firstValidNode Is Nothing Then
' couldn't find any valid node
With clone
.Status = New OperationStatus(OperationStatusFlag.None, VBFeaturesResources.Selection_doesn_t_contain_any_valid_node)
.FirstTokenInFinalSpan = Nothing
.LastTokenInFinalSpan = Nothing
End With
Return clone
End If
With clone
.SelectionInExpression = TypeOf firstValidNode Is ExpressionSyntax
.SelectionInSingleStatement = TypeOf firstValidNode Is StatementSyntax
.FirstTokenInFinalSpan = firstValidNode.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = firstValidNode.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End Function
Private Shared Function AssignInitialFinalTokens(selectionInfo As SelectionInfo, root As SyntaxNode, cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
If selectionInfo.SelectionInExpression Then
' prefer outer statement or expression if two has same span
Dim outerNode = selectionInfo.CommonRootFromOriginalSpan.GetOutermostNodeWithSameSpan(Function(n) TypeOf n Is StatementSyntax OrElse TypeOf n Is ExpressionSyntax)
' simple expression case
With clone
.SelectionInExpression = TypeOf outerNode Is ExpressionSyntax
.SelectionInSingleStatement = TypeOf outerNode Is StatementSyntax
.FirstTokenInFinalSpan = outerNode.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = outerNode.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End If
Dim range = GetStatementRangeContainingSpan(Of StatementSyntax)(
root, TextSpan.FromBounds(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.LastTokenInOriginalSpan.Span.End),
cancellationToken)
If range Is Nothing Then
With clone
.Status = clone.Status.With(OperationStatusFlag.None, VBFeaturesResources.no_valid_statement_range_to_extract_out)
End With
Return clone
End If
Dim statement1 = DirectCast(range.Item1, StatementSyntax)
Dim statement2 = DirectCast(range.Item2, StatementSyntax)
If statement1 Is statement2 Then
' check one more time to see whether it is an expression case
Dim expression = selectionInfo.CommonRootFromOriginalSpan.GetAncestor(Of ExpressionSyntax)()
If expression IsNot Nothing AndAlso statement1.Span.Contains(expression.Span) Then
With clone
.SelectionInExpression = True
.FirstTokenInFinalSpan = expression.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = expression.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End If
' single statement case
' current way to find out a statement that can be extracted out
Dim singleStatement = statement1.GetAncestorsOrThis(Of StatementSyntax)().FirstOrDefault(
Function(s) s.Parent IsNot Nothing AndAlso s.Parent.IsStatementContainerNode() AndAlso s.Parent.ContainStatement(s))
If singleStatement Is Nothing Then
With clone
.Status = clone.Status.With(OperationStatusFlag.None, VBFeaturesResources.no_valid_statement_range_to_extract_out)
End With
Return clone
End If
With clone
.SelectionInSingleStatement = True
.FirstTokenInFinalSpan = singleStatement.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = singleStatement.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End If
' Special check for vb
' either statement1 or statement2 is pointing to header and end of a block node
' return the block instead of each node
If statement1.Parent.IsStatementContainerNode() Then
Dim contain1 = statement1.Parent.ContainStatement(statement1)
Dim contain2 = statement2.Parent.ContainStatement(statement2)
If Not contain1 OrElse Not contain2 Then
Dim parent = statement1.Parent _
.GetAncestorsOrThis(Of SyntaxNode)() _
.Where(Function(n) TypeOf n Is ExpressionSyntax OrElse TypeOf n Is StatementSyntax) _
.First()
' single statement case
With clone
.SelectionInExpression = TypeOf parent Is ExpressionSyntax
.SelectionInSingleStatement = TypeOf parent Is StatementSyntax
.FirstTokenInFinalSpan = parent.GetFirstToken()
.LastTokenInFinalSpan = parent.GetLastToken()
End With
Return clone
End If
End If
With clone
.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = statement2.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End Function
Private Function GetInitialSelectionInfo(root As SyntaxNode) As SelectionInfo
Dim adjustedSpan = GetAdjustedSpan(root, Me.OriginalSpan)
Dim firstTokenInSelection = root.FindTokenOnRightOfPosition(adjustedSpan.Start, includeSkipped:=False)
Dim lastTokenInSelection = root.FindTokenOnLeftOfPosition(adjustedSpan.End, includeSkipped:=False)
If firstTokenInSelection.Kind = SyntaxKind.None OrElse lastTokenInSelection.Kind = SyntaxKind.None Then
Return New SelectionInfo With {.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.Invalid_selection), .OriginalSpan = adjustedSpan}
End If
If firstTokenInSelection <> lastTokenInSelection AndAlso
firstTokenInSelection.Span.End > lastTokenInSelection.SpanStart Then
Return New SelectionInfo With {.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.Invalid_selection), .OriginalSpan = adjustedSpan}
End If
If (Not adjustedSpan.Contains(firstTokenInSelection.Span)) AndAlso (Not adjustedSpan.Contains(lastTokenInSelection.Span)) Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_does_not_contain_a_valid_token),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
If (Not firstTokenInSelection.UnderValidContext()) OrElse (Not lastTokenInSelection.UnderValidContext()) Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
Dim commonRoot = GetCommonRoot(firstTokenInSelection, lastTokenInSelection)
If commonRoot Is Nothing Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.No_common_root_node_for_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
If Not commonRoot.ContainedInValidType() Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.Selection_not_contained_inside_a_type),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
Dim selectionInExpression = TypeOf commonRoot Is ExpressionSyntax AndAlso
commonRoot.GetFirstToken(includeZeroWidth:=True) = firstTokenInSelection AndAlso
commonRoot.GetLastToken(includeZeroWidth:=True) = lastTokenInSelection
If (Not selectionInExpression) AndAlso (Not commonRoot.UnderValidContext()) Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
' make sure type block enclosing the selection exist
If commonRoot.GetAncestor(Of TypeBlockSyntax)() Is Nothing Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, FeaturesResources.No_valid_selection_to_perform_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
Return New SelectionInfo With
{
.Status = OperationStatus.Succeeded,
.OriginalSpan = adjustedSpan,
.CommonRootFromOriginalSpan = commonRoot,
.SelectionInExpression = selectionInExpression,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End Function
Public Overrides Function ContainsNonReturnExitPointsStatements(jumpsOutOfRegion As IEnumerable(Of SyntaxNode)) As Boolean
Dim returnStatement = False
Dim exitStatement = False
For Each statement In jumpsOutOfRegion
If TypeOf statement Is ReturnStatementSyntax Then
returnStatement = True
ElseIf TypeOf statement Is ExitStatementSyntax Then
exitStatement = True
Else
Return True
End If
Next
If exitStatement Then
Return Not returnStatement
End If
Return False
End Function
Public Overrides Function GetOuterReturnStatements(commonRoot As SyntaxNode, jumpsOutOfRegionStatements As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxNode)
Dim returnStatements = jumpsOutOfRegionStatements.Where(Function(n) TypeOf n Is ReturnStatementSyntax OrElse TypeOf n Is ExitStatementSyntax)
Dim container = commonRoot.GetAncestorsOrThis(Of SyntaxNode)().Where(Function(a) a.IsReturnableConstruct()).FirstOrDefault()
If container Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Dim returnableConstructPairs = returnStatements.
Select(Function(r) Tuple.Create(r, r.GetAncestors(Of SyntaxNode)().Where(Function(a) a.IsReturnableConstruct()).FirstOrDefault())).
Where(Function(p) p.Item2 IsNot Nothing)
' now filter return statements to only include the one under outmost container
Return returnableConstructPairs.Where(Function(p) p.Item2 Is container).Select(Function(p) p.Item1)
End Function
Public Overrides Function IsFinalSpanSemanticallyValidSpan(root As SyntaxNode,
textSpan As TextSpan,
returnStatements As IEnumerable(Of SyntaxNode),
cancellationToken As CancellationToken) As Boolean
' do quick check to make sure we are under sub (no return value) container. otherwise, there is no point to anymore checks.
If returnStatements.Any(Function(s)
Return s.TypeSwitch(
Function(e As ExitStatementSyntax) e.BlockKeyword.Kind <> SyntaxKind.SubKeyword,
Function(r As ReturnStatementSyntax) r.Expression IsNot Nothing,
Function(n As SyntaxNode) True)
End Function) Then
Return False
End If
' check whether selection reaches the end of the container
Dim lastToken = root.FindToken(textSpan.End)
If lastToken.Kind = SyntaxKind.None Then
Return False
End If
Dim nextToken = lastToken.GetNextToken(includeZeroWidth:=True)
Dim container = nextToken.GetAncestors(Of SyntaxNode).Where(Function(n) n.IsReturnableConstruct()).FirstOrDefault()
If container Is Nothing Then
Return False
End If
Dim match = If(TryCast(container, MethodBlockBaseSyntax)?.EndBlockStatement.EndKeyword = nextToken, False) OrElse
If(TryCast(container, MultiLineLambdaExpressionSyntax)?.EndSubOrFunctionStatement.EndKeyword = nextToken, False)
If Not match Then
Return False
End If
If TryCast(container, MethodBlockBaseSyntax)?.BlockStatement.Kind = SyntaxKind.SubStatement Then
Return True
ElseIf TryCast(container, MultiLineLambdaExpressionSyntax)?.SubOrFunctionHeader.Kind = SyntaxKind.SubLambdaHeader Then
Return True
Else
Return False
End If
End Function
Private Shared Function GetAdjustedSpan(root As SyntaxNode, textSpan As TextSpan) As TextSpan
' quick exit
If textSpan.IsEmpty OrElse textSpan.End = 0 Then
Return textSpan
End If
' regular column 0 check
Dim line = root.GetText().Lines.GetLineFromPosition(textSpan.End)
If line.Start <> textSpan.End Then
Return textSpan
End If
' previous line
Contract.ThrowIfFalse(line.LineNumber > 0)
Dim previousLine = root.GetText().Lines(line.LineNumber - 1)
' check whether end of previous line is last token of a statement. if it is, don't do anything
If root.FindTokenOnLeftOfPosition(previousLine.End).IsLastTokenOfStatement() Then
Return textSpan
End If
' move end position of the selection
Return TextSpan.FromBounds(textSpan.Start, previousLine.End)
End Function
Private Class SelectionInfo
Public Property Status() As OperationStatus
Public Property OriginalSpan() As TextSpan
Public Property FinalSpan() As TextSpan
Public Property CommonRootFromOriginalSpan() As SyntaxNode
Public Property FirstTokenInOriginalSpan() As SyntaxToken
Public Property LastTokenInOriginalSpan() As SyntaxToken
Public Property FirstTokenInFinalSpan() As SyntaxToken
Public Property LastTokenInFinalSpan() As SyntaxToken
Public Property SelectionInExpression() As Boolean
Public Property SelectionInSingleStatement() As Boolean
Public Function Clone() As SelectionInfo
Return CType(Me.MemberwiseClone(), SelectionInfo)
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/EditorFeatures/Core/Implementation/IntelliSense/QuickInfo/QuickInfoSourceProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo
{
[ContentType(ContentTypeNames.RoslynContentType)]
[Export(typeof(IAsyncQuickInfoSourceProvider))]
[Name("RoslynQuickInfoProvider")]
internal partial class QuickInfoSourceProvider : IAsyncQuickInfoSourceProvider
{
private readonly IThreadingContext _threadingContext;
private readonly IUIThreadOperationExecutor _operationExecutor;
private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter;
private readonly IAsynchronousOperationListener _listener;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public QuickInfoSourceProvider(
IThreadingContext threadingContext,
IUIThreadOperationExecutor operationExecutor,
IAsynchronousOperationListenerProvider listenerProvider,
Lazy<IStreamingFindUsagesPresenter> streamingPresenter)
{
_threadingContext = threadingContext;
_operationExecutor = operationExecutor;
_streamingPresenter = streamingPresenter;
_listener = listenerProvider.GetListener(FeatureAttribute.QuickInfo);
}
public IAsyncQuickInfoSource TryCreateQuickInfoSource(ITextBuffer textBuffer)
{
if (textBuffer.IsInLspEditorContext())
return null;
return new QuickInfoSource(
textBuffer, _threadingContext, _operationExecutor, _listener, _streamingPresenter);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo
{
[ContentType(ContentTypeNames.RoslynContentType)]
[Export(typeof(IAsyncQuickInfoSourceProvider))]
[Name("RoslynQuickInfoProvider")]
internal partial class QuickInfoSourceProvider : IAsyncQuickInfoSourceProvider
{
private readonly IThreadingContext _threadingContext;
private readonly IUIThreadOperationExecutor _operationExecutor;
private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter;
private readonly IAsynchronousOperationListener _listener;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public QuickInfoSourceProvider(
IThreadingContext threadingContext,
IUIThreadOperationExecutor operationExecutor,
IAsynchronousOperationListenerProvider listenerProvider,
Lazy<IStreamingFindUsagesPresenter> streamingPresenter)
{
_threadingContext = threadingContext;
_operationExecutor = operationExecutor;
_streamingPresenter = streamingPresenter;
_listener = listenerProvider.GetListener(FeatureAttribute.QuickInfo);
}
public IAsyncQuickInfoSource TryCreateQuickInfoSource(ITextBuffer textBuffer)
{
if (textBuffer.IsInLspEditorContext())
return null;
return new QuickInfoSource(
textBuffer, _threadingContext, _operationExecutor, _listener, _streamingPresenter);
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.NullSyntaxReference.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class CSharpSyntaxTreeFactoryServiceFactory
{
private partial class CSharpSyntaxTreeFactoryService
{
/// <summary>
/// Represents a syntax reference that was passed a null
/// reference to a node. In this case, we just hold onto the
/// weak tree reference and throw if any invalid properties
/// are accessed.
/// </summary>
private class NullSyntaxReference : SyntaxReference
{
private readonly SyntaxTree _tree;
public NullSyntaxReference(SyntaxTree tree)
=> _tree = tree;
public override SyntaxTree SyntaxTree
{
get
{
return _tree;
}
}
public override SyntaxNode GetSyntax(CancellationToken cancellationToken)
=> null;
public override TextSpan Span
{
get
{
throw new NotSupportedException(CSharpWorkspaceResources.Cannot_retrieve_the_Span_of_a_null_syntax_reference);
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class CSharpSyntaxTreeFactoryServiceFactory
{
private partial class CSharpSyntaxTreeFactoryService
{
/// <summary>
/// Represents a syntax reference that was passed a null
/// reference to a node. In this case, we just hold onto the
/// weak tree reference and throw if any invalid properties
/// are accessed.
/// </summary>
private class NullSyntaxReference : SyntaxReference
{
private readonly SyntaxTree _tree;
public NullSyntaxReference(SyntaxTree tree)
=> _tree = tree;
public override SyntaxTree SyntaxTree
{
get
{
return _tree;
}
}
public override SyntaxNode GetSyntax(CancellationToken cancellationToken)
=> null;
public override TextSpan Span
{
get
{
throw new NotSupportedException(CSharpWorkspaceResources.Cannot_retrieve_the_Span_of_a_null_syntax_reference);
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/Core/Portable/Shared/Utilities/IStreamingProgressTrackerExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal static class IStreamingProgressTrackerExtensions
{
/// <summary>
/// Returns an <see cref="IAsyncDisposable"/> that will call <see
/// cref="IStreamingProgressTracker.ItemCompletedAsync"/> on <paramref
/// name="progressTracker"/> when it is disposed.
/// </summary>
public static async Task<IAsyncDisposable> AddSingleItemAsync(this IStreamingProgressTracker progressTracker, CancellationToken cancellationToken)
{
await progressTracker.AddItemsAsync(1, cancellationToken).ConfigureAwait(false);
return new StreamingProgressDisposer(progressTracker, cancellationToken);
}
private class StreamingProgressDisposer : IAsyncDisposable
{
private readonly IStreamingProgressTracker _progressTracker;
private readonly CancellationToken _cancellationToken;
public StreamingProgressDisposer(IStreamingProgressTracker progressTracker, CancellationToken cancellationToken)
{
_progressTracker = progressTracker;
_cancellationToken = cancellationToken;
}
public async ValueTask DisposeAsync()
=> await _progressTracker.ItemCompletedAsync(_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.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal static class IStreamingProgressTrackerExtensions
{
/// <summary>
/// Returns an <see cref="IAsyncDisposable"/> that will call <see
/// cref="IStreamingProgressTracker.ItemCompletedAsync"/> on <paramref
/// name="progressTracker"/> when it is disposed.
/// </summary>
public static async Task<IAsyncDisposable> AddSingleItemAsync(this IStreamingProgressTracker progressTracker, CancellationToken cancellationToken)
{
await progressTracker.AddItemsAsync(1, cancellationToken).ConfigureAwait(false);
return new StreamingProgressDisposer(progressTracker, cancellationToken);
}
private class StreamingProgressDisposer : IAsyncDisposable
{
private readonly IStreamingProgressTracker _progressTracker;
private readonly CancellationToken _cancellationToken;
public StreamingProgressDisposer(IStreamingProgressTracker progressTracker, CancellationToken cancellationToken)
{
_progressTracker = progressTracker;
_cancellationToken = cancellationToken;
}
public async ValueTask DisposeAsync()
=> await _progressTracker.ItemCompletedAsync(_cancellationToken).ConfigureAwait(false);
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/VisualStudio/IntegrationTest/TestUtilities/Common/Parameter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.Language.Intellisense;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common
{
[Serializable]
public class Parameter : IEquatable<Parameter>
{
public string? Name { get; set; }
public string? Documentation { get; set; }
public Parameter() { }
public Parameter(IParameter actual)
{
Name = actual.Name;
Documentation = actual.Documentation;
}
public bool Equals(Parameter? other)
{
if (other == null)
{
return false;
}
return Comparison.AreStringValuesEqual(Name, other.Name)
&& Comparison.AreStringValuesEqual(Documentation, other.Documentation);
}
public override bool Equals(object? obj)
=> Equals(obj as Parameter);
public override int GetHashCode()
=> Hash.Combine(Name, Hash.Combine(Documentation, 0));
public override string ToString()
=> !string.IsNullOrEmpty(Documentation) ? $"{Name} ({Documentation})" : $"{Name}";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.Language.Intellisense;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common
{
[Serializable]
public class Parameter : IEquatable<Parameter>
{
public string? Name { get; set; }
public string? Documentation { get; set; }
public Parameter() { }
public Parameter(IParameter actual)
{
Name = actual.Name;
Documentation = actual.Documentation;
}
public bool Equals(Parameter? other)
{
if (other == null)
{
return false;
}
return Comparison.AreStringValuesEqual(Name, other.Name)
&& Comparison.AreStringValuesEqual(Documentation, other.Documentation);
}
public override bool Equals(object? obj)
=> Equals(obj as Parameter);
public override int GetHashCode()
=> Hash.Combine(Name, Hash.Combine(Documentation, 0));
public override string ToString()
=> !string.IsNullOrEmpty(Documentation) ? $"{Name} ({Documentation})" : $"{Name}";
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Features/Core/Portable/Organizing/AbstractOrganizingService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Organizing.Organizers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Organizing
{
internal abstract class AbstractOrganizingService : IOrganizingService
{
private readonly IEnumerable<ISyntaxOrganizer> _organizers;
protected AbstractOrganizingService(IEnumerable<ISyntaxOrganizer> organizers)
=> _organizers = organizers.ToImmutableArrayOrEmpty();
public IEnumerable<ISyntaxOrganizer> GetDefaultOrganizers()
=> _organizers;
protected abstract Task<Document> ProcessAsync(Document document, IEnumerable<ISyntaxOrganizer> organizers, CancellationToken cancellationToken);
public Task<Document> OrganizeAsync(Document document, IEnumerable<ISyntaxOrganizer> organizers, CancellationToken cancellationToken)
=> ProcessAsync(document, organizers ?? GetDefaultOrganizers(), cancellationToken);
protected Func<SyntaxNode, IEnumerable<ISyntaxOrganizer>> GetNodeToOrganizers(IEnumerable<ISyntaxOrganizer> organizers)
{
var map = new ConcurrentDictionary<Type, IEnumerable<ISyntaxOrganizer>>();
IEnumerable<ISyntaxOrganizer> getter(Type t1)
{
return (from o in organizers
where !o.SyntaxNodeTypes.Any() ||
o.SyntaxNodeTypes.Any(t2 => t1 == t2 || t1.GetTypeInfo().IsSubclassOf(t2))
select o).Distinct();
}
return n => map.GetOrAdd(n.GetType(), getter);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Organizing.Organizers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Organizing
{
internal abstract class AbstractOrganizingService : IOrganizingService
{
private readonly IEnumerable<ISyntaxOrganizer> _organizers;
protected AbstractOrganizingService(IEnumerable<ISyntaxOrganizer> organizers)
=> _organizers = organizers.ToImmutableArrayOrEmpty();
public IEnumerable<ISyntaxOrganizer> GetDefaultOrganizers()
=> _organizers;
protected abstract Task<Document> ProcessAsync(Document document, IEnumerable<ISyntaxOrganizer> organizers, CancellationToken cancellationToken);
public Task<Document> OrganizeAsync(Document document, IEnumerable<ISyntaxOrganizer> organizers, CancellationToken cancellationToken)
=> ProcessAsync(document, organizers ?? GetDefaultOrganizers(), cancellationToken);
protected Func<SyntaxNode, IEnumerable<ISyntaxOrganizer>> GetNodeToOrganizers(IEnumerable<ISyntaxOrganizer> organizers)
{
var map = new ConcurrentDictionary<Type, IEnumerable<ISyntaxOrganizer>>();
IEnumerable<ISyntaxOrganizer> getter(Type t1)
{
return (from o in organizers
where !o.SyntaxNodeTypes.Any() ||
o.SyntaxNodeTypes.Any(t2 => t1 == t2 || t1.GetTypeInfo().IsSubclassOf(t2))
select o).Distinct();
}
return n => map.GetOrAdd(n.GetType(), getter);
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Interactive/Host/Interactive/Core/InteractiveHostPlatformInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
extern alias Scripting;
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Roslyn.Utilities;
using Scripting::Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Interactive
{
internal readonly struct InteractiveHostPlatformInfo
{
internal sealed class Data
{
public string[] PlatformAssemblyPaths = null!;
public bool HasGlobalAssemblyCache;
public InteractiveHostPlatformInfo Deserialize()
=> new InteractiveHostPlatformInfo(
PlatformAssemblyPaths.ToImmutableArray(),
HasGlobalAssemblyCache);
}
private static readonly string s_hostDirectory = PathUtilities.GetDirectoryName(typeof(InteractiveHostPlatformInfo).Assembly.Location)!;
public readonly ImmutableArray<string> PlatformAssemblyPaths;
public readonly bool HasGlobalAssemblyCache;
public InteractiveHostPlatformInfo(ImmutableArray<string> platformAssemblyPaths, bool hasGlobalAssemblyCache)
{
Debug.Assert(!platformAssemblyPaths.IsDefault);
HasGlobalAssemblyCache = hasGlobalAssemblyCache;
PlatformAssemblyPaths = platformAssemblyPaths;
}
public Data Serialize()
=> new Data()
{
HasGlobalAssemblyCache = HasGlobalAssemblyCache,
PlatformAssemblyPaths = PlatformAssemblyPaths.ToArray(),
};
public static InteractiveHostPlatformInfo GetCurrentPlatformInfo()
=> new InteractiveHostPlatformInfo(
RuntimeMetadataReferenceResolver.GetTrustedPlatformAssemblyPaths().Where(IsNotHostAssembly).ToImmutableArray(),
GacFileResolver.IsAvailable);
private static bool IsNotHostAssembly(string path)
=> !StringComparer.OrdinalIgnoreCase.Equals(PathUtilities.GetDirectoryName(path), s_hostDirectory);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
extern alias Scripting;
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Roslyn.Utilities;
using Scripting::Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Interactive
{
internal readonly struct InteractiveHostPlatformInfo
{
internal sealed class Data
{
public string[] PlatformAssemblyPaths = null!;
public bool HasGlobalAssemblyCache;
public InteractiveHostPlatformInfo Deserialize()
=> new InteractiveHostPlatformInfo(
PlatformAssemblyPaths.ToImmutableArray(),
HasGlobalAssemblyCache);
}
private static readonly string s_hostDirectory = PathUtilities.GetDirectoryName(typeof(InteractiveHostPlatformInfo).Assembly.Location)!;
public readonly ImmutableArray<string> PlatformAssemblyPaths;
public readonly bool HasGlobalAssemblyCache;
public InteractiveHostPlatformInfo(ImmutableArray<string> platformAssemblyPaths, bool hasGlobalAssemblyCache)
{
Debug.Assert(!platformAssemblyPaths.IsDefault);
HasGlobalAssemblyCache = hasGlobalAssemblyCache;
PlatformAssemblyPaths = platformAssemblyPaths;
}
public Data Serialize()
=> new Data()
{
HasGlobalAssemblyCache = HasGlobalAssemblyCache,
PlatformAssemblyPaths = PlatformAssemblyPaths.ToArray(),
};
public static InteractiveHostPlatformInfo GetCurrentPlatformInfo()
=> new InteractiveHostPlatformInfo(
RuntimeMetadataReferenceResolver.GetTrustedPlatformAssemblyPaths().Where(IsNotHostAssembly).ToImmutableArray(),
GacFileResolver.IsAvailable);
private static bool IsNotHostAssembly(string path)
=> !StringComparer.OrdinalIgnoreCase.Equals(PathUtilities.GetDirectoryName(path), s_hostDirectory);
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/OperatorOverloadSyntaxClassifier.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.Classification
Imports Microsoft.CodeAnalysis.Classification.Classifiers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers
Friend Class OperatorOverloadSyntaxClassifier
Inherits AbstractSyntaxClassifier
Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create(
GetType(BinaryExpressionSyntax),
GetType(UnaryExpressionSyntax))
Public Overrides Sub AddClassifications(
workspace As Workspace,
syntax As SyntaxNode,
semanticModel As SemanticModel,
result As ArrayBuilder(Of ClassifiedSpan),
cancellationToken As CancellationToken)
Dim symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken)
If TypeOf symbolInfo.Symbol Is IMethodSymbol AndAlso
DirectCast(symbolInfo.Symbol, IMethodSymbol).MethodKind = MethodKind.UserDefinedOperator Then
If TypeOf syntax Is BinaryExpressionSyntax Then
result.Add(New ClassifiedSpan(DirectCast(syntax, BinaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
ElseIf TypeOf syntax Is UnaryExpressionSyntax Then
result.Add(New ClassifiedSpan(DirectCast(syntax, UnaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
End If
End If
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.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Classification.Classifiers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers
Friend Class OperatorOverloadSyntaxClassifier
Inherits AbstractSyntaxClassifier
Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create(
GetType(BinaryExpressionSyntax),
GetType(UnaryExpressionSyntax))
Public Overrides Sub AddClassifications(
workspace As Workspace,
syntax As SyntaxNode,
semanticModel As SemanticModel,
result As ArrayBuilder(Of ClassifiedSpan),
cancellationToken As CancellationToken)
Dim symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken)
If TypeOf symbolInfo.Symbol Is IMethodSymbol AndAlso
DirectCast(symbolInfo.Symbol, IMethodSymbol).MethodKind = MethodKind.UserDefinedOperator Then
If TypeOf syntax Is BinaryExpressionSyntax Then
result.Add(New ClassifiedSpan(DirectCast(syntax, BinaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
ElseIf TypeOf syntax Is UnaryExpressionSyntax Then
result.Add(New ClassifiedSpan(DirectCast(syntax, UnaryExpressionSyntax).OperatorToken.Span, ClassificationTypeNames.OperatorOverloaded))
End If
End If
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.PatternMatching;
using Roslyn.Test.EditorUtilities.NavigateTo;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo
{
[UseExportProvider]
public abstract class AbstractNavigateToTests
{
protected static readonly TestComposition DefaultComposition = EditorTestCompositions.EditorFeatures;
protected static readonly TestComposition FirstVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsVisibleDocumentTrackingService.Factory));
protected static readonly TestComposition FirstActiveAndVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsActiveAndVisibleDocumentTrackingService.Factory));
protected INavigateToItemProvider _provider;
protected NavigateToTestAggregator _aggregator;
internal static readonly PatternMatch s_emptyExactPatternMatch = new PatternMatch(PatternMatchKind.Exact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch = new PatternMatch(PatternMatchKind.Prefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch = new PatternMatch(PatternMatchKind.Substring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseExact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch = new PatternMatch(PatternMatchKind.Fuzzy, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Exact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Prefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Substring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseExact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Fuzzy, true, false, ImmutableArray<Span>.Empty);
protected abstract TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider);
protected abstract string Language { get; }
public enum Composition
{
Default,
FirstVisible,
FirstActiveAndVisible,
}
protected async Task TestAsync(TestHost testHost, Composition composition, string content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
protected async Task TestAsync(TestHost testHost, Composition composition, XElement content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
private async Task TestAsync(
string content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
protected async Task TestAsync(
XElement content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
private protected TestWorkspace CreateWorkspace(
XElement workspaceElement,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = TestWorkspace.Create(workspaceElement, exportProvider: exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
private protected TestWorkspace CreateWorkspace(
string content,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = CreateWorkspace(content, exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
internal void InitializeWorkspace(TestWorkspace workspace)
{
_provider = new NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService<IThreadingContext>());
_aggregator = new NavigateToTestAggregator(_provider);
}
protected static void VerifyNavigateToResultItems(
List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items)
{
expecteditems = expecteditems.OrderBy(i => i.Name).ToList();
items = items.OrderBy(i => i.Name).ToList();
Assert.Equal(expecteditems.Count(), items.Count());
for (var i = 0; i < expecteditems.Count; i++)
{
var expectedItem = expecteditems[i];
var actualItem = items.ElementAt(i);
Assert.Equal(expectedItem.Name, actualItem.Name);
Assert.True(expectedItem.PatternMatch.Kind == actualItem.PatternMatch.Kind, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.Kind, actualItem.PatternMatch.Kind));
Assert.True(expectedItem.PatternMatch.IsCaseSensitive == actualItem.PatternMatch.IsCaseSensitive, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.IsCaseSensitive, actualItem.PatternMatch.IsCaseSensitive));
Assert.Equal(expectedItem.Language, actualItem.Language);
Assert.Equal(expectedItem.Kind, actualItem.Kind);
if (!string.IsNullOrEmpty(expectedItem.SecondarySort))
{
Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal);
}
}
}
internal void VerifyNavigateToResultItem(
NavigateToItem result, string name, string displayMarkup,
PatternMatchKind matchKind, string navigateToItemKind,
Glyph glyph, string additionalInfo = null)
{
// Verify symbol information
Assert.Equal(name, result.Name);
Assert.Equal(matchKind, result.PatternMatch.Kind);
Assert.Equal(this.Language, result.Language);
Assert.Equal(navigateToItemKind, result.Kind);
MarkupTestFile.GetSpans(displayMarkup, out displayMarkup,
out ImmutableArray<TextSpan> expectedDisplayNameSpans);
var itemDisplay = (NavigateToItemDisplay)result.DisplayFactory.CreateItemDisplay(result);
Assert.Equal(itemDisplay.GlyphMoniker, glyph.GetImageMoniker());
Assert.Equal(displayMarkup, itemDisplay.Name);
Assert.Equal<TextSpan>(
expectedDisplayNameSpans,
itemDisplay.GetNameMatchRuns("").Select(s => s.ToTextSpan()).ToImmutableArray());
if (additionalInfo != null)
{
Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation);
}
}
internal static BitmapSource CreateIconBitmapSource()
{
var stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16;
return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride);
}
// For ordering of NavigateToItems, see
// http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx
protected static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b)
=> ComparerWithState.CompareTo(a, b, s_comparisonComponents);
private static readonly ImmutableArray<Func<NavigateToItem, IComparable>> s_comparisonComponents =
ImmutableArray.Create<Func<NavigateToItem, IComparable>>(
item => (int)item.PatternMatch.Kind,
item => item.Name,
item => item.Kind,
item => item.SecondarySort);
private class FirstDocIsVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> null;
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
private class FirstDocIsActiveAndVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsActiveAndVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> _workspace.CurrentSolution.Projects.First().DocumentIds.First();
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsActiveAndVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.PatternMatching;
using Roslyn.Test.EditorUtilities.NavigateTo;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo
{
[UseExportProvider]
public abstract class AbstractNavigateToTests
{
protected static readonly TestComposition DefaultComposition = EditorTestCompositions.EditorFeatures;
protected static readonly TestComposition FirstVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsVisibleDocumentTrackingService.Factory));
protected static readonly TestComposition FirstActiveAndVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsActiveAndVisibleDocumentTrackingService.Factory));
protected INavigateToItemProvider _provider;
protected NavigateToTestAggregator _aggregator;
internal static readonly PatternMatch s_emptyExactPatternMatch = new PatternMatch(PatternMatchKind.Exact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch = new PatternMatch(PatternMatchKind.Prefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch = new PatternMatch(PatternMatchKind.Substring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseExact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch = new PatternMatch(PatternMatchKind.Fuzzy, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Exact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Prefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Substring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseExact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Fuzzy, true, false, ImmutableArray<Span>.Empty);
protected abstract TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider);
protected abstract string Language { get; }
public enum Composition
{
Default,
FirstVisible,
FirstActiveAndVisible,
}
protected async Task TestAsync(TestHost testHost, Composition composition, string content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
protected async Task TestAsync(TestHost testHost, Composition composition, XElement content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
private async Task TestAsync(
string content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
protected async Task TestAsync(
XElement content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
private protected TestWorkspace CreateWorkspace(
XElement workspaceElement,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = TestWorkspace.Create(workspaceElement, exportProvider: exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
private protected TestWorkspace CreateWorkspace(
string content,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = CreateWorkspace(content, exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
internal void InitializeWorkspace(TestWorkspace workspace)
{
_provider = new NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService<IThreadingContext>());
_aggregator = new NavigateToTestAggregator(_provider);
}
protected static void VerifyNavigateToResultItems(
List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items)
{
expecteditems = expecteditems.OrderBy(i => i.Name).ToList();
items = items.OrderBy(i => i.Name).ToList();
Assert.Equal(expecteditems.Count(), items.Count());
for (var i = 0; i < expecteditems.Count; i++)
{
var expectedItem = expecteditems[i];
var actualItem = items.ElementAt(i);
Assert.Equal(expectedItem.Name, actualItem.Name);
Assert.True(expectedItem.PatternMatch.Kind == actualItem.PatternMatch.Kind, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.Kind, actualItem.PatternMatch.Kind));
Assert.True(expectedItem.PatternMatch.IsCaseSensitive == actualItem.PatternMatch.IsCaseSensitive, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.IsCaseSensitive, actualItem.PatternMatch.IsCaseSensitive));
Assert.Equal(expectedItem.Language, actualItem.Language);
Assert.Equal(expectedItem.Kind, actualItem.Kind);
if (!string.IsNullOrEmpty(expectedItem.SecondarySort))
{
Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal);
}
}
}
internal void VerifyNavigateToResultItem(
NavigateToItem result, string name, string displayMarkup,
PatternMatchKind matchKind, string navigateToItemKind,
Glyph glyph, string additionalInfo = null)
{
// Verify symbol information
Assert.Equal(name, result.Name);
Assert.Equal(matchKind, result.PatternMatch.Kind);
Assert.Equal(this.Language, result.Language);
Assert.Equal(navigateToItemKind, result.Kind);
MarkupTestFile.GetSpans(displayMarkup, out displayMarkup,
out ImmutableArray<TextSpan> expectedDisplayNameSpans);
var itemDisplay = (NavigateToItemDisplay)result.DisplayFactory.CreateItemDisplay(result);
Assert.Equal(itemDisplay.GlyphMoniker, glyph.GetImageMoniker());
Assert.Equal(displayMarkup, itemDisplay.Name);
Assert.Equal<TextSpan>(
expectedDisplayNameSpans,
itemDisplay.GetNameMatchRuns("").Select(s => s.ToTextSpan()).ToImmutableArray());
if (additionalInfo != null)
{
Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation);
}
}
internal static BitmapSource CreateIconBitmapSource()
{
var stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16;
return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride);
}
// For ordering of NavigateToItems, see
// http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx
protected static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b)
=> ComparerWithState.CompareTo(a, b, s_comparisonComponents);
private static readonly ImmutableArray<Func<NavigateToItem, IComparable>> s_comparisonComponents =
ImmutableArray.Create<Func<NavigateToItem, IComparable>>(
item => (int)item.PatternMatch.Kind,
item => item.Name,
item => item.Kind,
item => item.SecondarySort);
private class FirstDocIsVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> null;
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
private class FirstDocIsActiveAndVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsActiveAndVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> _workspace.CurrentSolution.Projects.First().DocumentIds.First();
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsActiveAndVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/Core/Portable/Rename/ConflictEngine/RelatedLocationType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Rename.ConflictEngine
{
[Flags]
internal enum RelatedLocationType
{
/// <summary>
/// There was no conflict.
/// </summary>
NoConflict = 0x0,
/// <summary>
/// A conflict was resolved at a location that references the symbol being renamed.
/// </summary>
ResolvedReferenceConflict = 0x1,
/// <summary>
/// A conflict was resolved in a piece of code that does not reference the symbol being
/// renamed.
/// </summary>
ResolvedNonReferenceConflict = 0x2,
/// <summary>
/// There was a conflict that could not be resolved.
/// </summary>
PossiblyResolvableConflict = 0x4,
/// <summary>
/// These are the conflicts that cannot be resolved. E.g.: Declaration Conflict
/// </summary>
UnresolvableConflict = 0x8,
UnresolvedConflict = PossiblyResolvableConflict | UnresolvableConflict
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Rename.ConflictEngine
{
[Flags]
internal enum RelatedLocationType
{
/// <summary>
/// There was no conflict.
/// </summary>
NoConflict = 0x0,
/// <summary>
/// A conflict was resolved at a location that references the symbol being renamed.
/// </summary>
ResolvedReferenceConflict = 0x1,
/// <summary>
/// A conflict was resolved in a piece of code that does not reference the symbol being
/// renamed.
/// </summary>
ResolvedNonReferenceConflict = 0x2,
/// <summary>
/// There was a conflict that could not be resolved.
/// </summary>
PossiblyResolvableConflict = 0x4,
/// <summary>
/// These are the conflicts that cannot be resolved. E.g.: Declaration Conflict
/// </summary>
UnresolvableConflict = 0x8,
UnresolvedConflict = PossiblyResolvableConflict | UnresolvableConflict
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.EquivalenceVisitor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////#define TRACKDEPTH
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal partial class SymbolEquivalenceComparer
{
private class EquivalenceVisitor
{
private readonly bool _compareMethodTypeParametersByIndex;
private readonly bool _objectAndDynamicCompareEqually;
private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer;
public EquivalenceVisitor(
SymbolEquivalenceComparer symbolEquivalenceComparer,
bool compareMethodTypeParametersByIndex,
bool objectAndDynamicCompareEqually)
{
_symbolEquivalenceComparer = symbolEquivalenceComparer;
_compareMethodTypeParametersByIndex = compareMethodTypeParametersByIndex;
_objectAndDynamicCompareEqually = objectAndDynamicCompareEqually;
}
#if TRACKDEPTH
private int depth = 0;
#endif
public bool AreEquivalent(ISymbol? x, ISymbol? y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
#if TRACKDEPTH
try
{
this.depth++;
if (depth > 100)
{
throw new InvalidOperationException("Stack too deep.");
}
#endif
if (ReferenceEquals(x, y))
{
return true;
}
if (x == null || y == null)
{
return false;
}
var xKind = GetKindAndUnwrapAlias(ref x);
var yKind = GetKindAndUnwrapAlias(ref y);
// Normally, if they're different types, then they're not the same.
if (xKind != yKind)
{
// Special case. If we're comparing signatures then we want to compare 'object'
// and 'dynamic' as the same. However, since they're different types, we don't
// want to bail out using the above check.
if (_objectAndDynamicCompareEqually)
{
return (xKind == SymbolKind.DynamicType && IsObjectType(y)) ||
(yKind == SymbolKind.DynamicType && IsObjectType(x));
}
return false;
}
return AreEquivalentWorker(x, y, xKind, equivalentTypesWithDifferingAssemblies);
#if TRACKDEPTH
}
finally
{
this.depth--;
}
#endif
}
internal bool AreEquivalent(CustomModifier x, CustomModifier y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
=> x.IsOptional == y.IsOptional && AreEquivalent(x.Modifier, y.Modifier, equivalentTypesWithDifferingAssemblies);
internal bool AreEquivalent(ImmutableArray<CustomModifier> x, ImmutableArray<CustomModifier> y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
Debug.Assert(!x.IsDefault && !y.IsDefault);
if (x.Length != y.Length)
{
return false;
}
for (var i = 0; i < x.Length; i++)
{
if (!AreEquivalent(x[i], y[i], equivalentTypesWithDifferingAssemblies))
{
return false;
}
}
return true;
}
private bool NullableAnnotationsEquivalent(ITypeSymbol x, ITypeSymbol y)
=> _symbolEquivalenceComparer._ignoreNullableAnnotations || x.NullableAnnotation == y.NullableAnnotation;
private bool AreEquivalentWorker(ISymbol x, ISymbol y, SymbolKind k, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
Debug.Assert(x.Kind == y.Kind && x.Kind == k);
return k switch
{
SymbolKind.ArrayType => ArrayTypesAreEquivalent((IArrayTypeSymbol)x, (IArrayTypeSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Assembly => AssembliesAreEquivalent((IAssemblySymbol)x, (IAssemblySymbol)y),
SymbolKind.DynamicType => NullableAnnotationsEquivalent((IDynamicTypeSymbol)x, (IDynamicTypeSymbol)y),
SymbolKind.Event => EventsAreEquivalent((IEventSymbol)x, (IEventSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Field => FieldsAreEquivalent((IFieldSymbol)x, (IFieldSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Label => LabelsAreEquivalent((ILabelSymbol)x, (ILabelSymbol)y),
SymbolKind.Local => LocalsAreEquivalent((ILocalSymbol)x, (ILocalSymbol)y),
SymbolKind.Method => MethodsAreEquivalent((IMethodSymbol)x, (IMethodSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.NetModule => ModulesAreEquivalent((IModuleSymbol)x, (IModuleSymbol)y),
SymbolKind.NamedType => NamedTypesAreEquivalent((INamedTypeSymbol)x, (INamedTypeSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.ErrorType => NamedTypesAreEquivalent((INamedTypeSymbol)x, (INamedTypeSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Namespace => NamespacesAreEquivalent((INamespaceSymbol)x, (INamespaceSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Parameter => ParametersAreEquivalent((IParameterSymbol)x, (IParameterSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.PointerType => PointerTypesAreEquivalent((IPointerTypeSymbol)x, (IPointerTypeSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Property => PropertiesAreEquivalent((IPropertySymbol)x, (IPropertySymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.RangeVariable => RangeVariablesAreEquivalent((IRangeVariableSymbol)x, (IRangeVariableSymbol)y),
SymbolKind.TypeParameter => TypeParametersAreEquivalent((ITypeParameterSymbol)x, (ITypeParameterSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Preprocessing => PreprocessingSymbolsAreEquivalent((IPreprocessingSymbol)x, (IPreprocessingSymbol)y),
SymbolKind.FunctionPointerType => FunctionPointerTypesAreEquivalent((IFunctionPointerTypeSymbol)x, (IFunctionPointerTypeSymbol)y, equivalentTypesWithDifferingAssemblies),
_ => false,
};
}
private bool ArrayTypesAreEquivalent(IArrayTypeSymbol x, IArrayTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
return
x.Rank == y.Rank &&
AreEquivalent(x.CustomModifiers, y.CustomModifiers, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.ElementType, y.ElementType, equivalentTypesWithDifferingAssemblies) &&
NullableAnnotationsEquivalent(x, y);
}
private bool AssembliesAreEquivalent(IAssemblySymbol x, IAssemblySymbol y)
=> _symbolEquivalenceComparer._assemblyComparerOpt?.Equals(x, y) ?? true;
private bool FieldsAreEquivalent(IFieldSymbol x, IFieldSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
return
x.Name == y.Name &&
AreEquivalent(x.CustomModifiers, y.CustomModifiers, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private static bool LabelsAreEquivalent(ILabelSymbol x, ILabelSymbol y)
{
return
x.Name == y.Name &&
HaveSameLocation(x, y);
}
private static bool LocalsAreEquivalent(ILocalSymbol x, ILocalSymbol y)
=> HaveSameLocation(x, y);
private bool MethodsAreEquivalent(IMethodSymbol x, IMethodSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies, bool considerReturnRefKinds = false)
{
if (!AreCompatibleMethodKinds(x.MethodKind, y.MethodKind))
{
return false;
}
if (x.MethodKind == MethodKind.ReducedExtension)
{
var rx = x.ReducedFrom;
var ry = y.ReducedFrom;
// reduced from symbols are equivalent
if (!AreEquivalent(rx, ry, equivalentTypesWithDifferingAssemblies))
{
return false;
}
// receiver types are equivalent
if (!AreEquivalent(x.ReceiverType, y.ReceiverType, equivalentTypesWithDifferingAssemblies))
{
return false;
}
}
else
{
if (x.MethodKind == MethodKind.AnonymousFunction ||
x.MethodKind == MethodKind.LocalFunction)
{
// Treat local and anonymous functions just like we do ILocalSymbols.
// They're only equivalent if they have the same location.
return HaveSameLocation(x, y);
}
if (IsPartialMethodDefinitionPart(x) != IsPartialMethodDefinitionPart(y) ||
IsPartialMethodImplementationPart(x) != IsPartialMethodImplementationPart(y) ||
x.IsDefinition != y.IsDefinition ||
IsConstructedFromSelf(x) != IsConstructedFromSelf(y) ||
x.Arity != y.Arity ||
x.Parameters.Length != y.Parameters.Length ||
x.Name != y.Name)
{
return false;
}
var checkContainingType = CheckContainingType(x);
if (checkContainingType)
{
if (!AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies))
{
return false;
}
}
if (!ParametersAreEquivalent(x.Parameters, y.Parameters, equivalentTypesWithDifferingAssemblies))
{
return false;
}
if (!ReturnTypesAreEquivalent(x, y, equivalentTypesWithDifferingAssemblies))
{
return false;
}
if (considerReturnRefKinds && !AreRefKindsEquivalent(x.RefKind, y.RefKind, distinguishRefFromOut: false))
{
return false;
}
}
// If it's an unconstructed method, then we don't need to check the type arguments.
if (IsConstructedFromSelf(x))
{
return true;
}
return TypeArgumentsAreEquivalent(x.TypeArguments, y.TypeArguments, equivalentTypesWithDifferingAssemblies);
}
private static bool AreCompatibleMethodKinds(MethodKind kind1, MethodKind kind2)
{
if (kind1 == kind2)
{
return true;
}
if ((kind1 == MethodKind.Ordinary && kind2.IsPropertyAccessor()) ||
(kind1.IsPropertyAccessor() && kind2 == MethodKind.Ordinary))
{
return true;
}
// User-defined and Built-in operators are comparable
if ((kind1 == MethodKind.BuiltinOperator && kind2 == MethodKind.UserDefinedOperator) ||
(kind1 == MethodKind.UserDefinedOperator && kind2 == MethodKind.BuiltinOperator))
{
return true;
}
return false;
}
private static bool HaveSameLocation(ISymbol x, ISymbol y)
{
return x.Locations.Length == 1 && y.Locations.Length == 1 &&
x.Locations.First().Equals(y.Locations.First());
}
private bool ModulesAreEquivalent(IModuleSymbol x, IModuleSymbol y)
=> AssembliesAreEquivalent(x.ContainingAssembly, y.ContainingAssembly) && x.Name == y.Name;
private bool NamedTypesAreEquivalent(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
// PERF: Avoid multiple virtual calls to fetch the TypeKind property
var xTypeKind = GetTypeKind(x);
var yTypeKind = GetTypeKind(y);
if (xTypeKind == TypeKind.Error ||
yTypeKind == TypeKind.Error)
{
// Slow path: x or y is an error type. We need to compare
// all the candidates in both.
return NamedTypesAreEquivalentError(x, y, equivalentTypesWithDifferingAssemblies);
}
// Fast path: we can compare the symbols directly,
// avoiding any allocations associated with the Unwrap()
// enumerator.
return xTypeKind == yTypeKind && HandleNamedTypesWorker(x, y, equivalentTypesWithDifferingAssemblies);
}
private bool NamedTypesAreEquivalentError(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
foreach (var type1 in Unwrap(x))
{
var typeKind1 = GetTypeKind(type1);
foreach (var type2 in Unwrap(y))
{
var typeKind2 = GetTypeKind(type2);
if (typeKind1 == typeKind2 && HandleNamedTypesWorker(type1, type2, equivalentTypesWithDifferingAssemblies))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Worker for comparing two named types for equivalence. Note: The two
/// types must have the same TypeKind.
/// </summary>
/// <param name="x">The first type to compare</param>
/// <param name="y">The second type to compare</param>
/// <param name="equivalentTypesWithDifferingAssemblies">
/// Map of equivalent non-nested types to be populated, such that each key-value pair of named types are equivalent but reside in different assemblies.
/// This map is populated only if we are ignoring assemblies for symbol equivalence comparison, i.e. <see cref="_assemblyComparerOpt"/> is true.
/// </param>
/// <returns>True if the two types are equivalent.</returns>
private bool HandleNamedTypesWorker(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
Debug.Assert(GetTypeKind(x) == GetTypeKind(y));
if (x.IsTupleType != y.IsTupleType)
return false;
if (x.IsTupleType)
return HandleTupleTypes(x, y, equivalentTypesWithDifferingAssemblies);
if (IsConstructedFromSelf(x) != IsConstructedFromSelf(y) ||
x.Arity != y.Arity ||
x.Name != y.Name ||
x.IsAnonymousType != y.IsAnonymousType ||
x.IsUnboundGenericType != y.IsUnboundGenericType ||
!NullableAnnotationsEquivalent(x, y))
{
return false;
}
if (x.Kind == SymbolKind.ErrorType &&
x.ContainingSymbol is INamespaceSymbol xNamespace &&
y.ContainingSymbol is INamespaceSymbol yNamespace)
{
Debug.Assert(y.Kind == SymbolKind.ErrorType);
// For error types, we just ensure that the containing namespaces are equivalent up to the root.
while (true)
{
if (xNamespace.Name != yNamespace.Name)
return false;
// Error namespaces don't set the IsGlobalNamespace bit unfortunately. So we just do the
// nominal check to see if we've actually hit the root.
if (xNamespace.Name == "")
break;
xNamespace = xNamespace.ContainingNamespace;
yNamespace = yNamespace.ContainingNamespace;
}
}
else
{
if (!AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies))
return false;
// Above check makes sure that the containing assemblies are considered the same by the assembly comparer being used.
// If they are in fact not the same (have different name) and the caller requested to know about such types add {x, y}
// to equivalentTypesWithDifferingAssemblies map.
if (equivalentTypesWithDifferingAssemblies != null &&
x.ContainingType == null &&
x.ContainingAssembly != null &&
!AssemblyIdentityComparer.SimpleNameComparer.Equals(x.ContainingAssembly.Name, y.ContainingAssembly.Name) &&
!equivalentTypesWithDifferingAssemblies.ContainsKey(x))
{
equivalentTypesWithDifferingAssemblies.Add(x, y);
}
}
if (x.IsAnonymousType)
return HandleAnonymousTypes(x, y, equivalentTypesWithDifferingAssemblies);
// They look very similar at this point. In the case of non constructed types, we're
// done. However, if they are constructed, then their type arguments have to match
// as well.
return
IsConstructedFromSelf(x) ||
x.IsUnboundGenericType ||
TypeArgumentsAreEquivalent(x.TypeArguments, y.TypeArguments, equivalentTypesWithDifferingAssemblies);
}
private bool HandleTupleTypes(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
Debug.Assert(y.IsTupleType);
var xElements = x.TupleElements;
var yElements = y.TupleElements;
if (xElements.Length != yElements.Length)
return false;
// Check names first if necessary.
if (_symbolEquivalenceComparer._tupleNamesMustMatch)
{
for (var i = 0; i < xElements.Length; i++)
{
var xElement = xElements[i];
var yElement = yElements[i];
if (xElement.Name != yElement.Name)
return false;
}
}
// If we're validating the actual unconstructed ValueTuple type itself, we're done at this point. No
// need to check field types.
//
// For VB we have to unwrap tuples to their underlying types to do this check.
// https://github.com/dotnet/roslyn/issues/42860
if (IsConstructedFromSelf(x.TupleUnderlyingType ?? x))
return true;
for (var i = 0; i < xElements.Length; i++)
{
var xElement = xElements[i];
var yElement = yElements[i];
if (!AreEquivalent(xElement.Type, yElement.Type, equivalentTypesWithDifferingAssemblies))
return false;
}
return true;
}
private bool ParametersAreEquivalent(
ImmutableArray<IParameterSymbol> xParameters,
ImmutableArray<IParameterSymbol> yParameters,
Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies,
bool compareParameterName = false,
bool isParameterNameCaseSensitive = false)
{
// Note the special parameter comparer we pass in. We do this so we don't end up
// infinitely looping between parameters -> type parameters -> methods -> parameters
var count = xParameters.Length;
if (yParameters.Length != count)
{
return false;
}
for (var i = 0; i < count; i++)
{
if (!_symbolEquivalenceComparer.ParameterEquivalenceComparer.Equals(xParameters[i], yParameters[i], equivalentTypesWithDifferingAssemblies, compareParameterName, isParameterNameCaseSensitive))
{
return false;
}
}
return true;
}
internal bool ReturnTypesAreEquivalent(IMethodSymbol x, IMethodSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies = null)
{
return _symbolEquivalenceComparer.SignatureTypeEquivalenceComparer.Equals(x.ReturnType, y.ReturnType, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.ReturnTypeCustomModifiers, y.ReturnTypeCustomModifiers, equivalentTypesWithDifferingAssemblies);
}
private bool TypeArgumentsAreEquivalent(ImmutableArray<ITypeSymbol> xTypeArguments, ImmutableArray<ITypeSymbol> yTypeArguments, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
var count = xTypeArguments.Length;
if (yTypeArguments.Length != count)
{
return false;
}
for (var i = 0; i < count; i++)
{
if (!AreEquivalent(xTypeArguments[i], yTypeArguments[i], equivalentTypesWithDifferingAssemblies))
{
return false;
}
}
return true;
}
private bool HandleAnonymousTypes(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
if (x.TypeKind == TypeKind.Delegate)
{
return AreEquivalent(x.DelegateInvokeMethod, y.DelegateInvokeMethod, equivalentTypesWithDifferingAssemblies);
}
else
{
var xMembers = x.GetValidAnonymousTypeProperties();
var yMembers = y.GetValidAnonymousTypeProperties();
var xMembersEnumerator = xMembers.GetEnumerator();
var yMembersEnumerator = yMembers.GetEnumerator();
while (xMembersEnumerator.MoveNext())
{
if (!yMembersEnumerator.MoveNext())
{
return false;
}
var p1 = xMembersEnumerator.Current;
var p2 = yMembersEnumerator.Current;
if (p1.Name != p2.Name ||
p1.IsReadOnly != p2.IsReadOnly ||
!AreEquivalent(p1.Type, p2.Type, equivalentTypesWithDifferingAssemblies))
{
return false;
}
}
return !yMembersEnumerator.MoveNext();
}
}
private bool NamespacesAreEquivalent(INamespaceSymbol x, INamespaceSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
if (x.IsGlobalNamespace != y.IsGlobalNamespace ||
x.Name != y.Name)
{
return false;
}
if (x.IsGlobalNamespace && _symbolEquivalenceComparer._assemblyComparerOpt == null)
{
// No need to compare the containers of global namespace when assembly identities are ignored.
return true;
}
return AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private bool ParametersAreEquivalent(IParameterSymbol x, IParameterSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
return
x.IsRefOrOut() == y.IsRefOrOut() &&
x.Name == y.Name &&
AreEquivalent(x.CustomModifiers, y.CustomModifiers, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.Type, y.Type, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private bool PointerTypesAreEquivalent(IPointerTypeSymbol x, IPointerTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
return
AreEquivalent(x.CustomModifiers, y.CustomModifiers, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.PointedAtType, y.PointedAtType, equivalentTypesWithDifferingAssemblies);
}
private bool FunctionPointerTypesAreEquivalent(IFunctionPointerTypeSymbol x, IFunctionPointerTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
=> MethodsAreEquivalent(x.Signature, y.Signature, equivalentTypesWithDifferingAssemblies);
private bool PropertiesAreEquivalent(IPropertySymbol x, IPropertySymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
if (x.ContainingType.IsAnonymousType && y.ContainingType.IsAnonymousType)
{
// We can short circuit here and just use the symbols themselves to determine
// equality. This will properly handle things like the VB case where two
// anonymous types will be considered the same if they have properties that
// differ in casing.
if (x.Equals(y))
{
return true;
}
}
return
x.IsIndexer == y.IsIndexer &&
x.MetadataName == y.MetadataName &&
x.Parameters.Length == y.Parameters.Length &&
ParametersAreEquivalent(x.Parameters, y.Parameters, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private bool EventsAreEquivalent(IEventSymbol x, IEventSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
return
x.Name == y.Name &&
AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private bool TypeParametersAreEquivalent(ITypeParameterSymbol x, ITypeParameterSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
Debug.Assert(
(x.TypeParameterKind == TypeParameterKind.Method && IsConstructedFromSelf(x.DeclaringMethod!)) ||
(x.TypeParameterKind == TypeParameterKind.Type && IsConstructedFromSelf(x.ContainingType)) ||
x.TypeParameterKind == TypeParameterKind.Cref);
Debug.Assert(
(y.TypeParameterKind == TypeParameterKind.Method && IsConstructedFromSelf(y.DeclaringMethod!)) ||
(y.TypeParameterKind == TypeParameterKind.Type && IsConstructedFromSelf(y.ContainingType)) ||
y.TypeParameterKind == TypeParameterKind.Cref);
if (x.Ordinal != y.Ordinal ||
x.TypeParameterKind != y.TypeParameterKind)
{
return false;
}
// If this is a method type parameter, and we are in 'non-recurse' mode (because
// we're comparing method parameters), then we're done at this point. The types are
// equal.
if (x.TypeParameterKind == TypeParameterKind.Method && _compareMethodTypeParametersByIndex)
{
return true;
}
if (x.TypeParameterKind == TypeParameterKind.Type && x.ContainingType.IsAnonymousType)
{
// Anonymous type type parameters compare by index as well to prevent
// recursion.
return true;
}
if (x.TypeParameterKind == TypeParameterKind.Cref)
{
return true;
}
return AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private static bool RangeVariablesAreEquivalent(IRangeVariableSymbol x, IRangeVariableSymbol y)
=> HaveSameLocation(x, y);
private static bool PreprocessingSymbolsAreEquivalent(IPreprocessingSymbol x, IPreprocessingSymbol y)
=> x.Name == y.Name;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////#define TRACKDEPTH
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal partial class SymbolEquivalenceComparer
{
private class EquivalenceVisitor
{
private readonly bool _compareMethodTypeParametersByIndex;
private readonly bool _objectAndDynamicCompareEqually;
private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer;
public EquivalenceVisitor(
SymbolEquivalenceComparer symbolEquivalenceComparer,
bool compareMethodTypeParametersByIndex,
bool objectAndDynamicCompareEqually)
{
_symbolEquivalenceComparer = symbolEquivalenceComparer;
_compareMethodTypeParametersByIndex = compareMethodTypeParametersByIndex;
_objectAndDynamicCompareEqually = objectAndDynamicCompareEqually;
}
#if TRACKDEPTH
private int depth = 0;
#endif
public bool AreEquivalent(ISymbol? x, ISymbol? y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
#if TRACKDEPTH
try
{
this.depth++;
if (depth > 100)
{
throw new InvalidOperationException("Stack too deep.");
}
#endif
if (ReferenceEquals(x, y))
{
return true;
}
if (x == null || y == null)
{
return false;
}
var xKind = GetKindAndUnwrapAlias(ref x);
var yKind = GetKindAndUnwrapAlias(ref y);
// Normally, if they're different types, then they're not the same.
if (xKind != yKind)
{
// Special case. If we're comparing signatures then we want to compare 'object'
// and 'dynamic' as the same. However, since they're different types, we don't
// want to bail out using the above check.
if (_objectAndDynamicCompareEqually)
{
return (xKind == SymbolKind.DynamicType && IsObjectType(y)) ||
(yKind == SymbolKind.DynamicType && IsObjectType(x));
}
return false;
}
return AreEquivalentWorker(x, y, xKind, equivalentTypesWithDifferingAssemblies);
#if TRACKDEPTH
}
finally
{
this.depth--;
}
#endif
}
internal bool AreEquivalent(CustomModifier x, CustomModifier y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
=> x.IsOptional == y.IsOptional && AreEquivalent(x.Modifier, y.Modifier, equivalentTypesWithDifferingAssemblies);
internal bool AreEquivalent(ImmutableArray<CustomModifier> x, ImmutableArray<CustomModifier> y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
Debug.Assert(!x.IsDefault && !y.IsDefault);
if (x.Length != y.Length)
{
return false;
}
for (var i = 0; i < x.Length; i++)
{
if (!AreEquivalent(x[i], y[i], equivalentTypesWithDifferingAssemblies))
{
return false;
}
}
return true;
}
private bool NullableAnnotationsEquivalent(ITypeSymbol x, ITypeSymbol y)
=> _symbolEquivalenceComparer._ignoreNullableAnnotations || x.NullableAnnotation == y.NullableAnnotation;
private bool AreEquivalentWorker(ISymbol x, ISymbol y, SymbolKind k, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
Debug.Assert(x.Kind == y.Kind && x.Kind == k);
return k switch
{
SymbolKind.ArrayType => ArrayTypesAreEquivalent((IArrayTypeSymbol)x, (IArrayTypeSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Assembly => AssembliesAreEquivalent((IAssemblySymbol)x, (IAssemblySymbol)y),
SymbolKind.DynamicType => NullableAnnotationsEquivalent((IDynamicTypeSymbol)x, (IDynamicTypeSymbol)y),
SymbolKind.Event => EventsAreEquivalent((IEventSymbol)x, (IEventSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Field => FieldsAreEquivalent((IFieldSymbol)x, (IFieldSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Label => LabelsAreEquivalent((ILabelSymbol)x, (ILabelSymbol)y),
SymbolKind.Local => LocalsAreEquivalent((ILocalSymbol)x, (ILocalSymbol)y),
SymbolKind.Method => MethodsAreEquivalent((IMethodSymbol)x, (IMethodSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.NetModule => ModulesAreEquivalent((IModuleSymbol)x, (IModuleSymbol)y),
SymbolKind.NamedType => NamedTypesAreEquivalent((INamedTypeSymbol)x, (INamedTypeSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.ErrorType => NamedTypesAreEquivalent((INamedTypeSymbol)x, (INamedTypeSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Namespace => NamespacesAreEquivalent((INamespaceSymbol)x, (INamespaceSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Parameter => ParametersAreEquivalent((IParameterSymbol)x, (IParameterSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.PointerType => PointerTypesAreEquivalent((IPointerTypeSymbol)x, (IPointerTypeSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Property => PropertiesAreEquivalent((IPropertySymbol)x, (IPropertySymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.RangeVariable => RangeVariablesAreEquivalent((IRangeVariableSymbol)x, (IRangeVariableSymbol)y),
SymbolKind.TypeParameter => TypeParametersAreEquivalent((ITypeParameterSymbol)x, (ITypeParameterSymbol)y, equivalentTypesWithDifferingAssemblies),
SymbolKind.Preprocessing => PreprocessingSymbolsAreEquivalent((IPreprocessingSymbol)x, (IPreprocessingSymbol)y),
SymbolKind.FunctionPointerType => FunctionPointerTypesAreEquivalent((IFunctionPointerTypeSymbol)x, (IFunctionPointerTypeSymbol)y, equivalentTypesWithDifferingAssemblies),
_ => false,
};
}
private bool ArrayTypesAreEquivalent(IArrayTypeSymbol x, IArrayTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
return
x.Rank == y.Rank &&
AreEquivalent(x.CustomModifiers, y.CustomModifiers, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.ElementType, y.ElementType, equivalentTypesWithDifferingAssemblies) &&
NullableAnnotationsEquivalent(x, y);
}
private bool AssembliesAreEquivalent(IAssemblySymbol x, IAssemblySymbol y)
=> _symbolEquivalenceComparer._assemblyComparerOpt?.Equals(x, y) ?? true;
private bool FieldsAreEquivalent(IFieldSymbol x, IFieldSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
return
x.Name == y.Name &&
AreEquivalent(x.CustomModifiers, y.CustomModifiers, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private static bool LabelsAreEquivalent(ILabelSymbol x, ILabelSymbol y)
{
return
x.Name == y.Name &&
HaveSameLocation(x, y);
}
private static bool LocalsAreEquivalent(ILocalSymbol x, ILocalSymbol y)
=> HaveSameLocation(x, y);
private bool MethodsAreEquivalent(IMethodSymbol x, IMethodSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies, bool considerReturnRefKinds = false)
{
if (!AreCompatibleMethodKinds(x.MethodKind, y.MethodKind))
{
return false;
}
if (x.MethodKind == MethodKind.ReducedExtension)
{
var rx = x.ReducedFrom;
var ry = y.ReducedFrom;
// reduced from symbols are equivalent
if (!AreEquivalent(rx, ry, equivalentTypesWithDifferingAssemblies))
{
return false;
}
// receiver types are equivalent
if (!AreEquivalent(x.ReceiverType, y.ReceiverType, equivalentTypesWithDifferingAssemblies))
{
return false;
}
}
else
{
if (x.MethodKind == MethodKind.AnonymousFunction ||
x.MethodKind == MethodKind.LocalFunction)
{
// Treat local and anonymous functions just like we do ILocalSymbols.
// They're only equivalent if they have the same location.
return HaveSameLocation(x, y);
}
if (IsPartialMethodDefinitionPart(x) != IsPartialMethodDefinitionPart(y) ||
IsPartialMethodImplementationPart(x) != IsPartialMethodImplementationPart(y) ||
x.IsDefinition != y.IsDefinition ||
IsConstructedFromSelf(x) != IsConstructedFromSelf(y) ||
x.Arity != y.Arity ||
x.Parameters.Length != y.Parameters.Length ||
x.Name != y.Name)
{
return false;
}
var checkContainingType = CheckContainingType(x);
if (checkContainingType)
{
if (!AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies))
{
return false;
}
}
if (!ParametersAreEquivalent(x.Parameters, y.Parameters, equivalentTypesWithDifferingAssemblies))
{
return false;
}
if (!ReturnTypesAreEquivalent(x, y, equivalentTypesWithDifferingAssemblies))
{
return false;
}
if (considerReturnRefKinds && !AreRefKindsEquivalent(x.RefKind, y.RefKind, distinguishRefFromOut: false))
{
return false;
}
}
// If it's an unconstructed method, then we don't need to check the type arguments.
if (IsConstructedFromSelf(x))
{
return true;
}
return TypeArgumentsAreEquivalent(x.TypeArguments, y.TypeArguments, equivalentTypesWithDifferingAssemblies);
}
private static bool AreCompatibleMethodKinds(MethodKind kind1, MethodKind kind2)
{
if (kind1 == kind2)
{
return true;
}
if ((kind1 == MethodKind.Ordinary && kind2.IsPropertyAccessor()) ||
(kind1.IsPropertyAccessor() && kind2 == MethodKind.Ordinary))
{
return true;
}
// User-defined and Built-in operators are comparable
if ((kind1 == MethodKind.BuiltinOperator && kind2 == MethodKind.UserDefinedOperator) ||
(kind1 == MethodKind.UserDefinedOperator && kind2 == MethodKind.BuiltinOperator))
{
return true;
}
return false;
}
private static bool HaveSameLocation(ISymbol x, ISymbol y)
{
return x.Locations.Length == 1 && y.Locations.Length == 1 &&
x.Locations.First().Equals(y.Locations.First());
}
private bool ModulesAreEquivalent(IModuleSymbol x, IModuleSymbol y)
=> AssembliesAreEquivalent(x.ContainingAssembly, y.ContainingAssembly) && x.Name == y.Name;
private bool NamedTypesAreEquivalent(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
// PERF: Avoid multiple virtual calls to fetch the TypeKind property
var xTypeKind = GetTypeKind(x);
var yTypeKind = GetTypeKind(y);
if (xTypeKind == TypeKind.Error ||
yTypeKind == TypeKind.Error)
{
// Slow path: x or y is an error type. We need to compare
// all the candidates in both.
return NamedTypesAreEquivalentError(x, y, equivalentTypesWithDifferingAssemblies);
}
// Fast path: we can compare the symbols directly,
// avoiding any allocations associated with the Unwrap()
// enumerator.
return xTypeKind == yTypeKind && HandleNamedTypesWorker(x, y, equivalentTypesWithDifferingAssemblies);
}
private bool NamedTypesAreEquivalentError(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
foreach (var type1 in Unwrap(x))
{
var typeKind1 = GetTypeKind(type1);
foreach (var type2 in Unwrap(y))
{
var typeKind2 = GetTypeKind(type2);
if (typeKind1 == typeKind2 && HandleNamedTypesWorker(type1, type2, equivalentTypesWithDifferingAssemblies))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Worker for comparing two named types for equivalence. Note: The two
/// types must have the same TypeKind.
/// </summary>
/// <param name="x">The first type to compare</param>
/// <param name="y">The second type to compare</param>
/// <param name="equivalentTypesWithDifferingAssemblies">
/// Map of equivalent non-nested types to be populated, such that each key-value pair of named types are equivalent but reside in different assemblies.
/// This map is populated only if we are ignoring assemblies for symbol equivalence comparison, i.e. <see cref="_assemblyComparerOpt"/> is true.
/// </param>
/// <returns>True if the two types are equivalent.</returns>
private bool HandleNamedTypesWorker(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
Debug.Assert(GetTypeKind(x) == GetTypeKind(y));
if (x.IsTupleType != y.IsTupleType)
return false;
if (x.IsTupleType)
return HandleTupleTypes(x, y, equivalentTypesWithDifferingAssemblies);
if (IsConstructedFromSelf(x) != IsConstructedFromSelf(y) ||
x.Arity != y.Arity ||
x.Name != y.Name ||
x.IsAnonymousType != y.IsAnonymousType ||
x.IsUnboundGenericType != y.IsUnboundGenericType ||
!NullableAnnotationsEquivalent(x, y))
{
return false;
}
if (x.Kind == SymbolKind.ErrorType &&
x.ContainingSymbol is INamespaceSymbol xNamespace &&
y.ContainingSymbol is INamespaceSymbol yNamespace)
{
Debug.Assert(y.Kind == SymbolKind.ErrorType);
// For error types, we just ensure that the containing namespaces are equivalent up to the root.
while (true)
{
if (xNamespace.Name != yNamespace.Name)
return false;
// Error namespaces don't set the IsGlobalNamespace bit unfortunately. So we just do the
// nominal check to see if we've actually hit the root.
if (xNamespace.Name == "")
break;
xNamespace = xNamespace.ContainingNamespace;
yNamespace = yNamespace.ContainingNamespace;
}
}
else
{
if (!AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies))
return false;
// Above check makes sure that the containing assemblies are considered the same by the assembly comparer being used.
// If they are in fact not the same (have different name) and the caller requested to know about such types add {x, y}
// to equivalentTypesWithDifferingAssemblies map.
if (equivalentTypesWithDifferingAssemblies != null &&
x.ContainingType == null &&
x.ContainingAssembly != null &&
!AssemblyIdentityComparer.SimpleNameComparer.Equals(x.ContainingAssembly.Name, y.ContainingAssembly.Name) &&
!equivalentTypesWithDifferingAssemblies.ContainsKey(x))
{
equivalentTypesWithDifferingAssemblies.Add(x, y);
}
}
if (x.IsAnonymousType)
return HandleAnonymousTypes(x, y, equivalentTypesWithDifferingAssemblies);
// They look very similar at this point. In the case of non constructed types, we're
// done. However, if they are constructed, then their type arguments have to match
// as well.
return
IsConstructedFromSelf(x) ||
x.IsUnboundGenericType ||
TypeArgumentsAreEquivalent(x.TypeArguments, y.TypeArguments, equivalentTypesWithDifferingAssemblies);
}
private bool HandleTupleTypes(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
Debug.Assert(y.IsTupleType);
var xElements = x.TupleElements;
var yElements = y.TupleElements;
if (xElements.Length != yElements.Length)
return false;
// Check names first if necessary.
if (_symbolEquivalenceComparer._tupleNamesMustMatch)
{
for (var i = 0; i < xElements.Length; i++)
{
var xElement = xElements[i];
var yElement = yElements[i];
if (xElement.Name != yElement.Name)
return false;
}
}
// If we're validating the actual unconstructed ValueTuple type itself, we're done at this point. No
// need to check field types.
//
// For VB we have to unwrap tuples to their underlying types to do this check.
// https://github.com/dotnet/roslyn/issues/42860
if (IsConstructedFromSelf(x.TupleUnderlyingType ?? x))
return true;
for (var i = 0; i < xElements.Length; i++)
{
var xElement = xElements[i];
var yElement = yElements[i];
if (!AreEquivalent(xElement.Type, yElement.Type, equivalentTypesWithDifferingAssemblies))
return false;
}
return true;
}
private bool ParametersAreEquivalent(
ImmutableArray<IParameterSymbol> xParameters,
ImmutableArray<IParameterSymbol> yParameters,
Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies,
bool compareParameterName = false,
bool isParameterNameCaseSensitive = false)
{
// Note the special parameter comparer we pass in. We do this so we don't end up
// infinitely looping between parameters -> type parameters -> methods -> parameters
var count = xParameters.Length;
if (yParameters.Length != count)
{
return false;
}
for (var i = 0; i < count; i++)
{
if (!_symbolEquivalenceComparer.ParameterEquivalenceComparer.Equals(xParameters[i], yParameters[i], equivalentTypesWithDifferingAssemblies, compareParameterName, isParameterNameCaseSensitive))
{
return false;
}
}
return true;
}
internal bool ReturnTypesAreEquivalent(IMethodSymbol x, IMethodSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies = null)
{
return _symbolEquivalenceComparer.SignatureTypeEquivalenceComparer.Equals(x.ReturnType, y.ReturnType, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.ReturnTypeCustomModifiers, y.ReturnTypeCustomModifiers, equivalentTypesWithDifferingAssemblies);
}
private bool TypeArgumentsAreEquivalent(ImmutableArray<ITypeSymbol> xTypeArguments, ImmutableArray<ITypeSymbol> yTypeArguments, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
var count = xTypeArguments.Length;
if (yTypeArguments.Length != count)
{
return false;
}
for (var i = 0; i < count; i++)
{
if (!AreEquivalent(xTypeArguments[i], yTypeArguments[i], equivalentTypesWithDifferingAssemblies))
{
return false;
}
}
return true;
}
private bool HandleAnonymousTypes(INamedTypeSymbol x, INamedTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
if (x.TypeKind == TypeKind.Delegate)
{
return AreEquivalent(x.DelegateInvokeMethod, y.DelegateInvokeMethod, equivalentTypesWithDifferingAssemblies);
}
else
{
var xMembers = x.GetValidAnonymousTypeProperties();
var yMembers = y.GetValidAnonymousTypeProperties();
var xMembersEnumerator = xMembers.GetEnumerator();
var yMembersEnumerator = yMembers.GetEnumerator();
while (xMembersEnumerator.MoveNext())
{
if (!yMembersEnumerator.MoveNext())
{
return false;
}
var p1 = xMembersEnumerator.Current;
var p2 = yMembersEnumerator.Current;
if (p1.Name != p2.Name ||
p1.IsReadOnly != p2.IsReadOnly ||
!AreEquivalent(p1.Type, p2.Type, equivalentTypesWithDifferingAssemblies))
{
return false;
}
}
return !yMembersEnumerator.MoveNext();
}
}
private bool NamespacesAreEquivalent(INamespaceSymbol x, INamespaceSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
if (x.IsGlobalNamespace != y.IsGlobalNamespace ||
x.Name != y.Name)
{
return false;
}
if (x.IsGlobalNamespace && _symbolEquivalenceComparer._assemblyComparerOpt == null)
{
// No need to compare the containers of global namespace when assembly identities are ignored.
return true;
}
return AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private bool ParametersAreEquivalent(IParameterSymbol x, IParameterSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
return
x.IsRefOrOut() == y.IsRefOrOut() &&
x.Name == y.Name &&
AreEquivalent(x.CustomModifiers, y.CustomModifiers, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.Type, y.Type, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private bool PointerTypesAreEquivalent(IPointerTypeSymbol x, IPointerTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
return
AreEquivalent(x.CustomModifiers, y.CustomModifiers, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.PointedAtType, y.PointedAtType, equivalentTypesWithDifferingAssemblies);
}
private bool FunctionPointerTypesAreEquivalent(IFunctionPointerTypeSymbol x, IFunctionPointerTypeSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
=> MethodsAreEquivalent(x.Signature, y.Signature, equivalentTypesWithDifferingAssemblies);
private bool PropertiesAreEquivalent(IPropertySymbol x, IPropertySymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
if (x.ContainingType.IsAnonymousType && y.ContainingType.IsAnonymousType)
{
// We can short circuit here and just use the symbols themselves to determine
// equality. This will properly handle things like the VB case where two
// anonymous types will be considered the same if they have properties that
// differ in casing.
if (x.Equals(y))
{
return true;
}
}
return
x.IsIndexer == y.IsIndexer &&
x.MetadataName == y.MetadataName &&
x.Parameters.Length == y.Parameters.Length &&
ParametersAreEquivalent(x.Parameters, y.Parameters, equivalentTypesWithDifferingAssemblies) &&
AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private bool EventsAreEquivalent(IEventSymbol x, IEventSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
return
x.Name == y.Name &&
AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private bool TypeParametersAreEquivalent(ITypeParameterSymbol x, ITypeParameterSymbol y, Dictionary<INamedTypeSymbol, INamedTypeSymbol>? equivalentTypesWithDifferingAssemblies)
{
Debug.Assert(
(x.TypeParameterKind == TypeParameterKind.Method && IsConstructedFromSelf(x.DeclaringMethod!)) ||
(x.TypeParameterKind == TypeParameterKind.Type && IsConstructedFromSelf(x.ContainingType)) ||
x.TypeParameterKind == TypeParameterKind.Cref);
Debug.Assert(
(y.TypeParameterKind == TypeParameterKind.Method && IsConstructedFromSelf(y.DeclaringMethod!)) ||
(y.TypeParameterKind == TypeParameterKind.Type && IsConstructedFromSelf(y.ContainingType)) ||
y.TypeParameterKind == TypeParameterKind.Cref);
if (x.Ordinal != y.Ordinal ||
x.TypeParameterKind != y.TypeParameterKind)
{
return false;
}
// If this is a method type parameter, and we are in 'non-recurse' mode (because
// we're comparing method parameters), then we're done at this point. The types are
// equal.
if (x.TypeParameterKind == TypeParameterKind.Method && _compareMethodTypeParametersByIndex)
{
return true;
}
if (x.TypeParameterKind == TypeParameterKind.Type && x.ContainingType.IsAnonymousType)
{
// Anonymous type type parameters compare by index as well to prevent
// recursion.
return true;
}
if (x.TypeParameterKind == TypeParameterKind.Cref)
{
return true;
}
return AreEquivalent(x.ContainingSymbol, y.ContainingSymbol, equivalentTypesWithDifferingAssemblies);
}
private static bool RangeVariablesAreEquivalent(IRangeVariableSymbol x, IRangeVariableSymbol y)
=> HaveSameLocation(x, y);
private static bool PreprocessingSymbolsAreEquivalent(IPreprocessingSymbol x, IPreprocessingSymbol y)
=> x.Name == y.Name;
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/EditorFeatures/VisualBasic/LineCommit/ICommitFormatter.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.VisualStudio.Text
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Friend Interface ICommitFormatter
''' <summary>
''' Commits a region by formatting and case correcting it. It is assumed that an
''' ITextUndoTransaction is open the underlying text buffer, as multiple edits may be done
''' by this function. Further, if the operation is cancelled, the buffer may be left in a
''' partially committed state that must be rolled back by the transaction.
''' </summary>
Sub CommitRegion(
spanToFormat As SnapshotSpan,
isExplicitFormat As Boolean,
useSemantics As Boolean,
dirtyRegion As SnapshotSpan,
baseSnapshot As ITextSnapshot,
baseTree As SyntaxTree,
cancellationToken As CancellationToken)
End Interface
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.VisualStudio.Text
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Friend Interface ICommitFormatter
''' <summary>
''' Commits a region by formatting and case correcting it. It is assumed that an
''' ITextUndoTransaction is open the underlying text buffer, as multiple edits may be done
''' by this function. Further, if the operation is cancelled, the buffer may be left in a
''' partially committed state that must be rolled back by the transaction.
''' </summary>
Sub CommitRegion(
spanToFormat As SnapshotSpan,
isExplicitFormat As Boolean,
useSemantics As Boolean,
dirtyRegion As SnapshotSpan,
baseSnapshot As ITextSnapshot,
baseTree As SyntaxTree,
cancellationToken As CancellationToken)
End Interface
End Namespace
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Compilers/Core/Portable/Syntax/SyntaxList.WithTwoChildren.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Syntax
{
internal partial class SyntaxList
{
internal class WithTwoChildren : SyntaxList
{
private SyntaxNode? _child0;
private SyntaxNode? _child1;
internal WithTwoChildren(InternalSyntax.SyntaxList green, SyntaxNode? parent, int position)
: base(green, parent, position)
{
}
internal override SyntaxNode? GetNodeSlot(int index)
{
switch (index)
{
case 0:
return this.GetRedElement(ref _child0, 0);
case 1:
return this.GetRedElementIfNotToken(ref _child1);
default:
return null;
}
}
internal override SyntaxNode? GetCachedSlot(int index)
{
switch (index)
{
case 0:
return _child0;
case 1:
return _child1;
default:
return null;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Syntax
{
internal partial class SyntaxList
{
internal class WithTwoChildren : SyntaxList
{
private SyntaxNode? _child0;
private SyntaxNode? _child1;
internal WithTwoChildren(InternalSyntax.SyntaxList green, SyntaxNode? parent, int position)
: base(green, parent, position)
{
}
internal override SyntaxNode? GetNodeSlot(int index)
{
switch (index)
{
case 0:
return this.GetRedElement(ref _child0, 0);
case 1:
return this.GetRedElementIfNotToken(ref _child1);
default:
return null;
}
}
internal override SyntaxNode? GetCachedSlot(int index)
{
switch (index)
{
case 0:
return _child0;
case 1:
return _child1;
default:
return null;
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/VisualStudio/Core/Def/Implementation/PullMemberUp/WarningDialog/PullMemberUpWarningViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PullMemberUp;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.WarningDialog
{
internal class PullMemberUpWarningViewModel : AbstractNotifyPropertyChanged
{
public ImmutableArray<string> WarningMessageContainer { get; set; }
public string ProblemsListViewAutomationText => ServicesVSResources.Review_Changes;
public PullMemberUpWarningViewModel(PullMembersUpOptions options)
=> WarningMessageContainer = GenerateMessage(options);
private ImmutableArray<string> GenerateMessage(PullMembersUpOptions options)
{
var warningMessagesBuilder = ImmutableArray.CreateBuilder<string>();
if (!options.Destination.IsAbstract &&
options.MemberAnalysisResults.Any(result => result.ChangeDestinationTypeToAbstract))
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeTargetToAbstract);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_abstract, options.Destination.Name));
}
foreach (var result in options.MemberAnalysisResults)
{
if (result.ChangeOriginalToPublic)
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeOriginToPublic);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_public, result.Member.Name));
}
if (result.ChangeOriginalToNonStatic)
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeOriginToNonStatic);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_non_static, result.Member.Name));
}
}
return warningMessagesBuilder.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.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PullMemberUp;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.WarningDialog
{
internal class PullMemberUpWarningViewModel : AbstractNotifyPropertyChanged
{
public ImmutableArray<string> WarningMessageContainer { get; set; }
public string ProblemsListViewAutomationText => ServicesVSResources.Review_Changes;
public PullMemberUpWarningViewModel(PullMembersUpOptions options)
=> WarningMessageContainer = GenerateMessage(options);
private ImmutableArray<string> GenerateMessage(PullMembersUpOptions options)
{
var warningMessagesBuilder = ImmutableArray.CreateBuilder<string>();
if (!options.Destination.IsAbstract &&
options.MemberAnalysisResults.Any(result => result.ChangeDestinationTypeToAbstract))
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeTargetToAbstract);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_abstract, options.Destination.Name));
}
foreach (var result in options.MemberAnalysisResults)
{
if (result.ChangeOriginalToPublic)
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeOriginToPublic);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_public, result.Member.Name));
}
if (result.ChangeOriginalToNonStatic)
{
Logger.Log(FunctionId.PullMembersUpWarning_ChangeOriginToNonStatic);
warningMessagesBuilder.Add(string.Format(ServicesVSResources._0_will_be_changed_to_non_static, result.Member.Name));
}
}
return warningMessagesBuilder.ToImmutableArray();
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Analyzers/Core/Analyzers/IDEDiagnosticIdToOptionMappingHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Helper type to map <see cref="IDEDiagnosticIds"/> to an unique editorconfig code style option, if any,
/// such that diagnostic's severity can be configured in .editorconfig with an entry such as:
/// "%option_name% = %option_value%:%severity%
/// </summary>
internal static class IDEDiagnosticIdToOptionMappingHelper
{
private static readonly ConcurrentDictionary<string, ImmutableHashSet<IOption2>> s_diagnosticIdToOptionMap = new();
private static readonly ConcurrentDictionary<string, ConcurrentDictionary<string, ImmutableHashSet<IOption2>>> s_diagnosticIdToLanguageSpecificOptionsMap = new();
public static bool TryGetMappedOptions(string diagnosticId, string language, [NotNullWhen(true)] out ImmutableHashSet<IOption2>? options)
=> s_diagnosticIdToOptionMap.TryGetValue(diagnosticId, out options) ||
(s_diagnosticIdToLanguageSpecificOptionsMap.TryGetValue(language, out var map) &&
map.TryGetValue(diagnosticId, out options));
public static void AddOptionMapping(string diagnosticId, ImmutableHashSet<IPerLanguageOption> perLanguageOptions)
{
diagnosticId = diagnosticId ?? throw new ArgumentNullException(nameof(diagnosticId));
perLanguageOptions = perLanguageOptions ?? throw new ArgumentNullException(nameof(perLanguageOptions));
var options = perLanguageOptions.Cast<IOption2>().ToImmutableHashSet();
AddOptionMapping(s_diagnosticIdToOptionMap, diagnosticId, options);
}
public static void AddOptionMapping(string diagnosticId, ImmutableHashSet<ILanguageSpecificOption> languageSpecificOptions, string language)
{
diagnosticId = diagnosticId ?? throw new ArgumentNullException(nameof(diagnosticId));
languageSpecificOptions = languageSpecificOptions ?? throw new ArgumentNullException(nameof(languageSpecificOptions));
language = language ?? throw new ArgumentNullException(nameof(language));
var map = s_diagnosticIdToLanguageSpecificOptionsMap.GetOrAdd(language, _ => new ConcurrentDictionary<string, ImmutableHashSet<IOption2>>());
var options = languageSpecificOptions.Cast<IOption2>().ToImmutableHashSet();
AddOptionMapping(map, diagnosticId, options);
}
private static void AddOptionMapping(ConcurrentDictionary<string, ImmutableHashSet<IOption2>> map, string diagnosticId, ImmutableHashSet<IOption2> options)
{
// Verify that the option is either being added for the first time, or the existing option is already the same.
// Latter can happen in tests as we re-instantiate the analyzer for every test, which attempts to add the mapping every time.
Debug.Assert(!map.TryGetValue(diagnosticId, out var existingOptions) || options.SetEquals(existingOptions));
map.TryAdd(diagnosticId, options);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Helper type to map <see cref="IDEDiagnosticIds"/> to an unique editorconfig code style option, if any,
/// such that diagnostic's severity can be configured in .editorconfig with an entry such as:
/// "%option_name% = %option_value%:%severity%
/// </summary>
internal static class IDEDiagnosticIdToOptionMappingHelper
{
private static readonly ConcurrentDictionary<string, ImmutableHashSet<IOption2>> s_diagnosticIdToOptionMap = new();
private static readonly ConcurrentDictionary<string, ConcurrentDictionary<string, ImmutableHashSet<IOption2>>> s_diagnosticIdToLanguageSpecificOptionsMap = new();
public static bool TryGetMappedOptions(string diagnosticId, string language, [NotNullWhen(true)] out ImmutableHashSet<IOption2>? options)
=> s_diagnosticIdToOptionMap.TryGetValue(diagnosticId, out options) ||
(s_diagnosticIdToLanguageSpecificOptionsMap.TryGetValue(language, out var map) &&
map.TryGetValue(diagnosticId, out options));
public static void AddOptionMapping(string diagnosticId, ImmutableHashSet<IPerLanguageOption> perLanguageOptions)
{
diagnosticId = diagnosticId ?? throw new ArgumentNullException(nameof(diagnosticId));
perLanguageOptions = perLanguageOptions ?? throw new ArgumentNullException(nameof(perLanguageOptions));
var options = perLanguageOptions.Cast<IOption2>().ToImmutableHashSet();
AddOptionMapping(s_diagnosticIdToOptionMap, diagnosticId, options);
}
public static void AddOptionMapping(string diagnosticId, ImmutableHashSet<ILanguageSpecificOption> languageSpecificOptions, string language)
{
diagnosticId = diagnosticId ?? throw new ArgumentNullException(nameof(diagnosticId));
languageSpecificOptions = languageSpecificOptions ?? throw new ArgumentNullException(nameof(languageSpecificOptions));
language = language ?? throw new ArgumentNullException(nameof(language));
var map = s_diagnosticIdToLanguageSpecificOptionsMap.GetOrAdd(language, _ => new ConcurrentDictionary<string, ImmutableHashSet<IOption2>>());
var options = languageSpecificOptions.Cast<IOption2>().ToImmutableHashSet();
AddOptionMapping(map, diagnosticId, options);
}
private static void AddOptionMapping(ConcurrentDictionary<string, ImmutableHashSet<IOption2>> map, string diagnosticId, ImmutableHashSet<IOption2> options)
{
// Verify that the option is either being added for the first time, or the existing option is already the same.
// Latter can happen in tests as we re-instantiate the analyzer for every test, which attempts to add the mapping every time.
Debug.Assert(!map.TryGetValue(diagnosticId, out var existingOptions) || options.SetEquals(existingOptions));
map.TryAdd(diagnosticId, options);
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpInteractiveCommands.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpInteractiveCommands : AbstractInteractiveWindowTest
{
public CSharpInteractiveCommands(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
[WpfFact]
public void VerifyPreviousAndNextHistory()
{
VisualStudio.InteractiveWindow.SubmitText("1 + 2");
VisualStudio.InteractiveWindow.SubmitText("1.ToString()");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"1\"");
VisualStudio.SendKeys.Send(Alt(VirtualKey.Up));
VisualStudio.InteractiveWindow.Verify.LastReplInput("1.ToString()");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"1\"");
VisualStudio.SendKeys.Send(Alt(VirtualKey.Up));
VisualStudio.InteractiveWindow.Verify.LastReplInput("1.ToString()");
VisualStudio.SendKeys.Send(Alt(VirtualKey.Up));
VisualStudio.InteractiveWindow.Verify.LastReplInput("1 + 2");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("3");
VisualStudio.SendKeys.Send(Alt(VirtualKey.Down));
VisualStudio.InteractiveWindow.Verify.LastReplInput("1.ToString()");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"1\"");
}
[WpfFact]
public void VerifyMaybeExecuteInput()
{
VisualStudio.InteractiveWindow.InsertCode("2 + 3");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("5");
}
[WpfFact]
public void VerifyNewLineAndIndent()
{
VisualStudio.InteractiveWindow.InsertCode("3 + ");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.InsertCode("4");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("7");
}
[WpfFact]
public void VerifyExecuteInput()
{
VisualStudio.InteractiveWindow.SubmitText("1 + ");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("CS1733");
}
[WpfFact]
public void VerifyForceNewLineAndIndent()
{
VisualStudio.InteractiveWindow.InsertCode("1 + 2");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.SubmitText("+ 3");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("3");
VisualStudio.InteractiveWindow.Verify.ReplPromptConsistency("<![CDATA[1 + 2 + 3]]>", "6");
}
[WpfFact]
public void VerifyCancelInput()
{
VisualStudio.InteractiveWindow.InsertCode("1 + 4");
VisualStudio.SendKeys.Send(Shift(VirtualKey.Enter));
VisualStudio.SendKeys.Send(VirtualKey.Escape);
VisualStudio.InteractiveWindow.Verify.LastReplInput(string.Empty);
}
[WpfFact]
public void VerifyUndoAndRedo()
{
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.InsertCode(" 2 + 4 ");
VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z));
VisualStudio.InteractiveWindow.Verify.ReplPromptConsistency("< ![CDATA[]] >", string.Empty);
VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Y));
VisualStudio.InteractiveWindow.Verify.LastReplInput(" 2 + 4 ");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("6");
}
[WpfFact]
public void CutDeletePasteSelectAll()
{
ClearInteractiveWindow();
VisualStudio.InteractiveWindow.InsertCode("Text");
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineStart);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineEnd);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineStartExtend);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_SelectionCancel);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineEndExtend);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_SelectAll);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_SelectAll);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Copy);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Cut);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Paste);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("Text");
VisualStudio.InteractiveWindow.Verify.LastReplInput("Text");
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Delete);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineUp);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineDown);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Paste);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("TextText");
VisualStudio.InteractiveWindow.Verify.LastReplInput("TextText");
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Paste);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("TextTextText");
VisualStudio.InteractiveWindow.Verify.LastReplInput("TextTextText");
VisualStudio.SendKeys.Send(VirtualKey.Escape);
}
//<!-- Regression test for bug 13731.
// Unfortunately we don't have good unit-test infrastructure to test InteractiveWindow.cs.
// For now, since we don't have coverage of InteractiveWindow.IndentCurrentLine at all,
// I'd rather have a quick integration test scenario rather than no coverage at all.
// At some point when we start investing in Interactive work again, we'll go through some
// of these tests and convert them to unit-tests.
// -->
//<!-- TODO(https://github.com/dotnet/roslyn/issues/4235)
[WpfFact]
public void VerifyReturnIndentCurrentLine()
{
VisualStudio.InteractiveWindow.ClearScreen();
VisualStudio.SendKeys.Send(" (");
VisualStudio.SendKeys.Send(")");
VisualStudio.SendKeys.Send(VirtualKey.Left);
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.Verify.CaretPosition(12);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpInteractiveCommands : AbstractInteractiveWindowTest
{
public CSharpInteractiveCommands(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory)
{
}
[WpfFact]
public void VerifyPreviousAndNextHistory()
{
VisualStudio.InteractiveWindow.SubmitText("1 + 2");
VisualStudio.InteractiveWindow.SubmitText("1.ToString()");
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"1\"");
VisualStudio.SendKeys.Send(Alt(VirtualKey.Up));
VisualStudio.InteractiveWindow.Verify.LastReplInput("1.ToString()");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"1\"");
VisualStudio.SendKeys.Send(Alt(VirtualKey.Up));
VisualStudio.InteractiveWindow.Verify.LastReplInput("1.ToString()");
VisualStudio.SendKeys.Send(Alt(VirtualKey.Up));
VisualStudio.InteractiveWindow.Verify.LastReplInput("1 + 2");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("3");
VisualStudio.SendKeys.Send(Alt(VirtualKey.Down));
VisualStudio.InteractiveWindow.Verify.LastReplInput("1.ToString()");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("\"1\"");
}
[WpfFact]
public void VerifyMaybeExecuteInput()
{
VisualStudio.InteractiveWindow.InsertCode("2 + 3");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("5");
}
[WpfFact]
public void VerifyNewLineAndIndent()
{
VisualStudio.InteractiveWindow.InsertCode("3 + ");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.InsertCode("4");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("7");
}
[WpfFact]
public void VerifyExecuteInput()
{
VisualStudio.InteractiveWindow.SubmitText("1 + ");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("CS1733");
}
[WpfFact]
public void VerifyForceNewLineAndIndent()
{
VisualStudio.InteractiveWindow.InsertCode("1 + 2");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.SubmitText("+ 3");
VisualStudio.InteractiveWindow.WaitForLastReplOutputContains("3");
VisualStudio.InteractiveWindow.Verify.ReplPromptConsistency("<![CDATA[1 + 2 + 3]]>", "6");
}
[WpfFact]
public void VerifyCancelInput()
{
VisualStudio.InteractiveWindow.InsertCode("1 + 4");
VisualStudio.SendKeys.Send(Shift(VirtualKey.Enter));
VisualStudio.SendKeys.Send(VirtualKey.Escape);
VisualStudio.InteractiveWindow.Verify.LastReplInput(string.Empty);
}
[WpfFact]
public void VerifyUndoAndRedo()
{
VisualStudio.InteractiveWindow.ClearReplText();
VisualStudio.InteractiveWindow.InsertCode(" 2 + 4 ");
VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Z));
VisualStudio.InteractiveWindow.Verify.ReplPromptConsistency("< ![CDATA[]] >", string.Empty);
VisualStudio.SendKeys.Send(Ctrl(VirtualKey.Y));
VisualStudio.InteractiveWindow.Verify.LastReplInput(" 2 + 4 ");
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.WaitForLastReplOutput("6");
}
[WpfFact]
public void CutDeletePasteSelectAll()
{
ClearInteractiveWindow();
VisualStudio.InteractiveWindow.InsertCode("Text");
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineStart);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineEnd);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineStartExtend);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_SelectionCancel);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineEndExtend);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_SelectAll);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_SelectAll);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Copy);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Cut);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Paste);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("Text");
VisualStudio.InteractiveWindow.Verify.LastReplInput("Text");
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Delete);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineUp);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_LineDown);
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Paste);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("TextText");
VisualStudio.InteractiveWindow.Verify.LastReplInput("TextText");
VisualStudio.ExecuteCommand(WellKnownCommandNames.Edit_Paste);
VisualStudio.InteractiveWindow.WaitForLastReplInputContains("TextTextText");
VisualStudio.InteractiveWindow.Verify.LastReplInput("TextTextText");
VisualStudio.SendKeys.Send(VirtualKey.Escape);
}
//<!-- Regression test for bug 13731.
// Unfortunately we don't have good unit-test infrastructure to test InteractiveWindow.cs.
// For now, since we don't have coverage of InteractiveWindow.IndentCurrentLine at all,
// I'd rather have a quick integration test scenario rather than no coverage at all.
// At some point when we start investing in Interactive work again, we'll go through some
// of these tests and convert them to unit-tests.
// -->
//<!-- TODO(https://github.com/dotnet/roslyn/issues/4235)
[WpfFact]
public void VerifyReturnIndentCurrentLine()
{
VisualStudio.InteractiveWindow.ClearScreen();
VisualStudio.SendKeys.Send(" (");
VisualStudio.SendKeys.Send(")");
VisualStudio.SendKeys.Send(VirtualKey.Left);
VisualStudio.SendKeys.Send(VirtualKey.Enter);
VisualStudio.InteractiveWindow.Verify.CaretPosition(12);
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Compilers/Core/Portable/Optional.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Combines a value, <see cref="Value"/>, and a flag, <see cref="HasValue"/>,
/// indicating whether or not that value is meaningful.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
public readonly struct Optional<T>
{
private readonly bool _hasValue;
private readonly T _value;
/// <summary>
/// Constructs an <see cref="Optional{T}"/> with a meaningful value.
/// </summary>
/// <param name="value"></param>
public Optional(T value)
{
_hasValue = true;
_value = value;
}
/// <summary>
/// Returns <see langword="true"/> if the <see cref="Value"/> will return a meaningful value.
/// </summary>
/// <returns></returns>
public bool HasValue
{
get { return _hasValue; }
}
/// <summary>
/// Gets the value of the current object. Not meaningful unless <see cref="HasValue"/> returns <see langword="true"/>.
/// </summary>
/// <remarks>
/// <para>Unlike <see cref="Nullable{T}.Value"/>, this property does not throw an exception when
/// <see cref="HasValue"/> is <see langword="false"/>.</para>
/// </remarks>
/// <returns>
/// <para>The value if <see cref="HasValue"/> is <see langword="true"/>; otherwise, the default value for type
/// <typeparamref name="T"/>.</para>
/// </returns>
public T Value
{
get { return _value; }
}
/// <summary>
/// Creates a new object initialized to a meaningful value.
/// </summary>
/// <param name="value"></param>
public static implicit operator Optional<T>(T value)
{
return new Optional<T>(value);
}
/// <summary>
/// Returns a string representation of this object.
/// </summary>
public override string ToString()
{
// Note: For nullable types, it's possible to have _hasValue true and _value null.
return _hasValue
? _value?.ToString() ?? "null"
: "unspecified";
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Combines a value, <see cref="Value"/>, and a flag, <see cref="HasValue"/>,
/// indicating whether or not that value is meaningful.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
public readonly struct Optional<T>
{
private readonly bool _hasValue;
private readonly T _value;
/// <summary>
/// Constructs an <see cref="Optional{T}"/> with a meaningful value.
/// </summary>
/// <param name="value"></param>
public Optional(T value)
{
_hasValue = true;
_value = value;
}
/// <summary>
/// Returns <see langword="true"/> if the <see cref="Value"/> will return a meaningful value.
/// </summary>
/// <returns></returns>
public bool HasValue
{
get { return _hasValue; }
}
/// <summary>
/// Gets the value of the current object. Not meaningful unless <see cref="HasValue"/> returns <see langword="true"/>.
/// </summary>
/// <remarks>
/// <para>Unlike <see cref="Nullable{T}.Value"/>, this property does not throw an exception when
/// <see cref="HasValue"/> is <see langword="false"/>.</para>
/// </remarks>
/// <returns>
/// <para>The value if <see cref="HasValue"/> is <see langword="true"/>; otherwise, the default value for type
/// <typeparamref name="T"/>.</para>
/// </returns>
public T Value
{
get { return _value; }
}
/// <summary>
/// Creates a new object initialized to a meaningful value.
/// </summary>
/// <param name="value"></param>
public static implicit operator Optional<T>(T value)
{
return new Optional<T>(value);
}
/// <summary>
/// Returns a string representation of this object.
/// </summary>
public override string ToString()
{
// Note: For nullable types, it's possible to have _hasValue true and _value null.
return _hasValue
? _value?.ToString() ?? "null"
: "unspecified";
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/VisualStudio/Core/Def/Shared/LogicalStringComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal class LogicalStringComparer : IComparer<string>
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
public static readonly IComparer<string> Instance = new LogicalStringComparer();
private LogicalStringComparer()
{
}
public int Compare(string x, string y)
=> StrCmpLogicalW(x, y);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal class LogicalStringComparer : IComparer<string>
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
public static readonly IComparer<string> Instance = new LogicalStringComparer();
private LogicalStringComparer()
{
}
public int Compare(string x, string y)
=> StrCmpLogicalW(x, y);
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/AbstractDescriptionBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
{
internal abstract partial class AbstractDescriptionBuilder
{
private readonly IVsObjectBrowserDescription3 _description;
private readonly AbstractObjectBrowserLibraryManager _libraryManager;
private readonly ObjectListItem _listItem;
private readonly Project _project;
private static readonly SymbolDisplayFormat s_typeDisplay = new(
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
protected AbstractDescriptionBuilder(
IVsObjectBrowserDescription3 description,
AbstractObjectBrowserLibraryManager libraryManager,
ObjectListItem listItem,
Project project)
{
_description = description;
_libraryManager = libraryManager;
_listItem = listItem;
_project = project;
}
private Compilation GetCompilation()
{
return _project
.GetCompilationAsync(CancellationToken.None)
.WaitAndGetResult_ObjectBrowser(CancellationToken.None);
}
protected void AddAssemblyLink(IAssemblySymbol assemblySymbol)
{
var name = assemblySymbol.Identity.Name;
var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForAssembly(assemblySymbol);
_description.AddDescriptionText3(name, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo);
}
protected void AddComma()
=> _description.AddDescriptionText3(", ", VSOBDESCRIPTIONSECTION.OBDS_COMMA, null);
protected void AddEndDeclaration()
=> _description.AddDescriptionText3("\n", VSOBDESCRIPTIONSECTION.OBDS_ENDDECL, null);
protected void AddIndent()
=> _description.AddDescriptionText3(" ", VSOBDESCRIPTIONSECTION.OBDS_MISC, null);
protected void AddLineBreak()
=> _description.AddDescriptionText3("\n", VSOBDESCRIPTIONSECTION.OBDS_MISC, null);
protected void AddName(string text)
=> _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_NAME, null);
protected void AddNamespaceLink(INamespaceSymbol namespaceSymbol)
{
if (namespaceSymbol.IsGlobalNamespace)
{
return;
}
var text = namespaceSymbol.ToDisplayString();
var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForNamespace(namespaceSymbol, _project, GetCompilation(), useExpandedHierarchy: false);
_description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo);
}
protected void AddParam(string text)
=> _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_PARAM, null);
protected void AddText(string text)
=> _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_MISC, null);
protected void AddTypeLink(ITypeSymbol typeSymbol, LinkFlags flags)
{
if (typeSymbol.TypeKind == TypeKind.Unknown ||
typeSymbol.TypeKind == TypeKind.Error ||
typeSymbol.TypeKind == TypeKind.TypeParameter ||
typeSymbol.SpecialType == SpecialType.System_Void)
{
AddName(typeSymbol.ToDisplayString(s_typeDisplay));
return;
}
var useSpecialTypes = (flags & LinkFlags.ExpandPredefinedTypes) == 0;
var splitLink = !useSpecialTypes & (flags & LinkFlags.SplitNamespaceAndType) != 0;
if (splitLink && !typeSymbol.ContainingNamespace.IsGlobalNamespace)
{
AddNamespaceLink(typeSymbol.ContainingNamespace);
AddText(".");
}
var typeQualificationStyle = splitLink
? SymbolDisplayTypeQualificationStyle.NameAndContainingTypes
: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces;
var miscellaneousOptions = useSpecialTypes
? SymbolDisplayMiscellaneousOptions.UseSpecialTypes
: SymbolDisplayMiscellaneousOptions.ExpandNullable;
var typeDisplayFormat = new SymbolDisplayFormat(
typeQualificationStyle: typeQualificationStyle,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
miscellaneousOptions: miscellaneousOptions);
var text = typeSymbol.ToDisplayString(typeDisplayFormat);
var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForType(typeSymbol, _project, GetCompilation(), useExpandedHierarchy: false);
_description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo);
}
private void BuildProject(ProjectListItem projectListItem)
{
AddText(ServicesVSResources.Project);
AddName(projectListItem.DisplayText);
}
private void BuildReference(ReferenceListItem referenceListItem)
{
AddText(ServicesVSResources.Assembly);
AddName(referenceListItem.DisplayText);
AddEndDeclaration();
AddIndent();
if (referenceListItem.MetadataReference is PortableExecutableReference portableExecutableReference)
{
AddText(portableExecutableReference.FilePath);
}
}
private void BuildNamespace(NamespaceListItem namespaceListItem, _VSOBJDESCOPTIONS options)
{
var compilation = GetCompilation();
if (compilation == null)
{
return;
}
var namespaceSymbol = namespaceListItem.ResolveTypedSymbol(compilation);
if (namespaceSymbol == null)
{
return;
}
BuildNamespaceDeclaration(namespaceSymbol, options);
AddEndDeclaration();
BuildMemberOf(namespaceSymbol.ContainingAssembly);
}
private void BuildType(TypeListItem typeListItem, _VSOBJDESCOPTIONS options)
{
var compilation = GetCompilation();
if (compilation == null)
{
return;
}
var symbol = typeListItem.ResolveTypedSymbol(compilation);
if (symbol == null)
{
return;
}
if (symbol.TypeKind == TypeKind.Delegate)
{
BuildDelegateDeclaration(symbol, options);
}
else
{
BuildTypeDeclaration(symbol, options);
}
AddEndDeclaration();
BuildMemberOf(symbol.ContainingNamespace);
BuildXmlDocumentation(symbol, compilation);
}
private void BuildMember(MemberListItem memberListItem, _VSOBJDESCOPTIONS options)
{
var compilation = GetCompilation();
if (compilation == null)
{
return;
}
var symbol = memberListItem.ResolveTypedSymbol(compilation);
if (symbol == null)
{
return;
}
switch (symbol.Kind)
{
case SymbolKind.Method:
BuildMethodDeclaration((IMethodSymbol)symbol, options);
break;
case SymbolKind.Field:
BuildFieldDeclaration((IFieldSymbol)symbol, options);
break;
case SymbolKind.Property:
BuildPropertyDeclaration((IPropertySymbol)symbol, options);
break;
case SymbolKind.Event:
BuildEventDeclaration((IEventSymbol)symbol, options);
break;
default:
Debug.Fail("Unsupported member kind: " + symbol.Kind.ToString());
return;
}
AddEndDeclaration();
BuildMemberOf(symbol.ContainingType);
BuildXmlDocumentation(symbol, compilation);
}
protected abstract void BuildNamespaceDeclaration(INamespaceSymbol namespaceSymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildDelegateDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildTypeDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildMethodDeclaration(IMethodSymbol methodSymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildFieldDeclaration(IFieldSymbol fieldSymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildPropertyDeclaration(IPropertySymbol propertySymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildEventDeclaration(IEventSymbol eventSymbol, _VSOBJDESCOPTIONS options);
private void BuildMemberOf(ISymbol containingSymbol)
{
if (containingSymbol is INamespaceSymbol &&
((INamespaceSymbol)containingSymbol).IsGlobalNamespace)
{
containingSymbol = containingSymbol.ContainingAssembly;
}
var memberOfText = ServicesVSResources.Member_of_0;
const string specifier = "{0}";
var index = memberOfText.IndexOf(specifier, StringComparison.Ordinal);
if (index < 0)
{
Debug.Fail("MemberOf string resource is incorrect.");
return;
}
var left = memberOfText.Substring(0, index);
var right = memberOfText.Substring(index + specifier.Length);
AddIndent();
AddText(left);
if (containingSymbol is IAssemblySymbol assemblySymbol)
{
AddAssemblyLink(assemblySymbol);
}
else if (containingSymbol is ITypeSymbol typeSymbol)
{
AddTypeLink(typeSymbol, LinkFlags.SplitNamespaceAndType | LinkFlags.ExpandPredefinedTypes);
}
else if (containingSymbol is INamespaceSymbol namespaceSymbol)
{
AddNamespaceLink(namespaceSymbol);
}
AddText(right);
AddEndDeclaration();
}
private void BuildXmlDocumentation(ISymbol symbol, Compilation compilation)
{
var documentationComment = symbol.GetDocumentationComment(compilation, expandIncludes: true, expandInheritdoc: true, cancellationToken: CancellationToken.None);
if (documentationComment == null)
{
return;
}
var formattingService = _project.LanguageServices.GetService<IDocumentationCommentFormattingService>();
if (formattingService == null)
{
return;
}
var emittedDocs = false;
if (documentationComment.SummaryText != null)
{
AddLineBreak();
AddName(ServicesVSResources.Summary_colon);
AddLineBreak();
AddText(formattingService.Format(documentationComment.SummaryText, compilation));
emittedDocs = true;
}
if (documentationComment.TypeParameterNames.Length > 0)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Type_Parameters_colon);
foreach (var typeParameterName in documentationComment.TypeParameterNames)
{
AddLineBreak();
var typeParameterText = documentationComment.GetTypeParameterText(typeParameterName);
if (typeParameterText != null)
{
AddParam(typeParameterName);
AddText(": ");
AddText(formattingService.Format(typeParameterText, compilation));
emittedDocs = true;
}
}
}
if (documentationComment.ParameterNames.Length > 0)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Parameters_colon1);
foreach (var parameterName in documentationComment.ParameterNames)
{
AddLineBreak();
var parameterText = documentationComment.GetParameterText(parameterName);
if (parameterText != null)
{
AddParam(parameterName);
AddText(": ");
AddText(formattingService.Format(parameterText, compilation));
emittedDocs = true;
}
}
}
if (ShowReturnsDocumentation(symbol) && documentationComment.ReturnsText != null)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Returns_colon);
AddLineBreak();
AddText(formattingService.Format(documentationComment.ReturnsText, compilation));
emittedDocs = true;
}
if (ShowValueDocumentation(symbol) && documentationComment.ValueText != null)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Value_colon);
AddLineBreak();
AddText(formattingService.Format(documentationComment.ValueText, compilation));
emittedDocs = true;
}
if (documentationComment.RemarksText != null)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Remarks_colon);
AddLineBreak();
AddText(formattingService.Format(documentationComment.RemarksText, compilation));
emittedDocs = true;
}
if (documentationComment.ExceptionTypes.Length > 0)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Exceptions_colon);
foreach (var exceptionType in documentationComment.ExceptionTypes)
{
if (DocumentationCommentId.GetFirstSymbolForDeclarationId(exceptionType, compilation) is INamedTypeSymbol exceptionTypeSymbol)
{
AddLineBreak();
var exceptionTexts = documentationComment.GetExceptionTexts(exceptionType);
if (exceptionTexts.Length == 0)
{
AddTypeLink(exceptionTypeSymbol, LinkFlags.None);
}
else
{
foreach (var exceptionText in exceptionTexts)
{
AddTypeLink(exceptionTypeSymbol, LinkFlags.None);
AddText(": ");
AddText(formattingService.Format(exceptionText, compilation));
}
}
}
}
}
}
private bool ShowReturnsDocumentation(ISymbol symbol)
{
return (symbol.Kind == SymbolKind.NamedType && ((INamedTypeSymbol)symbol).TypeKind == TypeKind.Delegate)
|| symbol.Kind == SymbolKind.Method
|| symbol.Kind == SymbolKind.Property;
}
private bool ShowValueDocumentation(ISymbol symbol)
{
// <returns> is often used in places where <value> was originally intended. Allow either to be used in
// documentation comments since they are not likely to be used together and it's not clear which one a
// particular code base will be using more often.
return ShowReturnsDocumentation(symbol);
}
internal bool TryBuild(_VSOBJDESCOPTIONS options)
{
switch (_listItem)
{
case ProjectListItem projectListItem:
BuildProject(projectListItem);
return true;
case ReferenceListItem referenceListItem:
BuildReference(referenceListItem);
return true;
case NamespaceListItem namespaceListItem:
BuildNamespace(namespaceListItem, options);
return true;
case TypeListItem typeListItem:
BuildType(typeListItem, options);
return true;
case MemberListItem memberListItem:
BuildMember(memberListItem, options);
return true;
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
{
internal abstract partial class AbstractDescriptionBuilder
{
private readonly IVsObjectBrowserDescription3 _description;
private readonly AbstractObjectBrowserLibraryManager _libraryManager;
private readonly ObjectListItem _listItem;
private readonly Project _project;
private static readonly SymbolDisplayFormat s_typeDisplay = new(
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
protected AbstractDescriptionBuilder(
IVsObjectBrowserDescription3 description,
AbstractObjectBrowserLibraryManager libraryManager,
ObjectListItem listItem,
Project project)
{
_description = description;
_libraryManager = libraryManager;
_listItem = listItem;
_project = project;
}
private Compilation GetCompilation()
{
return _project
.GetCompilationAsync(CancellationToken.None)
.WaitAndGetResult_ObjectBrowser(CancellationToken.None);
}
protected void AddAssemblyLink(IAssemblySymbol assemblySymbol)
{
var name = assemblySymbol.Identity.Name;
var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForAssembly(assemblySymbol);
_description.AddDescriptionText3(name, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo);
}
protected void AddComma()
=> _description.AddDescriptionText3(", ", VSOBDESCRIPTIONSECTION.OBDS_COMMA, null);
protected void AddEndDeclaration()
=> _description.AddDescriptionText3("\n", VSOBDESCRIPTIONSECTION.OBDS_ENDDECL, null);
protected void AddIndent()
=> _description.AddDescriptionText3(" ", VSOBDESCRIPTIONSECTION.OBDS_MISC, null);
protected void AddLineBreak()
=> _description.AddDescriptionText3("\n", VSOBDESCRIPTIONSECTION.OBDS_MISC, null);
protected void AddName(string text)
=> _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_NAME, null);
protected void AddNamespaceLink(INamespaceSymbol namespaceSymbol)
{
if (namespaceSymbol.IsGlobalNamespace)
{
return;
}
var text = namespaceSymbol.ToDisplayString();
var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForNamespace(namespaceSymbol, _project, GetCompilation(), useExpandedHierarchy: false);
_description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo);
}
protected void AddParam(string text)
=> _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_PARAM, null);
protected void AddText(string text)
=> _description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_MISC, null);
protected void AddTypeLink(ITypeSymbol typeSymbol, LinkFlags flags)
{
if (typeSymbol.TypeKind == TypeKind.Unknown ||
typeSymbol.TypeKind == TypeKind.Error ||
typeSymbol.TypeKind == TypeKind.TypeParameter ||
typeSymbol.SpecialType == SpecialType.System_Void)
{
AddName(typeSymbol.ToDisplayString(s_typeDisplay));
return;
}
var useSpecialTypes = (flags & LinkFlags.ExpandPredefinedTypes) == 0;
var splitLink = !useSpecialTypes & (flags & LinkFlags.SplitNamespaceAndType) != 0;
if (splitLink && !typeSymbol.ContainingNamespace.IsGlobalNamespace)
{
AddNamespaceLink(typeSymbol.ContainingNamespace);
AddText(".");
}
var typeQualificationStyle = splitLink
? SymbolDisplayTypeQualificationStyle.NameAndContainingTypes
: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces;
var miscellaneousOptions = useSpecialTypes
? SymbolDisplayMiscellaneousOptions.UseSpecialTypes
: SymbolDisplayMiscellaneousOptions.ExpandNullable;
var typeDisplayFormat = new SymbolDisplayFormat(
typeQualificationStyle: typeQualificationStyle,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
miscellaneousOptions: miscellaneousOptions);
var text = typeSymbol.ToDisplayString(typeDisplayFormat);
var navInfo = _libraryManager.LibraryService.NavInfoFactory.CreateForType(typeSymbol, _project, GetCompilation(), useExpandedHierarchy: false);
_description.AddDescriptionText3(text, VSOBDESCRIPTIONSECTION.OBDS_TYPE, navInfo);
}
private void BuildProject(ProjectListItem projectListItem)
{
AddText(ServicesVSResources.Project);
AddName(projectListItem.DisplayText);
}
private void BuildReference(ReferenceListItem referenceListItem)
{
AddText(ServicesVSResources.Assembly);
AddName(referenceListItem.DisplayText);
AddEndDeclaration();
AddIndent();
if (referenceListItem.MetadataReference is PortableExecutableReference portableExecutableReference)
{
AddText(portableExecutableReference.FilePath);
}
}
private void BuildNamespace(NamespaceListItem namespaceListItem, _VSOBJDESCOPTIONS options)
{
var compilation = GetCompilation();
if (compilation == null)
{
return;
}
var namespaceSymbol = namespaceListItem.ResolveTypedSymbol(compilation);
if (namespaceSymbol == null)
{
return;
}
BuildNamespaceDeclaration(namespaceSymbol, options);
AddEndDeclaration();
BuildMemberOf(namespaceSymbol.ContainingAssembly);
}
private void BuildType(TypeListItem typeListItem, _VSOBJDESCOPTIONS options)
{
var compilation = GetCompilation();
if (compilation == null)
{
return;
}
var symbol = typeListItem.ResolveTypedSymbol(compilation);
if (symbol == null)
{
return;
}
if (symbol.TypeKind == TypeKind.Delegate)
{
BuildDelegateDeclaration(symbol, options);
}
else
{
BuildTypeDeclaration(symbol, options);
}
AddEndDeclaration();
BuildMemberOf(symbol.ContainingNamespace);
BuildXmlDocumentation(symbol, compilation);
}
private void BuildMember(MemberListItem memberListItem, _VSOBJDESCOPTIONS options)
{
var compilation = GetCompilation();
if (compilation == null)
{
return;
}
var symbol = memberListItem.ResolveTypedSymbol(compilation);
if (symbol == null)
{
return;
}
switch (symbol.Kind)
{
case SymbolKind.Method:
BuildMethodDeclaration((IMethodSymbol)symbol, options);
break;
case SymbolKind.Field:
BuildFieldDeclaration((IFieldSymbol)symbol, options);
break;
case SymbolKind.Property:
BuildPropertyDeclaration((IPropertySymbol)symbol, options);
break;
case SymbolKind.Event:
BuildEventDeclaration((IEventSymbol)symbol, options);
break;
default:
Debug.Fail("Unsupported member kind: " + symbol.Kind.ToString());
return;
}
AddEndDeclaration();
BuildMemberOf(symbol.ContainingType);
BuildXmlDocumentation(symbol, compilation);
}
protected abstract void BuildNamespaceDeclaration(INamespaceSymbol namespaceSymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildDelegateDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildTypeDeclaration(INamedTypeSymbol typeSymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildMethodDeclaration(IMethodSymbol methodSymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildFieldDeclaration(IFieldSymbol fieldSymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildPropertyDeclaration(IPropertySymbol propertySymbol, _VSOBJDESCOPTIONS options);
protected abstract void BuildEventDeclaration(IEventSymbol eventSymbol, _VSOBJDESCOPTIONS options);
private void BuildMemberOf(ISymbol containingSymbol)
{
if (containingSymbol is INamespaceSymbol &&
((INamespaceSymbol)containingSymbol).IsGlobalNamespace)
{
containingSymbol = containingSymbol.ContainingAssembly;
}
var memberOfText = ServicesVSResources.Member_of_0;
const string specifier = "{0}";
var index = memberOfText.IndexOf(specifier, StringComparison.Ordinal);
if (index < 0)
{
Debug.Fail("MemberOf string resource is incorrect.");
return;
}
var left = memberOfText.Substring(0, index);
var right = memberOfText.Substring(index + specifier.Length);
AddIndent();
AddText(left);
if (containingSymbol is IAssemblySymbol assemblySymbol)
{
AddAssemblyLink(assemblySymbol);
}
else if (containingSymbol is ITypeSymbol typeSymbol)
{
AddTypeLink(typeSymbol, LinkFlags.SplitNamespaceAndType | LinkFlags.ExpandPredefinedTypes);
}
else if (containingSymbol is INamespaceSymbol namespaceSymbol)
{
AddNamespaceLink(namespaceSymbol);
}
AddText(right);
AddEndDeclaration();
}
private void BuildXmlDocumentation(ISymbol symbol, Compilation compilation)
{
var documentationComment = symbol.GetDocumentationComment(compilation, expandIncludes: true, expandInheritdoc: true, cancellationToken: CancellationToken.None);
if (documentationComment == null)
{
return;
}
var formattingService = _project.LanguageServices.GetService<IDocumentationCommentFormattingService>();
if (formattingService == null)
{
return;
}
var emittedDocs = false;
if (documentationComment.SummaryText != null)
{
AddLineBreak();
AddName(ServicesVSResources.Summary_colon);
AddLineBreak();
AddText(formattingService.Format(documentationComment.SummaryText, compilation));
emittedDocs = true;
}
if (documentationComment.TypeParameterNames.Length > 0)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Type_Parameters_colon);
foreach (var typeParameterName in documentationComment.TypeParameterNames)
{
AddLineBreak();
var typeParameterText = documentationComment.GetTypeParameterText(typeParameterName);
if (typeParameterText != null)
{
AddParam(typeParameterName);
AddText(": ");
AddText(formattingService.Format(typeParameterText, compilation));
emittedDocs = true;
}
}
}
if (documentationComment.ParameterNames.Length > 0)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Parameters_colon1);
foreach (var parameterName in documentationComment.ParameterNames)
{
AddLineBreak();
var parameterText = documentationComment.GetParameterText(parameterName);
if (parameterText != null)
{
AddParam(parameterName);
AddText(": ");
AddText(formattingService.Format(parameterText, compilation));
emittedDocs = true;
}
}
}
if (ShowReturnsDocumentation(symbol) && documentationComment.ReturnsText != null)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Returns_colon);
AddLineBreak();
AddText(formattingService.Format(documentationComment.ReturnsText, compilation));
emittedDocs = true;
}
if (ShowValueDocumentation(symbol) && documentationComment.ValueText != null)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Value_colon);
AddLineBreak();
AddText(formattingService.Format(documentationComment.ValueText, compilation));
emittedDocs = true;
}
if (documentationComment.RemarksText != null)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Remarks_colon);
AddLineBreak();
AddText(formattingService.Format(documentationComment.RemarksText, compilation));
emittedDocs = true;
}
if (documentationComment.ExceptionTypes.Length > 0)
{
if (emittedDocs)
{
AddLineBreak();
}
AddLineBreak();
AddName(ServicesVSResources.Exceptions_colon);
foreach (var exceptionType in documentationComment.ExceptionTypes)
{
if (DocumentationCommentId.GetFirstSymbolForDeclarationId(exceptionType, compilation) is INamedTypeSymbol exceptionTypeSymbol)
{
AddLineBreak();
var exceptionTexts = documentationComment.GetExceptionTexts(exceptionType);
if (exceptionTexts.Length == 0)
{
AddTypeLink(exceptionTypeSymbol, LinkFlags.None);
}
else
{
foreach (var exceptionText in exceptionTexts)
{
AddTypeLink(exceptionTypeSymbol, LinkFlags.None);
AddText(": ");
AddText(formattingService.Format(exceptionText, compilation));
}
}
}
}
}
}
private bool ShowReturnsDocumentation(ISymbol symbol)
{
return (symbol.Kind == SymbolKind.NamedType && ((INamedTypeSymbol)symbol).TypeKind == TypeKind.Delegate)
|| symbol.Kind == SymbolKind.Method
|| symbol.Kind == SymbolKind.Property;
}
private bool ShowValueDocumentation(ISymbol symbol)
{
// <returns> is often used in places where <value> was originally intended. Allow either to be used in
// documentation comments since they are not likely to be used together and it's not clear which one a
// particular code base will be using more often.
return ShowReturnsDocumentation(symbol);
}
internal bool TryBuild(_VSOBJDESCOPTIONS options)
{
switch (_listItem)
{
case ProjectListItem projectListItem:
BuildProject(projectListItem);
return true;
case ReferenceListItem referenceListItem:
BuildReference(referenceListItem);
return true;
case NamespaceListItem namespaceListItem:
BuildNamespace(namespaceListItem, options);
return true;
case TypeListItem typeListItem:
BuildType(typeListItem, options);
return true;
case MemberListItem memberListItem:
BuildMember(memberListItem, options);
return true;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Scripting/Core/Hosting/AssemblyLoader/MetadataShadowCopyProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Implements shadow-copying metadata file cache.
/// </summary>
public sealed class MetadataShadowCopyProvider : IDisposable
{
private readonly CultureInfo _documentationCommentsCulture;
// normalized absolute path
private readonly string _baseDirectory;
// Normalized absolute path to a directory where assemblies are copied. Must contain nothing but shadow-copied assemblies.
// Internal for testing.
internal string ShadowCopyDirectory;
// normalized absolute paths
private readonly ImmutableArray<string> _noShadowCopyDirectories;
private struct CacheEntry<TPublic>
{
public readonly TPublic Public;
public readonly Metadata Private;
public CacheEntry(TPublic @public, Metadata @private)
{
Debug.Assert(@public != null);
Debug.Assert(@private != null);
Public = @public;
Private = @private;
}
}
// Cache for files that are shadow-copied:
// (original path, last write timestamp) -> (public shadow copy, private metadata instance that owns the PE image)
private readonly Dictionary<FileKey, CacheEntry<MetadataShadowCopy>> _shadowCopies = new Dictionary<FileKey, CacheEntry<MetadataShadowCopy>>();
// Cache for files that are not shadow-copied:
// (path, last write timestamp) -> (public metadata, private metadata instance that owns the PE image)
private readonly Dictionary<FileKey, CacheEntry<Metadata>> _noShadowCopyCache = new Dictionary<FileKey, CacheEntry<Metadata>>();
// files that should not be copied:
private HashSet<string> _lazySuppressedFiles;
private object Guard => _shadowCopies;
/// <summary>
/// Creates an instance of <see cref="MetadataShadowCopyProvider"/>.
/// </summary>
/// <param name="directory">The directory to use to store file copies.</param>
/// <param name="noShadowCopyDirectories">Directories to exclude from shadow-copying.</param>
/// <param name="documentationCommentsCulture">Culture of documentation comments to copy. If not specified no doc comment files are going to be copied.</param>
/// <exception cref="ArgumentNullException"><paramref name="directory"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="directory"/> is not an absolute path.</exception>
public MetadataShadowCopyProvider(string directory = null, IEnumerable<string> noShadowCopyDirectories = null, CultureInfo documentationCommentsCulture = null)
{
if (directory != null)
{
RequireAbsolutePath(directory, nameof(directory));
try
{
_baseDirectory = FileUtilities.NormalizeDirectoryPath(directory);
}
catch (Exception e)
{
throw new ArgumentException(e.Message, nameof(directory));
}
}
else
{
_baseDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
}
if (noShadowCopyDirectories != null)
{
try
{
_noShadowCopyDirectories = ImmutableArray.CreateRange(noShadowCopyDirectories.Select(FileUtilities.NormalizeDirectoryPath));
}
catch (Exception e)
{
throw new ArgumentException(e.Message, nameof(noShadowCopyDirectories));
}
}
else
{
_noShadowCopyDirectories = ImmutableArray<string>.Empty;
}
_documentationCommentsCulture = documentationCommentsCulture;
}
private static void RequireAbsolutePath(string path, string argumentName)
{
if (path == null)
{
throw new ArgumentNullException(argumentName);
}
if (!PathUtilities.IsAbsolute(path))
{
throw new ArgumentException(ScriptingResources.AbsolutePathExpected, argumentName);
}
}
/// <summary>
/// Determine whether given path is under the shadow-copy directory managed by this shadow-copy provider.
/// </summary>
/// <param name="fullPath">Absolute path.</param>
/// <exception cref="ArgumentNullException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not an absolute path.</exception>
public bool IsShadowCopy(string fullPath)
{
RequireAbsolutePath(fullPath, nameof(fullPath));
string directory = ShadowCopyDirectory;
if (directory == null)
{
return false;
}
string normalizedPath;
try
{
normalizedPath = FileUtilities.NormalizeDirectoryPath(fullPath);
}
catch
{
return false;
}
return normalizedPath.StartsWith(directory, StringComparison.OrdinalIgnoreCase);
}
~MetadataShadowCopyProvider()
{
DisposeShadowCopies();
DeleteShadowCopyDirectory();
}
/// <summary>
/// Clears shadow-copy cache, disposes all allocated metadata, and attempts to delete copied files.
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
lock (Guard)
{
DisposeShadowCopies();
_shadowCopies.Clear();
}
DeleteShadowCopyDirectory();
}
private void DisposeShadowCopies()
{
foreach (var entry in _shadowCopies.Values)
{
// metadata file handles have been disposed already, but the xml doc file handle hasn't:
entry.Public.DisposeFileHandles();
// dispose metadata images:
entry.Private.Dispose();
}
}
private void DeleteShadowCopyDirectory()
{
var directory = ShadowCopyDirectory;
if (Directory.Exists(directory))
{
try
{
// First, strip the read-only bit off of any files.
var directoryInfo = new DirectoryInfo(directory);
foreach (var fileInfo in directoryInfo.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories))
{
StripReadOnlyAttributeFromFile(fileInfo);
}
// Second, delete everything.
Directory.Delete(directory, recursive: true);
}
catch
{
}
}
}
private static void StripReadOnlyAttributeFromFile(FileInfo fileInfo)
{
try
{
if (fileInfo.IsReadOnly)
{
fileInfo.IsReadOnly = false;
}
}
catch
{
// There are many reasons this could fail. Just ignore it and move on.
}
}
/// <summary>
/// Gets or creates metadata for specified file path.
/// </summary>
/// <param name="fullPath">Full path to an assembly manifest module file or a standalone module file.</param>
/// <param name="kind">Metadata kind (assembly or module).</param>
/// <returns>Metadata for the specified file.</returns>
/// <exception cref="IOException">Error reading file <paramref name="fullPath"/>. See <see cref="Exception.InnerException"/> for details.</exception>
public Metadata GetMetadata(string fullPath, MetadataImageKind kind)
{
if (NeedsShadowCopy(fullPath))
{
return GetMetadataShadowCopyNoCheck(fullPath, kind).Metadata;
}
FileKey key = FileKey.Create(fullPath);
lock (Guard)
{
CacheEntry<Metadata> existing;
if (_noShadowCopyCache.TryGetValue(key, out existing))
{
return existing.Public;
}
}
Metadata newMetadata;
if (kind == MetadataImageKind.Assembly)
{
newMetadata = AssemblyMetadata.CreateFromFile(fullPath);
}
else
{
newMetadata = ModuleMetadata.CreateFromFile(fullPath);
}
// the files are locked (memory mapped) now
key = FileKey.Create(fullPath);
lock (Guard)
{
CacheEntry<Metadata> existing;
if (_noShadowCopyCache.TryGetValue(key, out existing))
{
newMetadata.Dispose();
return existing.Public;
}
Metadata publicMetadata = newMetadata.Copy();
_noShadowCopyCache.Add(key, new CacheEntry<Metadata>(publicMetadata, newMetadata));
return publicMetadata;
}
}
/// <summary>
/// Gets or creates a copy of specified assembly or standalone module.
/// </summary>
/// <param name="fullPath">Full path to an assembly manifest module file or a standalone module file.</param>
/// <param name="kind">Metadata kind (assembly or module).</param>
/// <returns>
/// Copy of the specified file, or null if the file doesn't need a copy (<see cref="NeedsShadowCopy"/>).
/// Returns the same object if called multiple times with the same path.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not an absolute path.</exception>
/// <exception cref="IOException">Error reading file <paramref name="fullPath"/>. See <see cref="Exception.InnerException"/> for details.</exception>
public MetadataShadowCopy GetMetadataShadowCopy(string fullPath, MetadataImageKind kind)
{
return NeedsShadowCopy(fullPath) ? GetMetadataShadowCopyNoCheck(fullPath, kind) : null;
}
private MetadataShadowCopy GetMetadataShadowCopyNoCheck(string fullPath, MetadataImageKind kind)
{
if (kind < MetadataImageKind.Assembly || kind > MetadataImageKind.Module)
{
throw new ArgumentOutOfRangeException(nameof(kind));
}
FileKey key = FileKey.Create(fullPath);
lock (Guard)
{
CacheEntry<MetadataShadowCopy> existing;
if (CopyExistsOrIsSuppressed(key, out existing))
{
return existing.Public;
}
}
CacheEntry<MetadataShadowCopy> newCopy = CreateMetadataShadowCopy(fullPath, kind);
// last-write timestamp is copied from the original file at the time the snapshot was made:
bool fault = true;
try
{
key = new FileKey(fullPath, FileUtilities.GetFileTimeStamp(newCopy.Public.PrimaryModule.FullPath));
fault = false;
}
finally
{
if (fault)
{
newCopy.Private.Dispose();
}
}
lock (Guard)
{
CacheEntry<MetadataShadowCopy> existing;
if (CopyExistsOrIsSuppressed(key, out existing))
{
newCopy.Private.Dispose();
return existing.Public;
}
_shadowCopies.Add(key, newCopy);
}
return newCopy.Public;
}
private bool CopyExistsOrIsSuppressed(FileKey key, out CacheEntry<MetadataShadowCopy> existing)
{
if (_lazySuppressedFiles != null && _lazySuppressedFiles.Contains(key.FullPath))
{
existing = default(CacheEntry<MetadataShadowCopy>);
return true;
}
return _shadowCopies.TryGetValue(key, out existing);
}
/// <summary>
/// Suppresses shadow-copying of specified path.
/// </summary>
/// <param name="originalPath">Full path.</param>
/// <exception cref="ArgumentNullException"><paramref name="originalPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="originalPath"/> is not an absolute path.</exception>
/// <remarks>
/// Doesn't affect files that have already been shadow-copied.
/// </remarks>
public void SuppressShadowCopy(string originalPath)
{
RequireAbsolutePath(originalPath, nameof(originalPath));
lock (Guard)
{
if (_lazySuppressedFiles == null)
{
_lazySuppressedFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
_lazySuppressedFiles.Add(originalPath);
}
}
/// <summary>
/// Determines whether given file is a candidate for shadow-copy.
/// </summary>
/// <param name="fullPath">An absolute path.</param>
/// <returns>True if the shadow-copy policy applies to the specified path.</returns>
/// <exception cref="NullReferenceException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not absolute.</exception>
public bool NeedsShadowCopy(string fullPath)
{
RequireAbsolutePath(fullPath, nameof(fullPath));
string directory = Path.GetDirectoryName(fullPath);
// do not shadow-copy shadow-copies:
string referencesDir = ShadowCopyDirectory;
if (referencesDir != null && directory.StartsWith(referencesDir, StringComparison.Ordinal))
{
return false;
}
return !_noShadowCopyDirectories.Any(dir => directory.StartsWith(dir, StringComparison.Ordinal));
}
private CacheEntry<MetadataShadowCopy> CreateMetadataShadowCopy(string originalPath, MetadataImageKind kind)
{
int attempts = 10;
while (true)
{
try
{
if (ShadowCopyDirectory == null)
{
ShadowCopyDirectory = CreateUniqueDirectory(_baseDirectory);
}
// Create directory for the assembly.
// If the assembly has any modules they have to be copied to the same directory
// and have the same names as specified in metadata.
string assemblyCopyDir = CreateUniqueDirectory(ShadowCopyDirectory);
string shadowCopyPath = Path.Combine(assemblyCopyDir, Path.GetFileName(originalPath));
FileShadowCopy documentationFileCopy = TryCopyDocumentationFile(originalPath, assemblyCopyDir, _documentationCommentsCulture);
var manifestModuleCopyStream = CopyFile(originalPath, shadowCopyPath);
var manifestModuleCopy = new FileShadowCopy(manifestModuleCopyStream, originalPath, shadowCopyPath);
Metadata privateMetadata;
if (kind == MetadataImageKind.Assembly)
{
privateMetadata = CreateAssemblyMetadata(manifestModuleCopyStream, originalPath, shadowCopyPath);
}
else
{
privateMetadata = CreateModuleMetadata(manifestModuleCopyStream);
}
var publicMetadata = privateMetadata.Copy();
return new CacheEntry<MetadataShadowCopy>(new MetadataShadowCopy(manifestModuleCopy, documentationFileCopy, publicMetadata), privateMetadata);
}
catch (DirectoryNotFoundException)
{
// the shadow copy directory has been deleted - try to copy all files again
if (!Directory.Exists(ShadowCopyDirectory))
{
ShadowCopyDirectory = null;
if (attempts-- > 0)
{
continue;
}
}
throw;
}
}
}
private AssemblyMetadata CreateAssemblyMetadata(FileStream manifestModuleCopyStream, string originalPath, string shadowCopyPath)
{
// We don't need to use the global metadata cache here since the shadow copy
// won't change and is private to us - only users of the same shadow copy provider see it.
ImmutableArray<ModuleMetadata>.Builder moduleBuilder = null;
bool fault = true;
ModuleMetadata manifestModule = null;
try
{
manifestModule = CreateModuleMetadata(manifestModuleCopyStream);
string originalDirectory = null, shadowCopyDirectory = null;
foreach (string moduleName in manifestModule.GetModuleNames())
{
if (moduleBuilder == null)
{
moduleBuilder = ImmutableArray.CreateBuilder<ModuleMetadata>();
moduleBuilder.Add(manifestModule);
originalDirectory = Path.GetDirectoryName(originalPath);
shadowCopyDirectory = Path.GetDirectoryName(shadowCopyPath);
}
FileStream moduleCopyStream = CopyFile(
originalPath: Path.Combine(originalDirectory, moduleName),
shadowCopyPath: Path.Combine(shadowCopyDirectory, moduleName));
moduleBuilder.Add(CreateModuleMetadata(moduleCopyStream));
}
var modules = (moduleBuilder != null) ? moduleBuilder.ToImmutable() : ImmutableArray.Create(manifestModule);
fault = false;
return AssemblyMetadata.Create(modules);
}
finally
{
if (fault)
{
if (manifestModule != null)
{
manifestModule.Dispose();
}
if (moduleBuilder != null)
{
for (int i = 1; i < moduleBuilder.Count; i++)
{
moduleBuilder[i].Dispose();
}
}
}
}
}
private static ModuleMetadata CreateModuleMetadata(FileStream stream)
{
// The Stream is held by the ModuleMetadata to read metadata on demand.
// We hand off the responsibility for closing the stream to the metadata object.
return ModuleMetadata.CreateFromStream(stream, leaveOpen: false);
}
private string CreateUniqueDirectory(string basePath)
{
int attempts = 10;
while (true)
{
string dir = Path.Combine(basePath, Guid.NewGuid().ToString());
if (File.Exists(dir) || Directory.Exists(dir))
{
// try a different name (guid):
continue;
}
try
{
Directory.CreateDirectory(dir);
return dir;
}
catch (IOException)
{
// Some other process might have created a file of the same name after we checked for its existence.
if (File.Exists(dir))
{
continue;
}
// This file might also have been deleted by now. So try again for a while and then give up.
if (--attempts == 0)
{
throw;
}
}
}
}
private static FileShadowCopy TryCopyDocumentationFile(string originalAssemblyPath, string assemblyCopyDirectory, CultureInfo docCultureOpt)
{
// Note: Doc comments are not supported for netmodules.
string assemblyDirectory = Path.GetDirectoryName(originalAssemblyPath);
string assemblyFileName = Path.GetFileName(originalAssemblyPath);
string xmlSubdirectory;
string xmlFileName;
if (docCultureOpt == null ||
!TryFindCollocatedDocumentationFile(assemblyDirectory, assemblyFileName, docCultureOpt, out xmlSubdirectory, out xmlFileName))
{
return null;
}
if (!xmlSubdirectory.IsEmpty())
{
try
{
Directory.CreateDirectory(Path.Combine(assemblyCopyDirectory, xmlSubdirectory));
}
catch
{
return null;
}
}
string xmlCopyPath = Path.Combine(assemblyCopyDirectory, xmlSubdirectory, xmlFileName);
string xmlOriginalPath = Path.Combine(assemblyDirectory, xmlSubdirectory, xmlFileName);
var xmlStream = CopyFile(xmlOriginalPath, xmlCopyPath, fileMayNotExist: true);
return (xmlStream != null) ? new FileShadowCopy(xmlStream, xmlOriginalPath, xmlCopyPath) : null;
}
private static bool TryFindCollocatedDocumentationFile(
string assemblyDirectory,
string assemblyFileName,
CultureInfo culture,
out string docSubdirectory,
out string docFileName)
{
Debug.Assert(assemblyDirectory != null);
Debug.Assert(assemblyFileName != null);
Debug.Assert(culture != null);
// 1. Look in subdirectories based on the current culture
docFileName = Path.ChangeExtension(assemblyFileName, ".xml");
while (culture != CultureInfo.InvariantCulture)
{
docSubdirectory = culture.Name;
if (File.Exists(Path.Combine(assemblyDirectory, docSubdirectory, docFileName)))
{
return true;
}
culture = culture.Parent;
}
// 2. Look in the same directory as the assembly itself
docSubdirectory = string.Empty;
if (File.Exists(Path.Combine(assemblyDirectory, docFileName)))
{
return true;
}
docFileName = null;
return false;
}
private static FileStream CopyFile(string originalPath, string shadowCopyPath, bool fileMayNotExist = false)
{
try
{
File.Copy(originalPath, shadowCopyPath, overwrite: true);
StripReadOnlyAttributeFromFile(new FileInfo(shadowCopyPath));
return new FileStream(shadowCopyPath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (Exception e) when (fileMayNotExist && (e is FileNotFoundException || e is DirectoryNotFoundException))
{
return null;
}
}
#region Test hooks
// for testing only
internal int CacheSize
{
get { return _shadowCopies.Count; }
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
/// <summary>
/// Implements shadow-copying metadata file cache.
/// </summary>
public sealed class MetadataShadowCopyProvider : IDisposable
{
private readonly CultureInfo _documentationCommentsCulture;
// normalized absolute path
private readonly string _baseDirectory;
// Normalized absolute path to a directory where assemblies are copied. Must contain nothing but shadow-copied assemblies.
// Internal for testing.
internal string ShadowCopyDirectory;
// normalized absolute paths
private readonly ImmutableArray<string> _noShadowCopyDirectories;
private struct CacheEntry<TPublic>
{
public readonly TPublic Public;
public readonly Metadata Private;
public CacheEntry(TPublic @public, Metadata @private)
{
Debug.Assert(@public != null);
Debug.Assert(@private != null);
Public = @public;
Private = @private;
}
}
// Cache for files that are shadow-copied:
// (original path, last write timestamp) -> (public shadow copy, private metadata instance that owns the PE image)
private readonly Dictionary<FileKey, CacheEntry<MetadataShadowCopy>> _shadowCopies = new Dictionary<FileKey, CacheEntry<MetadataShadowCopy>>();
// Cache for files that are not shadow-copied:
// (path, last write timestamp) -> (public metadata, private metadata instance that owns the PE image)
private readonly Dictionary<FileKey, CacheEntry<Metadata>> _noShadowCopyCache = new Dictionary<FileKey, CacheEntry<Metadata>>();
// files that should not be copied:
private HashSet<string> _lazySuppressedFiles;
private object Guard => _shadowCopies;
/// <summary>
/// Creates an instance of <see cref="MetadataShadowCopyProvider"/>.
/// </summary>
/// <param name="directory">The directory to use to store file copies.</param>
/// <param name="noShadowCopyDirectories">Directories to exclude from shadow-copying.</param>
/// <param name="documentationCommentsCulture">Culture of documentation comments to copy. If not specified no doc comment files are going to be copied.</param>
/// <exception cref="ArgumentNullException"><paramref name="directory"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="directory"/> is not an absolute path.</exception>
public MetadataShadowCopyProvider(string directory = null, IEnumerable<string> noShadowCopyDirectories = null, CultureInfo documentationCommentsCulture = null)
{
if (directory != null)
{
RequireAbsolutePath(directory, nameof(directory));
try
{
_baseDirectory = FileUtilities.NormalizeDirectoryPath(directory);
}
catch (Exception e)
{
throw new ArgumentException(e.Message, nameof(directory));
}
}
else
{
_baseDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
}
if (noShadowCopyDirectories != null)
{
try
{
_noShadowCopyDirectories = ImmutableArray.CreateRange(noShadowCopyDirectories.Select(FileUtilities.NormalizeDirectoryPath));
}
catch (Exception e)
{
throw new ArgumentException(e.Message, nameof(noShadowCopyDirectories));
}
}
else
{
_noShadowCopyDirectories = ImmutableArray<string>.Empty;
}
_documentationCommentsCulture = documentationCommentsCulture;
}
private static void RequireAbsolutePath(string path, string argumentName)
{
if (path == null)
{
throw new ArgumentNullException(argumentName);
}
if (!PathUtilities.IsAbsolute(path))
{
throw new ArgumentException(ScriptingResources.AbsolutePathExpected, argumentName);
}
}
/// <summary>
/// Determine whether given path is under the shadow-copy directory managed by this shadow-copy provider.
/// </summary>
/// <param name="fullPath">Absolute path.</param>
/// <exception cref="ArgumentNullException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not an absolute path.</exception>
public bool IsShadowCopy(string fullPath)
{
RequireAbsolutePath(fullPath, nameof(fullPath));
string directory = ShadowCopyDirectory;
if (directory == null)
{
return false;
}
string normalizedPath;
try
{
normalizedPath = FileUtilities.NormalizeDirectoryPath(fullPath);
}
catch
{
return false;
}
return normalizedPath.StartsWith(directory, StringComparison.OrdinalIgnoreCase);
}
~MetadataShadowCopyProvider()
{
DisposeShadowCopies();
DeleteShadowCopyDirectory();
}
/// <summary>
/// Clears shadow-copy cache, disposes all allocated metadata, and attempts to delete copied files.
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
lock (Guard)
{
DisposeShadowCopies();
_shadowCopies.Clear();
}
DeleteShadowCopyDirectory();
}
private void DisposeShadowCopies()
{
foreach (var entry in _shadowCopies.Values)
{
// metadata file handles have been disposed already, but the xml doc file handle hasn't:
entry.Public.DisposeFileHandles();
// dispose metadata images:
entry.Private.Dispose();
}
}
private void DeleteShadowCopyDirectory()
{
var directory = ShadowCopyDirectory;
if (Directory.Exists(directory))
{
try
{
// First, strip the read-only bit off of any files.
var directoryInfo = new DirectoryInfo(directory);
foreach (var fileInfo in directoryInfo.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories))
{
StripReadOnlyAttributeFromFile(fileInfo);
}
// Second, delete everything.
Directory.Delete(directory, recursive: true);
}
catch
{
}
}
}
private static void StripReadOnlyAttributeFromFile(FileInfo fileInfo)
{
try
{
if (fileInfo.IsReadOnly)
{
fileInfo.IsReadOnly = false;
}
}
catch
{
// There are many reasons this could fail. Just ignore it and move on.
}
}
/// <summary>
/// Gets or creates metadata for specified file path.
/// </summary>
/// <param name="fullPath">Full path to an assembly manifest module file or a standalone module file.</param>
/// <param name="kind">Metadata kind (assembly or module).</param>
/// <returns>Metadata for the specified file.</returns>
/// <exception cref="IOException">Error reading file <paramref name="fullPath"/>. See <see cref="Exception.InnerException"/> for details.</exception>
public Metadata GetMetadata(string fullPath, MetadataImageKind kind)
{
if (NeedsShadowCopy(fullPath))
{
return GetMetadataShadowCopyNoCheck(fullPath, kind).Metadata;
}
FileKey key = FileKey.Create(fullPath);
lock (Guard)
{
CacheEntry<Metadata> existing;
if (_noShadowCopyCache.TryGetValue(key, out existing))
{
return existing.Public;
}
}
Metadata newMetadata;
if (kind == MetadataImageKind.Assembly)
{
newMetadata = AssemblyMetadata.CreateFromFile(fullPath);
}
else
{
newMetadata = ModuleMetadata.CreateFromFile(fullPath);
}
// the files are locked (memory mapped) now
key = FileKey.Create(fullPath);
lock (Guard)
{
CacheEntry<Metadata> existing;
if (_noShadowCopyCache.TryGetValue(key, out existing))
{
newMetadata.Dispose();
return existing.Public;
}
Metadata publicMetadata = newMetadata.Copy();
_noShadowCopyCache.Add(key, new CacheEntry<Metadata>(publicMetadata, newMetadata));
return publicMetadata;
}
}
/// <summary>
/// Gets or creates a copy of specified assembly or standalone module.
/// </summary>
/// <param name="fullPath">Full path to an assembly manifest module file or a standalone module file.</param>
/// <param name="kind">Metadata kind (assembly or module).</param>
/// <returns>
/// Copy of the specified file, or null if the file doesn't need a copy (<see cref="NeedsShadowCopy"/>).
/// Returns the same object if called multiple times with the same path.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not an absolute path.</exception>
/// <exception cref="IOException">Error reading file <paramref name="fullPath"/>. See <see cref="Exception.InnerException"/> for details.</exception>
public MetadataShadowCopy GetMetadataShadowCopy(string fullPath, MetadataImageKind kind)
{
return NeedsShadowCopy(fullPath) ? GetMetadataShadowCopyNoCheck(fullPath, kind) : null;
}
private MetadataShadowCopy GetMetadataShadowCopyNoCheck(string fullPath, MetadataImageKind kind)
{
if (kind < MetadataImageKind.Assembly || kind > MetadataImageKind.Module)
{
throw new ArgumentOutOfRangeException(nameof(kind));
}
FileKey key = FileKey.Create(fullPath);
lock (Guard)
{
CacheEntry<MetadataShadowCopy> existing;
if (CopyExistsOrIsSuppressed(key, out existing))
{
return existing.Public;
}
}
CacheEntry<MetadataShadowCopy> newCopy = CreateMetadataShadowCopy(fullPath, kind);
// last-write timestamp is copied from the original file at the time the snapshot was made:
bool fault = true;
try
{
key = new FileKey(fullPath, FileUtilities.GetFileTimeStamp(newCopy.Public.PrimaryModule.FullPath));
fault = false;
}
finally
{
if (fault)
{
newCopy.Private.Dispose();
}
}
lock (Guard)
{
CacheEntry<MetadataShadowCopy> existing;
if (CopyExistsOrIsSuppressed(key, out existing))
{
newCopy.Private.Dispose();
return existing.Public;
}
_shadowCopies.Add(key, newCopy);
}
return newCopy.Public;
}
private bool CopyExistsOrIsSuppressed(FileKey key, out CacheEntry<MetadataShadowCopy> existing)
{
if (_lazySuppressedFiles != null && _lazySuppressedFiles.Contains(key.FullPath))
{
existing = default(CacheEntry<MetadataShadowCopy>);
return true;
}
return _shadowCopies.TryGetValue(key, out existing);
}
/// <summary>
/// Suppresses shadow-copying of specified path.
/// </summary>
/// <param name="originalPath">Full path.</param>
/// <exception cref="ArgumentNullException"><paramref name="originalPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="originalPath"/> is not an absolute path.</exception>
/// <remarks>
/// Doesn't affect files that have already been shadow-copied.
/// </remarks>
public void SuppressShadowCopy(string originalPath)
{
RequireAbsolutePath(originalPath, nameof(originalPath));
lock (Guard)
{
if (_lazySuppressedFiles == null)
{
_lazySuppressedFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
_lazySuppressedFiles.Add(originalPath);
}
}
/// <summary>
/// Determines whether given file is a candidate for shadow-copy.
/// </summary>
/// <param name="fullPath">An absolute path.</param>
/// <returns>True if the shadow-copy policy applies to the specified path.</returns>
/// <exception cref="NullReferenceException"><paramref name="fullPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="fullPath"/> is not absolute.</exception>
public bool NeedsShadowCopy(string fullPath)
{
RequireAbsolutePath(fullPath, nameof(fullPath));
string directory = Path.GetDirectoryName(fullPath);
// do not shadow-copy shadow-copies:
string referencesDir = ShadowCopyDirectory;
if (referencesDir != null && directory.StartsWith(referencesDir, StringComparison.Ordinal))
{
return false;
}
return !_noShadowCopyDirectories.Any(dir => directory.StartsWith(dir, StringComparison.Ordinal));
}
private CacheEntry<MetadataShadowCopy> CreateMetadataShadowCopy(string originalPath, MetadataImageKind kind)
{
int attempts = 10;
while (true)
{
try
{
if (ShadowCopyDirectory == null)
{
ShadowCopyDirectory = CreateUniqueDirectory(_baseDirectory);
}
// Create directory for the assembly.
// If the assembly has any modules they have to be copied to the same directory
// and have the same names as specified in metadata.
string assemblyCopyDir = CreateUniqueDirectory(ShadowCopyDirectory);
string shadowCopyPath = Path.Combine(assemblyCopyDir, Path.GetFileName(originalPath));
FileShadowCopy documentationFileCopy = TryCopyDocumentationFile(originalPath, assemblyCopyDir, _documentationCommentsCulture);
var manifestModuleCopyStream = CopyFile(originalPath, shadowCopyPath);
var manifestModuleCopy = new FileShadowCopy(manifestModuleCopyStream, originalPath, shadowCopyPath);
Metadata privateMetadata;
if (kind == MetadataImageKind.Assembly)
{
privateMetadata = CreateAssemblyMetadata(manifestModuleCopyStream, originalPath, shadowCopyPath);
}
else
{
privateMetadata = CreateModuleMetadata(manifestModuleCopyStream);
}
var publicMetadata = privateMetadata.Copy();
return new CacheEntry<MetadataShadowCopy>(new MetadataShadowCopy(manifestModuleCopy, documentationFileCopy, publicMetadata), privateMetadata);
}
catch (DirectoryNotFoundException)
{
// the shadow copy directory has been deleted - try to copy all files again
if (!Directory.Exists(ShadowCopyDirectory))
{
ShadowCopyDirectory = null;
if (attempts-- > 0)
{
continue;
}
}
throw;
}
}
}
private AssemblyMetadata CreateAssemblyMetadata(FileStream manifestModuleCopyStream, string originalPath, string shadowCopyPath)
{
// We don't need to use the global metadata cache here since the shadow copy
// won't change and is private to us - only users of the same shadow copy provider see it.
ImmutableArray<ModuleMetadata>.Builder moduleBuilder = null;
bool fault = true;
ModuleMetadata manifestModule = null;
try
{
manifestModule = CreateModuleMetadata(manifestModuleCopyStream);
string originalDirectory = null, shadowCopyDirectory = null;
foreach (string moduleName in manifestModule.GetModuleNames())
{
if (moduleBuilder == null)
{
moduleBuilder = ImmutableArray.CreateBuilder<ModuleMetadata>();
moduleBuilder.Add(manifestModule);
originalDirectory = Path.GetDirectoryName(originalPath);
shadowCopyDirectory = Path.GetDirectoryName(shadowCopyPath);
}
FileStream moduleCopyStream = CopyFile(
originalPath: Path.Combine(originalDirectory, moduleName),
shadowCopyPath: Path.Combine(shadowCopyDirectory, moduleName));
moduleBuilder.Add(CreateModuleMetadata(moduleCopyStream));
}
var modules = (moduleBuilder != null) ? moduleBuilder.ToImmutable() : ImmutableArray.Create(manifestModule);
fault = false;
return AssemblyMetadata.Create(modules);
}
finally
{
if (fault)
{
if (manifestModule != null)
{
manifestModule.Dispose();
}
if (moduleBuilder != null)
{
for (int i = 1; i < moduleBuilder.Count; i++)
{
moduleBuilder[i].Dispose();
}
}
}
}
}
private static ModuleMetadata CreateModuleMetadata(FileStream stream)
{
// The Stream is held by the ModuleMetadata to read metadata on demand.
// We hand off the responsibility for closing the stream to the metadata object.
return ModuleMetadata.CreateFromStream(stream, leaveOpen: false);
}
private string CreateUniqueDirectory(string basePath)
{
int attempts = 10;
while (true)
{
string dir = Path.Combine(basePath, Guid.NewGuid().ToString());
if (File.Exists(dir) || Directory.Exists(dir))
{
// try a different name (guid):
continue;
}
try
{
Directory.CreateDirectory(dir);
return dir;
}
catch (IOException)
{
// Some other process might have created a file of the same name after we checked for its existence.
if (File.Exists(dir))
{
continue;
}
// This file might also have been deleted by now. So try again for a while and then give up.
if (--attempts == 0)
{
throw;
}
}
}
}
private static FileShadowCopy TryCopyDocumentationFile(string originalAssemblyPath, string assemblyCopyDirectory, CultureInfo docCultureOpt)
{
// Note: Doc comments are not supported for netmodules.
string assemblyDirectory = Path.GetDirectoryName(originalAssemblyPath);
string assemblyFileName = Path.GetFileName(originalAssemblyPath);
string xmlSubdirectory;
string xmlFileName;
if (docCultureOpt == null ||
!TryFindCollocatedDocumentationFile(assemblyDirectory, assemblyFileName, docCultureOpt, out xmlSubdirectory, out xmlFileName))
{
return null;
}
if (!xmlSubdirectory.IsEmpty())
{
try
{
Directory.CreateDirectory(Path.Combine(assemblyCopyDirectory, xmlSubdirectory));
}
catch
{
return null;
}
}
string xmlCopyPath = Path.Combine(assemblyCopyDirectory, xmlSubdirectory, xmlFileName);
string xmlOriginalPath = Path.Combine(assemblyDirectory, xmlSubdirectory, xmlFileName);
var xmlStream = CopyFile(xmlOriginalPath, xmlCopyPath, fileMayNotExist: true);
return (xmlStream != null) ? new FileShadowCopy(xmlStream, xmlOriginalPath, xmlCopyPath) : null;
}
private static bool TryFindCollocatedDocumentationFile(
string assemblyDirectory,
string assemblyFileName,
CultureInfo culture,
out string docSubdirectory,
out string docFileName)
{
Debug.Assert(assemblyDirectory != null);
Debug.Assert(assemblyFileName != null);
Debug.Assert(culture != null);
// 1. Look in subdirectories based on the current culture
docFileName = Path.ChangeExtension(assemblyFileName, ".xml");
while (culture != CultureInfo.InvariantCulture)
{
docSubdirectory = culture.Name;
if (File.Exists(Path.Combine(assemblyDirectory, docSubdirectory, docFileName)))
{
return true;
}
culture = culture.Parent;
}
// 2. Look in the same directory as the assembly itself
docSubdirectory = string.Empty;
if (File.Exists(Path.Combine(assemblyDirectory, docFileName)))
{
return true;
}
docFileName = null;
return false;
}
private static FileStream CopyFile(string originalPath, string shadowCopyPath, bool fileMayNotExist = false)
{
try
{
File.Copy(originalPath, shadowCopyPath, overwrite: true);
StripReadOnlyAttributeFromFile(new FileInfo(shadowCopyPath));
return new FileStream(shadowCopyPath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (Exception e) when (fileMayNotExist && (e is FileNotFoundException || e is DirectoryNotFoundException))
{
return null;
}
}
#region Test hooks
// for testing only
internal int CacheSize
{
get { return _shadowCopies.Count; }
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/EditorFeatures/TestUtilities/TestOptionsServiceWithSharedGlobalOptionsServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
/// <summary>
/// <see cref="IOptionService"/> factory that allows creating multiple test workspaces with shared <see cref="IGlobalOptionService"/>.
/// This mimics the real product scenarios where all workspaces share the same global options service.
/// Note that majority of unit tests use <see cref="TestOptionsServiceFactory"/> instead of this factory to ensure options isolation between each test.
/// </summary>
[ExportWorkspaceServiceFactory(typeof(IOptionService), ServiceLayer.Test), Shared, PartNotDiscoverable]
internal class TestOptionsServiceWithSharedGlobalOptionsServiceFactory : IWorkspaceServiceFactory
{
private readonly IGlobalOptionService _globalOptionService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestOptionsServiceWithSharedGlobalOptionsServiceFactory(
[Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService,
[ImportMany] IEnumerable<Lazy<IOptionProvider, LanguageMetadata>> optionProviders)
{
_globalOptionService = new GlobalOptionService(workspaceThreadingService, optionProviders.ToImmutableArray(), SpecializedCollections.EmptyEnumerable<Lazy<IOptionPersisterProvider>>());
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
// give out new option service per workspace, but share the global option service
return new OptionServiceFactory.OptionService(_globalOptionService, workspaceServices);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests
{
/// <summary>
/// <see cref="IOptionService"/> factory that allows creating multiple test workspaces with shared <see cref="IGlobalOptionService"/>.
/// This mimics the real product scenarios where all workspaces share the same global options service.
/// Note that majority of unit tests use <see cref="TestOptionsServiceFactory"/> instead of this factory to ensure options isolation between each test.
/// </summary>
[ExportWorkspaceServiceFactory(typeof(IOptionService), ServiceLayer.Test), Shared, PartNotDiscoverable]
internal class TestOptionsServiceWithSharedGlobalOptionsServiceFactory : IWorkspaceServiceFactory
{
private readonly IGlobalOptionService _globalOptionService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestOptionsServiceWithSharedGlobalOptionsServiceFactory(
[Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService,
[ImportMany] IEnumerable<Lazy<IOptionProvider, LanguageMetadata>> optionProviders)
{
_globalOptionService = new GlobalOptionService(workspaceThreadingService, optionProviders.ToImmutableArray(), SpecializedCollections.EmptyEnumerable<Lazy<IOptionPersisterProvider>>());
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
// give out new option service per workspace, but share the global option service
return new OptionServiceFactory.OptionService(_globalOptionService, workspaceServices);
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceEnumConstantSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a constant field of an enum.
/// </summary>
internal abstract class SourceEnumConstantSymbol : SourceFieldSymbolWithSyntaxReference
{
public static SourceEnumConstantSymbol CreateExplicitValuedConstant(
SourceMemberContainerTypeSymbol containingEnum,
EnumMemberDeclarationSyntax syntax,
BindingDiagnosticBag diagnostics)
{
var initializer = syntax.EqualsValue;
Debug.Assert(initializer != null);
return new ExplicitValuedEnumConstantSymbol(containingEnum, syntax, initializer, diagnostics);
}
public static SourceEnumConstantSymbol CreateImplicitValuedConstant(
SourceMemberContainerTypeSymbol containingEnum,
EnumMemberDeclarationSyntax syntax,
SourceEnumConstantSymbol otherConstant,
int otherConstantOffset,
BindingDiagnosticBag diagnostics)
{
if ((object)otherConstant == null)
{
Debug.Assert(otherConstantOffset == 0);
return new ZeroValuedEnumConstantSymbol(containingEnum, syntax, diagnostics);
}
else
{
Debug.Assert(otherConstantOffset > 0);
return new ImplicitValuedEnumConstantSymbol(containingEnum, syntax, otherConstant, (uint)otherConstantOffset, diagnostics);
}
}
protected SourceEnumConstantSymbol(SourceMemberContainerTypeSymbol containingEnum, EnumMemberDeclarationSyntax syntax, BindingDiagnosticBag diagnostics)
: base(containingEnum, syntax.Identifier.ValueText, syntax.GetReference(), syntax.Identifier.GetLocation())
{
if (this.Name == WellKnownMemberNames.EnumBackingFieldName)
{
diagnostics.Add(ErrorCode.ERR_ReservedEnumerator, this.ErrorLocation, WellKnownMemberNames.EnumBackingFieldName);
}
}
internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound)
{
return TypeWithAnnotations.Create(this.ContainingType);
}
public override Symbol AssociatedSymbol
{
get
{
return null;
}
}
protected sealed override DeclarationModifiers Modifiers
{
get
{
return DeclarationModifiers.Const | DeclarationModifiers.Static | DeclarationModifiers.Public;
}
}
public new EnumMemberDeclarationSyntax SyntaxNode
{
get
{
return (EnumMemberDeclarationSyntax)base.SyntaxNode;
}
}
protected override SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList
{
get
{
if (this.containingType.AnyMemberHasAttributes)
{
return this.SyntaxNode.AttributeLists;
}
return default(SyntaxList<AttributeListSyntax>);
}
}
internal sealed override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var incompletePart = state.NextIncompletePart;
switch (incompletePart)
{
case CompletionPart.Attributes:
GetAttributes();
break;
case CompletionPart.Type:
state.NotePartComplete(CompletionPart.Type);
break;
case CompletionPart.FixedSize:
Debug.Assert(!this.IsFixedSizeBuffer);
state.NotePartComplete(CompletionPart.FixedSize);
break;
case CompletionPart.ConstantValue:
GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false);
break;
case CompletionPart.None:
return;
default:
// any other values are completion parts intended for other kinds of symbols
state.NotePartComplete(CompletionPart.All & ~CompletionPart.FieldSymbolAll);
break;
}
state.SpinWaitComplete(incompletePart, cancellationToken);
}
}
private sealed class ZeroValuedEnumConstantSymbol : SourceEnumConstantSymbol
{
public ZeroValuedEnumConstantSymbol(
SourceMemberContainerTypeSymbol containingEnum,
EnumMemberDeclarationSyntax syntax,
BindingDiagnosticBag diagnostics)
: base(containingEnum, syntax, diagnostics)
{
}
protected override ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics)
{
var constantType = this.ContainingType.EnumUnderlyingType.SpecialType;
return Microsoft.CodeAnalysis.ConstantValue.Default(constantType);
}
}
private sealed class ExplicitValuedEnumConstantSymbol : SourceEnumConstantSymbol
{
private readonly SyntaxReference _equalsValueNodeRef;
public ExplicitValuedEnumConstantSymbol(
SourceMemberContainerTypeSymbol containingEnum,
EnumMemberDeclarationSyntax syntax,
EqualsValueClauseSyntax initializer,
BindingDiagnosticBag diagnostics) :
base(containingEnum, syntax, diagnostics)
{
_equalsValueNodeRef = initializer.GetReference();
}
protected override ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics)
{
return ConstantValueUtils.EvaluateFieldConstant(this, (EqualsValueClauseSyntax)_equalsValueNodeRef.GetSyntax(), dependencies, earlyDecodingWellKnownAttributes, diagnostics);
}
}
private sealed class ImplicitValuedEnumConstantSymbol : SourceEnumConstantSymbol
{
private readonly SourceEnumConstantSymbol _otherConstant;
private readonly uint _otherConstantOffset;
public ImplicitValuedEnumConstantSymbol(
SourceMemberContainerTypeSymbol containingEnum,
EnumMemberDeclarationSyntax syntax,
SourceEnumConstantSymbol otherConstant,
uint otherConstantOffset,
BindingDiagnosticBag diagnostics) :
base(containingEnum, syntax, diagnostics)
{
Debug.Assert((object)otherConstant != null);
Debug.Assert(otherConstantOffset > 0);
_otherConstant = otherConstant;
_otherConstantOffset = otherConstantOffset;
}
protected override ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics)
{
var otherValue = _otherConstant.GetConstantValue(new ConstantFieldsInProgress(this, dependencies), earlyDecodingWellKnownAttributes);
// Value may be Unset if there are dependencies
// that must be evaluated first.
if (otherValue == Microsoft.CodeAnalysis.ConstantValue.Unset)
{
return Microsoft.CodeAnalysis.ConstantValue.Unset;
}
if (otherValue.IsBad)
{
return Microsoft.CodeAnalysis.ConstantValue.Bad;
}
ConstantValue value;
var overflowKind = EnumConstantHelper.OffsetValue(otherValue, _otherConstantOffset, out value);
if (overflowKind == EnumOverflowKind.OverflowReport)
{
// Report an error if the value is immediately
// outside the range, but not otherwise.
diagnostics.Add(ErrorCode.ERR_EnumeratorOverflow, this.Locations[0], this);
}
return 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.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a constant field of an enum.
/// </summary>
internal abstract class SourceEnumConstantSymbol : SourceFieldSymbolWithSyntaxReference
{
public static SourceEnumConstantSymbol CreateExplicitValuedConstant(
SourceMemberContainerTypeSymbol containingEnum,
EnumMemberDeclarationSyntax syntax,
BindingDiagnosticBag diagnostics)
{
var initializer = syntax.EqualsValue;
Debug.Assert(initializer != null);
return new ExplicitValuedEnumConstantSymbol(containingEnum, syntax, initializer, diagnostics);
}
public static SourceEnumConstantSymbol CreateImplicitValuedConstant(
SourceMemberContainerTypeSymbol containingEnum,
EnumMemberDeclarationSyntax syntax,
SourceEnumConstantSymbol otherConstant,
int otherConstantOffset,
BindingDiagnosticBag diagnostics)
{
if ((object)otherConstant == null)
{
Debug.Assert(otherConstantOffset == 0);
return new ZeroValuedEnumConstantSymbol(containingEnum, syntax, diagnostics);
}
else
{
Debug.Assert(otherConstantOffset > 0);
return new ImplicitValuedEnumConstantSymbol(containingEnum, syntax, otherConstant, (uint)otherConstantOffset, diagnostics);
}
}
protected SourceEnumConstantSymbol(SourceMemberContainerTypeSymbol containingEnum, EnumMemberDeclarationSyntax syntax, BindingDiagnosticBag diagnostics)
: base(containingEnum, syntax.Identifier.ValueText, syntax.GetReference(), syntax.Identifier.GetLocation())
{
if (this.Name == WellKnownMemberNames.EnumBackingFieldName)
{
diagnostics.Add(ErrorCode.ERR_ReservedEnumerator, this.ErrorLocation, WellKnownMemberNames.EnumBackingFieldName);
}
}
internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound)
{
return TypeWithAnnotations.Create(this.ContainingType);
}
public override Symbol AssociatedSymbol
{
get
{
return null;
}
}
protected sealed override DeclarationModifiers Modifiers
{
get
{
return DeclarationModifiers.Const | DeclarationModifiers.Static | DeclarationModifiers.Public;
}
}
public new EnumMemberDeclarationSyntax SyntaxNode
{
get
{
return (EnumMemberDeclarationSyntax)base.SyntaxNode;
}
}
protected override SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList
{
get
{
if (this.containingType.AnyMemberHasAttributes)
{
return this.SyntaxNode.AttributeLists;
}
return default(SyntaxList<AttributeListSyntax>);
}
}
internal sealed override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var incompletePart = state.NextIncompletePart;
switch (incompletePart)
{
case CompletionPart.Attributes:
GetAttributes();
break;
case CompletionPart.Type:
state.NotePartComplete(CompletionPart.Type);
break;
case CompletionPart.FixedSize:
Debug.Assert(!this.IsFixedSizeBuffer);
state.NotePartComplete(CompletionPart.FixedSize);
break;
case CompletionPart.ConstantValue:
GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false);
break;
case CompletionPart.None:
return;
default:
// any other values are completion parts intended for other kinds of symbols
state.NotePartComplete(CompletionPart.All & ~CompletionPart.FieldSymbolAll);
break;
}
state.SpinWaitComplete(incompletePart, cancellationToken);
}
}
private sealed class ZeroValuedEnumConstantSymbol : SourceEnumConstantSymbol
{
public ZeroValuedEnumConstantSymbol(
SourceMemberContainerTypeSymbol containingEnum,
EnumMemberDeclarationSyntax syntax,
BindingDiagnosticBag diagnostics)
: base(containingEnum, syntax, diagnostics)
{
}
protected override ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics)
{
var constantType = this.ContainingType.EnumUnderlyingType.SpecialType;
return Microsoft.CodeAnalysis.ConstantValue.Default(constantType);
}
}
private sealed class ExplicitValuedEnumConstantSymbol : SourceEnumConstantSymbol
{
private readonly SyntaxReference _equalsValueNodeRef;
public ExplicitValuedEnumConstantSymbol(
SourceMemberContainerTypeSymbol containingEnum,
EnumMemberDeclarationSyntax syntax,
EqualsValueClauseSyntax initializer,
BindingDiagnosticBag diagnostics) :
base(containingEnum, syntax, diagnostics)
{
_equalsValueNodeRef = initializer.GetReference();
}
protected override ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics)
{
return ConstantValueUtils.EvaluateFieldConstant(this, (EqualsValueClauseSyntax)_equalsValueNodeRef.GetSyntax(), dependencies, earlyDecodingWellKnownAttributes, diagnostics);
}
}
private sealed class ImplicitValuedEnumConstantSymbol : SourceEnumConstantSymbol
{
private readonly SourceEnumConstantSymbol _otherConstant;
private readonly uint _otherConstantOffset;
public ImplicitValuedEnumConstantSymbol(
SourceMemberContainerTypeSymbol containingEnum,
EnumMemberDeclarationSyntax syntax,
SourceEnumConstantSymbol otherConstant,
uint otherConstantOffset,
BindingDiagnosticBag diagnostics) :
base(containingEnum, syntax, diagnostics)
{
Debug.Assert((object)otherConstant != null);
Debug.Assert(otherConstantOffset > 0);
_otherConstant = otherConstant;
_otherConstantOffset = otherConstantOffset;
}
protected override ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics)
{
var otherValue = _otherConstant.GetConstantValue(new ConstantFieldsInProgress(this, dependencies), earlyDecodingWellKnownAttributes);
// Value may be Unset if there are dependencies
// that must be evaluated first.
if (otherValue == Microsoft.CodeAnalysis.ConstantValue.Unset)
{
return Microsoft.CodeAnalysis.ConstantValue.Unset;
}
if (otherValue.IsBad)
{
return Microsoft.CodeAnalysis.ConstantValue.Bad;
}
ConstantValue value;
var overflowKind = EnumConstantHelper.OffsetValue(otherValue, _otherConstantOffset, out value);
if (overflowKind == EnumOverflowKind.OverflowReport)
{
// Report an error if the value is immediately
// outside the range, but not otherwise.
diagnostics.Add(ErrorCode.ERR_EnumeratorOverflow, this.Locations[0], this);
}
return value;
}
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousType_PropertyPublicSymbol.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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Partial Friend NotInheritable Class AnonymousTypeManager
Friend NotInheritable Class AnonymousTypePropertyPublicSymbol
Inherits SynthesizedPropertyBase
Private ReadOnly _container As AnonymousTypePublicSymbol
Private ReadOnly _getMethod As MethodSymbol
Private ReadOnly _setMethod As MethodSymbol
''' <summary> Index of the property in the containing anonymous type </summary>
Friend ReadOnly PropertyIndex As Integer
Public Sub New(container As AnonymousTypePublicSymbol, index As Integer)
Me._container = container
Me.PropertyIndex = index
Me._getMethod = New AnonymousTypePropertyGetAccessorPublicSymbol(Me)
If Not container.TypeDescriptor.Fields(index).IsKey Then
Me._setMethod = New AnonymousTypePropertySetAccessorPublicSymbol(Me, container.Manager.System_Void)
End If
End Sub
Friend ReadOnly Property AnonymousType As AnonymousTypePublicSymbol
Get
Return _container
End Get
End Property
Public Overrides ReadOnly Property SetMethod As MethodSymbol
Get
Return Me._setMethod
End Get
End Property
Public Overrides ReadOnly Property GetMethod As MethodSymbol
Get
Return Me._getMethod
End Get
End Property
Public Overrides ReadOnly Property Type As TypeSymbol
Get
Return Me._container.TypeDescriptor.Fields(Me.PropertyIndex).Type
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return Me._container.TypeDescriptor.Fields(Me.PropertyIndex).Name
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _container
End Get
End Property
Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol
Get
Return _container
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray.Create(Me._container.TypeDescriptor.Fields(Me.PropertyIndex).Location)
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return GetDeclaringSyntaxReferenceHelper(Of FieldInitializerSyntax)(Me.Locations)
End Get
End Property
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
' The same as owning type
Return Me.ContainingType.IsImplicitlyDeclared
End Get
End Property
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing Then
Return False
ElseIf obj Is Me Then
Return True
End If
Dim other = TryCast(obj, AnonymousTypePropertyPublicSymbol)
If other Is Nothing Then
Return False
End If
' consider properties the same is the owning types are the
' same and the names are equal
Return other IsNot Nothing AndAlso
IdentifierComparison.Equals(other.Name, Me.Name) AndAlso
other.ContainingType.Equals(Me.ContainingType)
End Function
Public Overrides Function GetHashCode() As Integer
Return Hash.Combine(Me.ContainingType.GetHashCode(), IdentifierComparison.GetHashCode(Me.Name))
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Partial Friend NotInheritable Class AnonymousTypeManager
Friend NotInheritable Class AnonymousTypePropertyPublicSymbol
Inherits SynthesizedPropertyBase
Private ReadOnly _container As AnonymousTypePublicSymbol
Private ReadOnly _getMethod As MethodSymbol
Private ReadOnly _setMethod As MethodSymbol
''' <summary> Index of the property in the containing anonymous type </summary>
Friend ReadOnly PropertyIndex As Integer
Public Sub New(container As AnonymousTypePublicSymbol, index As Integer)
Me._container = container
Me.PropertyIndex = index
Me._getMethod = New AnonymousTypePropertyGetAccessorPublicSymbol(Me)
If Not container.TypeDescriptor.Fields(index).IsKey Then
Me._setMethod = New AnonymousTypePropertySetAccessorPublicSymbol(Me, container.Manager.System_Void)
End If
End Sub
Friend ReadOnly Property AnonymousType As AnonymousTypePublicSymbol
Get
Return _container
End Get
End Property
Public Overrides ReadOnly Property SetMethod As MethodSymbol
Get
Return Me._setMethod
End Get
End Property
Public Overrides ReadOnly Property GetMethod As MethodSymbol
Get
Return Me._getMethod
End Get
End Property
Public Overrides ReadOnly Property Type As TypeSymbol
Get
Return Me._container.TypeDescriptor.Fields(Me.PropertyIndex).Type
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return Me._container.TypeDescriptor.Fields(Me.PropertyIndex).Name
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _container
End Get
End Property
Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol
Get
Return _container
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray.Create(Me._container.TypeDescriptor.Fields(Me.PropertyIndex).Location)
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return GetDeclaringSyntaxReferenceHelper(Of FieldInitializerSyntax)(Me.Locations)
End Get
End Property
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
' The same as owning type
Return Me.ContainingType.IsImplicitlyDeclared
End Get
End Property
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing Then
Return False
ElseIf obj Is Me Then
Return True
End If
Dim other = TryCast(obj, AnonymousTypePropertyPublicSymbol)
If other Is Nothing Then
Return False
End If
' consider properties the same is the owning types are the
' same and the names are equal
Return other IsNot Nothing AndAlso
IdentifierComparison.Equals(other.Name, Me.Name) AndAlso
other.ContainingType.Equals(Me.ContainingType)
End Function
Public Overrides Function GetHashCode() As Integer
Return Hash.Combine(Me.ContainingType.GetHashCode(), IdentifierComparison.GetHashCode(Me.Name))
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/VisualStudio/LiveShare/Impl/Client/Projects/IRemoteProjectInfoProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects
{
internal interface IRemoteProjectInfoProvider
{
Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects
{
internal interface IRemoteProjectInfoProvider
{
Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ContextQuery/VisualBasicSyntaxContextService.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
<ExportLanguageService(GetType(ISyntaxContextService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicSyntaxContextService
Implements ISyntaxContextService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function CreateContext(document As Document, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As SyntaxContext Implements ISyntaxContextService.CreateContext
Return VisualBasicSyntaxContext.CreateContext(document, semanticModel, position, cancellationToken)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
<ExportLanguageService(GetType(ISyntaxContextService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicSyntaxContextService
Implements ISyntaxContextService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function CreateContext(document As Document, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As SyntaxContext Implements ISyntaxContextService.CreateContext
Return VisualBasicSyntaxContext.CreateContext(document, semanticModel, position, cancellationToken)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/CSharpSyntaxGenerator.csproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<Platforms>AnyCPU</Platforms>
<RootNamespace>CSharpSyntaxGenerator</RootNamespace>
<AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects>
<!-- We build this against netcoreapp3.1 to build the console app version, and against netstandard2.0 for
the Source Generator version. -->
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<OutputType Condition="'$(TargetFramework)' == 'netcoreapp3.1'">Exe</OutputType>
<RuntimeIdentifiers>$(RoslynPortableRuntimeIdentifiers)</RuntimeIdentifiers>
<IsShipping>false</IsShipping>
<ExcludeFromSourceBuild>false</ExcludeFromSourceBuild>
</PropertyGroup>
<ItemGroup>
<!-- Make sure to reference the same version of Microsoft.CodeAnalysis.Analyzers as the rest of the build -->
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="$(MicrosoftCodeAnalysisAnalyzersVersion)" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<!-- If we're building the command line tool, we have to include some dependencies used for grammar generation -->
<Compile Include="..\..\..\..\..\Compilers\Core\Portable\Symbols\WellKnownMemberNames.cs" Link="Grammar\WellKnownMemberNames.cs" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" />
<Compile Include="..\..\..\..\..\Compilers\CSharp\Portable\Declarations\DeclarationModifiers.cs" Link="Grammar\DeclarationModifiers.cs" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" />
<Compile Include="..\..\..\..\..\Compilers\CSharp\Portable\Syntax\SyntaxKind.cs" Link="Grammar\SyntaxKind.cs" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" />
<Compile Include="..\..\..\..\..\Compilers\CSharp\Portable\Syntax\SyntaxKindFacts.cs" Link="Grammar\SyntaxKindFacts.cs" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" />
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="$(SourceGeneratorMicrosoftCodeAnalysisVersion)" PrivateAssets="all" Condition="'$(TargetFramework)' == 'netstandard2.0'" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<Platforms>AnyCPU</Platforms>
<RootNamespace>CSharpSyntaxGenerator</RootNamespace>
<AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects>
<!-- We build this against netcoreapp3.1 to build the console app version, and against netstandard2.0 for
the Source Generator version. -->
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<OutputType Condition="'$(TargetFramework)' == 'netcoreapp3.1'">Exe</OutputType>
<RuntimeIdentifiers>$(RoslynPortableRuntimeIdentifiers)</RuntimeIdentifiers>
<IsShipping>false</IsShipping>
<ExcludeFromSourceBuild>false</ExcludeFromSourceBuild>
</PropertyGroup>
<ItemGroup>
<!-- Make sure to reference the same version of Microsoft.CodeAnalysis.Analyzers as the rest of the build -->
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="$(MicrosoftCodeAnalysisAnalyzersVersion)" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<!-- If we're building the command line tool, we have to include some dependencies used for grammar generation -->
<Compile Include="..\..\..\..\..\Compilers\Core\Portable\Symbols\WellKnownMemberNames.cs" Link="Grammar\WellKnownMemberNames.cs" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" />
<Compile Include="..\..\..\..\..\Compilers\CSharp\Portable\Declarations\DeclarationModifiers.cs" Link="Grammar\DeclarationModifiers.cs" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" />
<Compile Include="..\..\..\..\..\Compilers\CSharp\Portable\Syntax\SyntaxKind.cs" Link="Grammar\SyntaxKind.cs" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" />
<Compile Include="..\..\..\..\..\Compilers\CSharp\Portable\Syntax\SyntaxKindFacts.cs" Link="Grammar\SyntaxKindFacts.cs" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" />
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="$(SourceGeneratorMicrosoftCodeAnalysisVersion)" PrivateAssets="all" Condition="'$(TargetFramework)' == 'netstandard2.0'" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxTokenListExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SyntaxTokenListExtensions
{
public static SyntaxTokenList ToSyntaxTokenList(this IEnumerable<SyntaxToken> tokens)
=> new(tokens);
public static SyntaxTokenList ToSyntaxTokenListAndFree(this ArrayBuilder<SyntaxToken> tokens)
{
var tokenList = new SyntaxTokenList(tokens);
tokens.Free();
return tokenList;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SyntaxTokenListExtensions
{
public static SyntaxTokenList ToSyntaxTokenList(this IEnumerable<SyntaxToken> tokens)
=> new(tokens);
public static SyntaxTokenList ToSyntaxTokenListAndFree(this ArrayBuilder<SyntaxToken> tokens)
{
var tokenList = new SyntaxTokenList(tokens);
tokens.Free();
return tokenList;
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/SubKeywordRecommender.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.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Sub" keyword in member declaration contexts
''' </summary>
Friend Class SubKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsTypeMemberDeclarationKeywordContext OrElse context.IsInterfaceMemberDeclarationKeywordContext Then
Dim modifiers = context.ModifierCollectionFacts
If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Method) AndAlso
modifiers.IteratorKeyword.Kind = SyntaxKind.None Then
Return ImmutableArray.Create(New RecommendedKeyword("Sub", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code))
End If
End If
' Exit Sub
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
If targetToken.IsKindOrHasMatchingText(SyntaxKind.ExitKeyword) AndAlso
context.IsInStatementBlockOfKind(SyntaxKind.SubBlock, SyntaxKind.MultiLineSubLambdaExpression) AndAlso
Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then
Return ImmutableArray.Create(New RecommendedKeyword("Sub", VBFeaturesResources.Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure))
End If
Return ImmutableArray(Of RecommendedKeyword).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.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Sub" keyword in member declaration contexts
''' </summary>
Friend Class SubKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsTypeMemberDeclarationKeywordContext OrElse context.IsInterfaceMemberDeclarationKeywordContext Then
Dim modifiers = context.ModifierCollectionFacts
If modifiers.CouldApplyToOneOf(PossibleDeclarationTypes.Method) AndAlso
modifiers.IteratorKeyword.Kind = SyntaxKind.None Then
Return ImmutableArray.Create(New RecommendedKeyword("Sub", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code))
End If
End If
' Exit Sub
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
If targetToken.IsKindOrHasMatchingText(SyntaxKind.ExitKeyword) AndAlso
context.IsInStatementBlockOfKind(SyntaxKind.SubBlock, SyntaxKind.MultiLineSubLambdaExpression) AndAlso
Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then
Return ImmutableArray.Create(New RecommendedKeyword("Sub", VBFeaturesResources.Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure))
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Compilers/VisualBasic/Test/CommandLine/AssemblyAttributes.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 Xunit
| ' Licensed to the .NET Foundation under one or more 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 Xunit
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Features/Core/Portable/PublicAPI.Unshipped.txt | const Microsoft.CodeAnalysis.TextTags.Record = "Record" -> string
const Microsoft.CodeAnalysis.TextTags.RecordStruct = "RecordStruct" -> string
Microsoft.CodeAnalysis.Completion.CompletionItem.IsComplexTextEdit.get -> bool
Microsoft.CodeAnalysis.Completion.CompletionItem.WithIsComplexTextEdit(bool isComplexTextEdit) -> Microsoft.CodeAnalysis.Completion.CompletionItem
static Microsoft.CodeAnalysis.Completion.CompletionChange.Create(Microsoft.CodeAnalysis.Text.TextChange textChange, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Text.TextChange> textChanges, int? newPosition = null, bool includesCommitCharacter = false) -> Microsoft.CodeAnalysis.Completion.CompletionChange
static Microsoft.CodeAnalysis.Completion.CompletionItem.Create(string displayText, string filterText = null, string sortText = null, System.Collections.Immutable.ImmutableDictionary<string, string> properties = null, System.Collections.Immutable.ImmutableArray<string> tags = default(System.Collections.Immutable.ImmutableArray<string>), Microsoft.CodeAnalysis.Completion.CompletionItemRules rules = null, string displayTextPrefix = null, string displayTextSuffix = null, string inlineDescription = null, bool isComplexTextEdit = false) -> Microsoft.CodeAnalysis.Completion.CompletionItem
static Microsoft.CodeAnalysis.Completion.CompletionItem.Create(string displayText, string filterText, string sortText, System.Collections.Immutable.ImmutableDictionary<string, string> properties, System.Collections.Immutable.ImmutableArray<string> tags, Microsoft.CodeAnalysis.Completion.CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription) -> Microsoft.CodeAnalysis.Completion.CompletionItem
| const Microsoft.CodeAnalysis.TextTags.Record = "Record" -> string
const Microsoft.CodeAnalysis.TextTags.RecordStruct = "RecordStruct" -> string
Microsoft.CodeAnalysis.Completion.CompletionItem.IsComplexTextEdit.get -> bool
Microsoft.CodeAnalysis.Completion.CompletionItem.WithIsComplexTextEdit(bool isComplexTextEdit) -> Microsoft.CodeAnalysis.Completion.CompletionItem
static Microsoft.CodeAnalysis.Completion.CompletionChange.Create(Microsoft.CodeAnalysis.Text.TextChange textChange, System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.Text.TextChange> textChanges, int? newPosition = null, bool includesCommitCharacter = false) -> Microsoft.CodeAnalysis.Completion.CompletionChange
static Microsoft.CodeAnalysis.Completion.CompletionItem.Create(string displayText, string filterText = null, string sortText = null, System.Collections.Immutable.ImmutableDictionary<string, string> properties = null, System.Collections.Immutable.ImmutableArray<string> tags = default(System.Collections.Immutable.ImmutableArray<string>), Microsoft.CodeAnalysis.Completion.CompletionItemRules rules = null, string displayTextPrefix = null, string displayTextSuffix = null, string inlineDescription = null, bool isComplexTextEdit = false) -> Microsoft.CodeAnalysis.Completion.CompletionItem
static Microsoft.CodeAnalysis.Completion.CompletionItem.Create(string displayText, string filterText, string sortText, System.Collections.Immutable.ImmutableDictionary<string, string> properties, System.Collections.Immutable.ImmutableArray<string> tags, Microsoft.CodeAnalysis.Completion.CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription) -> Microsoft.CodeAnalysis.Completion.CompletionItem
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/Core/Portable/LanguageServices/DeclaredSymbolFactoryService/AbstractDeclaredSymbolInfoFactoryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using System.Threading;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal abstract class AbstractDeclaredSymbolInfoFactoryService<
TCompilationUnitSyntax,
TUsingDirectiveSyntax,
TNamespaceDeclarationSyntax,
TTypeDeclarationSyntax,
TEnumDeclarationSyntax,
TMemberDeclarationSyntax,
TNameSyntax,
TQualifiedNameSyntax,
TIdentifierNameSyntax> : IDeclaredSymbolInfoFactoryService
where TCompilationUnitSyntax : SyntaxNode
where TUsingDirectiveSyntax : SyntaxNode
where TNamespaceDeclarationSyntax : TMemberDeclarationSyntax
where TTypeDeclarationSyntax : TMemberDeclarationSyntax
where TEnumDeclarationSyntax : TMemberDeclarationSyntax
where TMemberDeclarationSyntax : SyntaxNode
where TNameSyntax : SyntaxNode
where TQualifiedNameSyntax : TNameSyntax
where TIdentifierNameSyntax : TNameSyntax
{
private static readonly ObjectPool<List<Dictionary<string, string>>> s_aliasMapListPool
= SharedPools.Default<List<Dictionary<string, string>>>();
// Note: these names are stored case insensitively. That way the alias mapping works
// properly for VB. It will mean that our inheritance maps may store more links in them
// for C#. However, that's ok. It will be rare in practice, and all it means is that
// we'll end up examining slightly more types (likely 0) when doing operations like
// Find all references.
private static readonly ObjectPool<Dictionary<string, string>> s_aliasMapPool
= SharedPools.StringIgnoreCaseDictionary<string>();
protected AbstractDeclaredSymbolInfoFactoryService()
{
}
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TCompilationUnitSyntax node);
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TNamespaceDeclarationSyntax node);
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TTypeDeclarationSyntax node);
protected abstract IEnumerable<TMemberDeclarationSyntax> GetChildren(TEnumDeclarationSyntax node);
protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TCompilationUnitSyntax node);
protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TNamespaceDeclarationSyntax node);
protected abstract TNameSyntax GetName(TNamespaceDeclarationSyntax node);
protected abstract TNameSyntax GetLeft(TQualifiedNameSyntax node);
protected abstract TNameSyntax GetRight(TQualifiedNameSyntax node);
protected abstract SyntaxToken GetIdentifier(TIdentifierNameSyntax node);
protected abstract string GetContainerDisplayName(TMemberDeclarationSyntax namespaceDeclaration);
protected abstract string GetFullyQualifiedContainerName(TMemberDeclarationSyntax memberDeclaration, string rootNamespace);
protected abstract void AddDeclaredSymbolInfosWorker(
SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken);
/// <summary>
/// Get the name of the target type of specified extension method declaration.
/// The node provided must be an extension method declaration, i.e. calling `TryGetDeclaredSymbolInfo()`
/// on `node` should return a `DeclaredSymbolInfo` of kind `ExtensionMethod`.
/// If the return value is null, then it means this is a "complex" method (as described at <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>).
/// </summary>
protected abstract string GetReceiverTypeName(TMemberDeclarationSyntax node);
protected abstract bool TryGetAliasesFromUsingDirective(TUsingDirectiveSyntax node, out ImmutableArray<(string aliasName, string name)> aliases);
protected abstract string GetRootNamespace(CompilationOptions compilationOptions);
protected static List<Dictionary<string, string>> AllocateAliasMapList()
=> s_aliasMapListPool.Allocate();
// We do not differentiate arrays of different kinds for simplicity.
// e.g. int[], int[][], int[,], etc. are all represented as int[] in the index.
protected static string CreateReceiverTypeString(string typeName, bool isArray)
{
if (string.IsNullOrEmpty(typeName))
{
return isArray
? FindSymbols.Extensions.ComplexArrayReceiverTypeName
: FindSymbols.Extensions.ComplexReceiverTypeName;
}
else
{
return isArray
? typeName + FindSymbols.Extensions.ArrayReceiverTypeNameSuffix
: typeName;
}
}
protected static string CreateValueTupleTypeString(int elementCount)
{
const string ValueTupleName = "ValueTuple";
if (elementCount == 0)
{
return ValueTupleName;
}
// A ValueTuple can have up to 8 type parameters.
return ValueTupleName + ArityUtilities.GetMetadataAritySuffix(elementCount > 8 ? 8 : elementCount);
}
protected static void FreeAliasMapList(List<Dictionary<string, string>> list)
{
if (list != null)
{
foreach (var aliasMap in list)
{
FreeAliasMap(aliasMap);
}
s_aliasMapListPool.ClearAndFree(list);
}
}
protected static void FreeAliasMap(Dictionary<string, string> aliasMap)
{
if (aliasMap != null)
{
s_aliasMapPool.ClearAndFree(aliasMap);
}
}
protected static Dictionary<string, string> AllocateAliasMap()
=> s_aliasMapPool.Allocate();
protected static void AppendTokens(SyntaxNode node, StringBuilder builder)
{
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsToken)
{
builder.Append(child.AsToken().Text);
}
else
{
AppendTokens(child.AsNode(), builder);
}
}
}
protected static void Intern(StringTable stringTable, ArrayBuilder<string> builder)
{
for (int i = 0, n = builder.Count; i < n; i++)
{
builder[i] = stringTable.Add(builder[i]);
}
}
public void AddDeclaredSymbolInfos(
Document document,
SyntaxNode root,
ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos,
Dictionary<string, ArrayBuilder<int>> extensionMethodInfo,
CancellationToken cancellationToken)
{
var project = document.Project;
var stringTable = SyntaxTreeIndex.GetStringTable(project);
var rootNamespace = this.GetRootNamespace(project.CompilationOptions);
using var _1 = PooledDictionary<string, string>.GetInstance(out var aliases);
foreach (var usingAlias in GetUsingAliases((TCompilationUnitSyntax)root))
{
if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current))
AddAliases(aliases, current);
}
foreach (var child in GetChildren((TCompilationUnitSyntax)root))
AddDeclaredSymbolInfos(root, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, "", "", cancellationToken);
}
private void AddDeclaredSymbolInfos(
SyntaxNode container,
TMemberDeclarationSyntax memberDeclaration,
StringTable stringTable,
string rootNamespace,
ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos,
Dictionary<string, string> aliases,
Dictionary<string, ArrayBuilder<int>> extensionMethodInfo,
string containerDisplayName,
string fullyQualifiedContainerName,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (memberDeclaration is TNamespaceDeclarationSyntax namespaceDeclaration)
{
AddNamespaceDeclaredSymbolInfos(GetName(namespaceDeclaration), fullyQualifiedContainerName);
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var usingAlias in GetUsingAliases(namespaceDeclaration))
{
if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current))
AddAliases(aliases, current);
}
foreach (var child in GetChildren(namespaceDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
else if (memberDeclaration is TTypeDeclarationSyntax baseTypeDeclaration)
{
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var child in GetChildren(baseTypeDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
else if (memberDeclaration is TEnumDeclarationSyntax enumDeclaration)
{
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var child in GetChildren(enumDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
AddDeclaredSymbolInfosWorker(
container,
memberDeclaration,
stringTable,
declaredSymbolInfos,
aliases,
extensionMethodInfo,
containerDisplayName,
fullyQualifiedContainerName,
cancellationToken);
return;
// Returns the new fully-qualified-container-name built from fullyQualifiedContainerName
// with all the pieces of 'name' added to the end of it.
string AddNamespaceDeclaredSymbolInfos(TNameSyntax name, string fullyQualifiedContainerName)
{
if (name is TQualifiedNameSyntax qualifiedName)
{
// Recurse down the left side of the qualified name. Build up the new fully qualified
// parent name for when going down the right side.
var parentQualifiedContainerName = AddNamespaceDeclaredSymbolInfos(GetLeft(qualifiedName), fullyQualifiedContainerName);
return AddNamespaceDeclaredSymbolInfos(GetRight(qualifiedName), parentQualifiedContainerName);
}
else if (name is TIdentifierNameSyntax nameSyntax)
{
var namespaceName = GetIdentifier(nameSyntax).ValueText;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
namespaceName,
nameSuffix: null,
containerDisplayName: null,
fullyQualifiedContainerName,
isPartial: true,
DeclaredSymbolInfoKind.Namespace,
Accessibility.Public,
nameSyntax.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return string.IsNullOrEmpty(fullyQualifiedContainerName)
? namespaceName
: fullyQualifiedContainerName + "." + namespaceName;
}
else
{
return fullyQualifiedContainerName;
}
}
}
protected void AddExtensionMethodInfo(
TMemberDeclarationSyntax node,
Dictionary<string, string> aliases,
int declaredSymbolInfoIndex,
Dictionary<string, ArrayBuilder<int>> extensionMethodsInfoBuilder)
{
var receiverTypeName = this.GetReceiverTypeName(node);
// Target type is an alias
if (aliases.TryGetValue(receiverTypeName, out var originalName))
{
// it is an alias of multiple with identical name,
// simply treat it as a complex method.
if (originalName == null)
{
receiverTypeName = FindSymbols.Extensions.ComplexReceiverTypeName;
}
else
{
// replace the alias with its original name.
receiverTypeName = originalName;
}
}
if (!extensionMethodsInfoBuilder.TryGetValue(receiverTypeName, out var arrayBuilder))
{
arrayBuilder = ArrayBuilder<int>.GetInstance();
extensionMethodsInfoBuilder[receiverTypeName] = arrayBuilder;
}
arrayBuilder.Add(declaredSymbolInfoIndex);
}
private static void AddAliases(Dictionary<string, string> allAliases, ImmutableArray<(string aliasName, string name)> aliases)
{
foreach (var (aliasName, name) in aliases)
{
// In C#, it's valid to declare two alias with identical name,
// as long as they are in different containers.
//
// e.g.
// using X = System.String;
// namespace N
// {
// using X = System.Int32;
// }
//
// If we detect this, we will simply treat extension methods whose
// target type is this alias as complex method.
if (allAliases.ContainsKey(aliasName))
{
allAliases[aliasName] = null;
}
else
{
allAliases[aliasName] = name;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal abstract class AbstractDeclaredSymbolInfoFactoryService<
TCompilationUnitSyntax,
TUsingDirectiveSyntax,
TNamespaceDeclarationSyntax,
TTypeDeclarationSyntax,
TEnumDeclarationSyntax,
TMemberDeclarationSyntax,
TNameSyntax,
TQualifiedNameSyntax,
TIdentifierNameSyntax> : IDeclaredSymbolInfoFactoryService
where TCompilationUnitSyntax : SyntaxNode
where TUsingDirectiveSyntax : SyntaxNode
where TNamespaceDeclarationSyntax : TMemberDeclarationSyntax
where TTypeDeclarationSyntax : TMemberDeclarationSyntax
where TEnumDeclarationSyntax : TMemberDeclarationSyntax
where TMemberDeclarationSyntax : SyntaxNode
where TNameSyntax : SyntaxNode
where TQualifiedNameSyntax : TNameSyntax
where TIdentifierNameSyntax : TNameSyntax
{
private static readonly ObjectPool<List<Dictionary<string, string>>> s_aliasMapListPool
= SharedPools.Default<List<Dictionary<string, string>>>();
// Note: these names are stored case insensitively. That way the alias mapping works
// properly for VB. It will mean that our inheritance maps may store more links in them
// for C#. However, that's ok. It will be rare in practice, and all it means is that
// we'll end up examining slightly more types (likely 0) when doing operations like
// Find all references.
private static readonly ObjectPool<Dictionary<string, string>> s_aliasMapPool
= SharedPools.StringIgnoreCaseDictionary<string>();
protected AbstractDeclaredSymbolInfoFactoryService()
{
}
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TCompilationUnitSyntax node);
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TNamespaceDeclarationSyntax node);
protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TTypeDeclarationSyntax node);
protected abstract IEnumerable<TMemberDeclarationSyntax> GetChildren(TEnumDeclarationSyntax node);
protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TCompilationUnitSyntax node);
protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TNamespaceDeclarationSyntax node);
protected abstract TNameSyntax GetName(TNamespaceDeclarationSyntax node);
protected abstract TNameSyntax GetLeft(TQualifiedNameSyntax node);
protected abstract TNameSyntax GetRight(TQualifiedNameSyntax node);
protected abstract SyntaxToken GetIdentifier(TIdentifierNameSyntax node);
protected abstract string GetContainerDisplayName(TMemberDeclarationSyntax namespaceDeclaration);
protected abstract string GetFullyQualifiedContainerName(TMemberDeclarationSyntax memberDeclaration, string rootNamespace);
protected abstract void AddDeclaredSymbolInfosWorker(
SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken);
/// <summary>
/// Get the name of the target type of specified extension method declaration.
/// The node provided must be an extension method declaration, i.e. calling `TryGetDeclaredSymbolInfo()`
/// on `node` should return a `DeclaredSymbolInfo` of kind `ExtensionMethod`.
/// If the return value is null, then it means this is a "complex" method (as described at <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>).
/// </summary>
protected abstract string GetReceiverTypeName(TMemberDeclarationSyntax node);
protected abstract bool TryGetAliasesFromUsingDirective(TUsingDirectiveSyntax node, out ImmutableArray<(string aliasName, string name)> aliases);
protected abstract string GetRootNamespace(CompilationOptions compilationOptions);
protected static List<Dictionary<string, string>> AllocateAliasMapList()
=> s_aliasMapListPool.Allocate();
// We do not differentiate arrays of different kinds for simplicity.
// e.g. int[], int[][], int[,], etc. are all represented as int[] in the index.
protected static string CreateReceiverTypeString(string typeName, bool isArray)
{
if (string.IsNullOrEmpty(typeName))
{
return isArray
? FindSymbols.Extensions.ComplexArrayReceiverTypeName
: FindSymbols.Extensions.ComplexReceiverTypeName;
}
else
{
return isArray
? typeName + FindSymbols.Extensions.ArrayReceiverTypeNameSuffix
: typeName;
}
}
protected static string CreateValueTupleTypeString(int elementCount)
{
const string ValueTupleName = "ValueTuple";
if (elementCount == 0)
{
return ValueTupleName;
}
// A ValueTuple can have up to 8 type parameters.
return ValueTupleName + ArityUtilities.GetMetadataAritySuffix(elementCount > 8 ? 8 : elementCount);
}
protected static void FreeAliasMapList(List<Dictionary<string, string>> list)
{
if (list != null)
{
foreach (var aliasMap in list)
{
FreeAliasMap(aliasMap);
}
s_aliasMapListPool.ClearAndFree(list);
}
}
protected static void FreeAliasMap(Dictionary<string, string> aliasMap)
{
if (aliasMap != null)
{
s_aliasMapPool.ClearAndFree(aliasMap);
}
}
protected static Dictionary<string, string> AllocateAliasMap()
=> s_aliasMapPool.Allocate();
protected static void AppendTokens(SyntaxNode node, StringBuilder builder)
{
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsToken)
{
builder.Append(child.AsToken().Text);
}
else
{
AppendTokens(child.AsNode(), builder);
}
}
}
protected static void Intern(StringTable stringTable, ArrayBuilder<string> builder)
{
for (int i = 0, n = builder.Count; i < n; i++)
{
builder[i] = stringTable.Add(builder[i]);
}
}
public void AddDeclaredSymbolInfos(
Document document,
SyntaxNode root,
ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos,
Dictionary<string, ArrayBuilder<int>> extensionMethodInfo,
CancellationToken cancellationToken)
{
var project = document.Project;
var stringTable = SyntaxTreeIndex.GetStringTable(project);
var rootNamespace = this.GetRootNamespace(project.CompilationOptions);
using var _1 = PooledDictionary<string, string>.GetInstance(out var aliases);
foreach (var usingAlias in GetUsingAliases((TCompilationUnitSyntax)root))
{
if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current))
AddAliases(aliases, current);
}
foreach (var child in GetChildren((TCompilationUnitSyntax)root))
AddDeclaredSymbolInfos(root, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, "", "", cancellationToken);
}
private void AddDeclaredSymbolInfos(
SyntaxNode container,
TMemberDeclarationSyntax memberDeclaration,
StringTable stringTable,
string rootNamespace,
ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos,
Dictionary<string, string> aliases,
Dictionary<string, ArrayBuilder<int>> extensionMethodInfo,
string containerDisplayName,
string fullyQualifiedContainerName,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (memberDeclaration is TNamespaceDeclarationSyntax namespaceDeclaration)
{
AddNamespaceDeclaredSymbolInfos(GetName(namespaceDeclaration), fullyQualifiedContainerName);
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var usingAlias in GetUsingAliases(namespaceDeclaration))
{
if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current))
AddAliases(aliases, current);
}
foreach (var child in GetChildren(namespaceDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
else if (memberDeclaration is TTypeDeclarationSyntax baseTypeDeclaration)
{
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var child in GetChildren(baseTypeDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
else if (memberDeclaration is TEnumDeclarationSyntax enumDeclaration)
{
var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration);
var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace);
foreach (var child in GetChildren(enumDeclaration))
{
AddDeclaredSymbolInfos(
memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo,
innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken);
}
}
AddDeclaredSymbolInfosWorker(
container,
memberDeclaration,
stringTable,
declaredSymbolInfos,
aliases,
extensionMethodInfo,
containerDisplayName,
fullyQualifiedContainerName,
cancellationToken);
return;
// Returns the new fully-qualified-container-name built from fullyQualifiedContainerName
// with all the pieces of 'name' added to the end of it.
string AddNamespaceDeclaredSymbolInfos(TNameSyntax name, string fullyQualifiedContainerName)
{
if (name is TQualifiedNameSyntax qualifiedName)
{
// Recurse down the left side of the qualified name. Build up the new fully qualified
// parent name for when going down the right side.
var parentQualifiedContainerName = AddNamespaceDeclaredSymbolInfos(GetLeft(qualifiedName), fullyQualifiedContainerName);
return AddNamespaceDeclaredSymbolInfos(GetRight(qualifiedName), parentQualifiedContainerName);
}
else if (name is TIdentifierNameSyntax nameSyntax)
{
var namespaceName = GetIdentifier(nameSyntax).ValueText;
declaredSymbolInfos.Add(DeclaredSymbolInfo.Create(
stringTable,
namespaceName,
nameSuffix: null,
containerDisplayName: null,
fullyQualifiedContainerName,
isPartial: true,
DeclaredSymbolInfoKind.Namespace,
Accessibility.Public,
nameSyntax.Span,
inheritanceNames: ImmutableArray<string>.Empty));
return string.IsNullOrEmpty(fullyQualifiedContainerName)
? namespaceName
: fullyQualifiedContainerName + "." + namespaceName;
}
else
{
return fullyQualifiedContainerName;
}
}
}
protected void AddExtensionMethodInfo(
TMemberDeclarationSyntax node,
Dictionary<string, string> aliases,
int declaredSymbolInfoIndex,
Dictionary<string, ArrayBuilder<int>> extensionMethodsInfoBuilder)
{
var receiverTypeName = this.GetReceiverTypeName(node);
// Target type is an alias
if (aliases.TryGetValue(receiverTypeName, out var originalName))
{
// it is an alias of multiple with identical name,
// simply treat it as a complex method.
if (originalName == null)
{
receiverTypeName = FindSymbols.Extensions.ComplexReceiverTypeName;
}
else
{
// replace the alias with its original name.
receiverTypeName = originalName;
}
}
if (!extensionMethodsInfoBuilder.TryGetValue(receiverTypeName, out var arrayBuilder))
{
arrayBuilder = ArrayBuilder<int>.GetInstance();
extensionMethodsInfoBuilder[receiverTypeName] = arrayBuilder;
}
arrayBuilder.Add(declaredSymbolInfoIndex);
}
private static void AddAliases(Dictionary<string, string> allAliases, ImmutableArray<(string aliasName, string name)> aliases)
{
foreach (var (aliasName, name) in aliases)
{
// In C#, it's valid to declare two alias with identical name,
// as long as they are in different containers.
//
// e.g.
// using X = System.String;
// namespace N
// {
// using X = System.Int32;
// }
//
// If we detect this, we will simply treat extension methods whose
// target type is this alias as complex method.
if (allAliases.ContainsKey(aliasName))
{
allAliases[aliasName] = null;
}
else
{
allAliases[aliasName] = name;
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/IEntryPointFinderService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal interface IEntryPointFinderService : ILanguageService
{
/// <summary>
/// Finds the types that contain entry points like the Main method in a give namespace.
/// </summary>
/// <param name="symbol">The namespace to search.</param>
/// <param name="findFormsOnly">Restrict the search to only Windows Forms classes. Note that this is only implemented for VisualBasic</param>
IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol, bool findFormsOnly);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal interface IEntryPointFinderService : ILanguageService
{
/// <summary>
/// Finds the types that contain entry points like the Main method in a give namespace.
/// </summary>
/// <param name="symbol">The namespace to search.</param>
/// <param name="findFormsOnly">Restrict the search to only Windows Forms classes. Note that this is only implemented for VisualBasic</param>
IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol, bool findFormsOnly);
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IUnaryOperatorExpression.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IUnaryOperatorExpression : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17591")]
public void Test_UnaryOperatorExpression_Type_Plus_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_LogicalNot_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/!i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_LogicalNot_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/!Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!Method()')
Operand:
IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_LogicalNot_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/!i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+Method()')
Operand:
IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-Method()')
Operand:
IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~Method()')
Operand:
IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_LogicalNot_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/!Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!Method()')
Operand:
IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/+i/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/-i/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/~i/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/+Method()/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()')
Operand:
IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/-Method()/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()')
Operand:
IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/~Method()/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~Method()')
Operand:
IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/+i/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/-i/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/~i/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_LogicalNot_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/!i/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/+Method()/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+Method()')
Operand:
IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/-Method()/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-Method()')
Operand:
IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/~Method()/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~Method()')
Operand:
IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_LogicalNot_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/!Method()/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!Method()')
Operand:
IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")]
[WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")]
public void Test_UnaryOperatorExpression_Type_And_TrueFalse()
{
string source = @"
public struct S
{
private int value;
public S(int v)
{
value = v;
}
public static S operator |(S x, S y)
{
return new S(x.value - y.value);
}
public static S operator &(S x, S y)
{
return new S(x.value + y.value);
}
public static bool operator true(S x)
{
return x.value > 0;
}
public static bool operator false(S x)
{
return x.value <= 0;
}
}
class C
{
public void M()
{
var x = new S(2);
var y = new S(1);
/*<bind>*/if (x && y) { }/*</bind>*/
}
}
";
string expectedOperationTree = @"
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x && y) { }')
Condition:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x && y')
Operand:
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y')
WhenTrue:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
WhenFalse:
null
";
VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")]
[WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")]
public void Test_UnaryOperatorExpression_Type_Or_TrueFalse()
{
string source = @"
public struct S
{
private int value;
public S(int v)
{
value = v;
}
public static S operator |(S x, S y)
{
return new S(x.value - y.value);
}
public static S operator &(S x, S y)
{
return new S(x.value + y.value);
}
public static bool operator true(S x)
{
return x.value > 0;
}
public static bool operator false(S x)
{
return x.value <= 0;
}
}
class C
{
public void M()
{
var x = new S(2);
var y = new S(1);
/*<bind>*/if (x || y) { }/*</bind>*/
}
}
";
string expectedOperationTree = @"
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x || y) { }')
Condition:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x || y')
Operand:
IBinaryOperation (BinaryOperatorKind.ConditionalOr) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x || y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y')
WhenTrue:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
WhenFalse:
null
";
VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_With_CustomType_NoRightOperator()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/+i/*</bind>*/;
}
}
public struct CustomType
{
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_With_CustomType_DerivedTypes()
{
string source = @"
class A
{
BaseType Method()
{
var i = default(DerivedType);
return /*<bind>*/+i/*</bind>*/;
}
}
public class BaseType
{
public static BaseType operator +(BaseType x)
{
return new BaseType();
}
}
public class DerivedType : BaseType
{
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: BaseType BaseType.op_UnaryPlus(BaseType x)) (OperationKind.Unary, Type: BaseType) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: BaseType, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_With_CustomType_ImplicitConversion()
{
string source = @"
class A
{
BaseType Method()
{
var i = default(DerivedType);
return /*<bind>*/+i/*</bind>*/;
}
}
public class BaseType
{
public static BaseType operator +(BaseType x)
{
return new BaseType();
}
}
public class DerivedType
{
public static implicit operator BaseType(DerivedType x)
{
return new BaseType();
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_With_CustomType_ExplicitConversion()
{
string source = @"
class A
{
BaseType Method()
{
var i = default(DerivedType);
return /*<bind>*/+i/*</bind>*/;
}
}
public class BaseType
{
public static BaseType operator +(BaseType x)
{
return new BaseType();
}
}
public class DerivedType
{
public static explicit operator BaseType(DerivedType x)
{
return new BaseType();
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_With_CustomType_Malformed_Operator()
{
string source = @"
class A
{
BaseType Method()
{
var i = default(BaseType);
return /*<bind>*/+i/*</bind>*/;
}
}
public class BaseType
{
public static BaseType operator +(int x)
{
return new BaseType();
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: BaseType, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")]
public void Test_BinaryExpressionSyntax_Type_And_TrueFalse_Condition()
{
string source = @"
public struct S
{
private int value;
public S(int v)
{
value = v;
}
public static S operator |(S x, S y)
{
return new S(x.value - y.value);
}
public static S operator &(S x, S y)
{
return new S(x.value + y.value);
}
public static bool operator true(S x)
{
return x.value > 0;
}
public static bool operator false(S x)
{
return x.value <= 0;
}
}
class C
{
public void M()
{
var x = new S(2);
var y = new S(1);
if (/*<bind>*/x && y/*</bind>*/) { }
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y')
";
VerifyOperationTreeForTest<BinaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_IncrementExpression()
{
string source = @"
class A
{
int Method()
{
var i = 1;
return /*<bind>*/++i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++i')
Target:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_DecrementExpression()
{
string source = @"
class A
{
int Method()
{
var i = 1;
return /*<bind>*/--i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--i')
Target:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Nullable()
{
string source = @"
class A
{
void Method()
{
var i = /*<bind>*/(int?)1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?) (Syntax: '(int?)1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
";
VerifyOperationTreeForTest<CastExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Pointer()
{
string source = @"
class A
{
unsafe void Method()
{
int[] a = new int[5] {10, 20, 30, 40, 50};
fixed (int* p = &a[0])
{
int* p2 = p;
int p1 = /*<bind>*/*p2/*</bind>*/;
}
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None, Type: null) (Syntax: '*p2')
Children(1):
ILocalReferenceOperation: p2 (OperationKind.LocalReference, Type: System.Int32*) (Syntax: 'p2')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VerifyLiftedUnaryOperators1()
{
var source = @"
class C
{
void F(int? x)
{
var y = /*<bind>*/-x/*</bind>*/;
}
}";
string expectedOperationTree =
@"
IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperationKind.Unary, Type: System.Int32?) (Syntax: '-x')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VerifyNonLiftedUnaryOperators1()
{
var source = @"
class C
{
void F(int x)
{
var y = /*<bind>*/-x/*</bind>*/;
}
}";
string expectedOperationTree =
@"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-x')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VerifyLiftedUserDefinedUnaryOperators1()
{
var source = @"
struct C
{
public static C operator -(C c) { }
void F(C? x)
{
var y = /*<bind>*/-x/*</bind>*/;
}
}";
string expectedOperationTree =
@"
IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C?) (Syntax: '-x')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C?) (Syntax: 'x')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VerifyNonLiftedUserDefinedUnaryOperators1()
{
var source = @"
struct C
{
public static C operator -(C c) { }
void F(C x)
{
var y = /*<bind>*/-x/*</bind>*/;
}
}";
string expectedOperationTree =
@"
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C) (Syntax: '-x')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void LogicalNotFlow_01()
{
string source = @"
class P
{
void M(bool a, bool b)
/*<bind>*/{
GetArray()[0] = !(a || b);
}/*</bind>*/
static bool[] GetArray() => null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetArray()[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Boolean) (Syntax: 'GetArray()[0]')
Array reference:
IInvocationOperation (System.Boolean[] P.GetArray()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'GetArray()')
Instance Receiver:
null
Arguments(0)
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Jump if True (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'a')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'GetArray()[ ... !(a || b);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'GetArray()[ ... !(a || b)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'GetArray()[0]')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'a || b')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void LogicalNotFlow_02()
{
var source = @"
class C
{
bool F(bool f)
/*<bind>*/{
return !f;
}/*</bind>*/
}";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Return) Block[B2]
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!f')
Operand:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f')
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void LogicalNotFlow_03()
{
var source = @"
class C
{
bool F(bool f)
/*<bind>*/{
return !!f;
}/*</bind>*/
}";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Return) Block[B2]
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f')
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DynamicNotFlow_01()
{
string source = @"
class P
{
void M(dynamic a, dynamic b)
/*<bind>*/{
a = !b;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = !b;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'a = !b')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'a')
Right:
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!b')
Operand:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
public void VerifyIndexOperator_Int()
{
var compilation = CreateCompilationWithIndexAndRange(@"
class Test
{
void M(int arg)
{
var x = /*<bind>*/^arg/*</bind>*/;
}
}").VerifyDiagnostics();
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg')
Operand:
IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg')
";
var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree);
Assert.Null(operation.OperatorMethod);
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
public void VerifyIndexOperator_NullableInt()
{
var compilation = CreateCompilationWithIndexAndRange(@"
class Test
{
void M(int? arg)
{
var x = /*<bind>*/^arg/*</bind>*/;
}
}").VerifyDiagnostics();
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Hat, IsLifted) (OperationKind.Unary, Type: System.Index?) (Syntax: '^arg')
Operand:
IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'arg')
";
var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree);
Assert.Null(operation.OperatorMethod);
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
public void VerifyIndexOperator_ConvertibleToInt()
{
var compilation = CreateCompilationWithIndexAndRange(@"
class Test
{
void M(byte arg)
{
var x = /*<bind>*/^arg/*</bind>*/;
}
}").VerifyDiagnostics();
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'arg')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'arg')
";
var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree);
Assert.Null(operation.OperatorMethod);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IUnaryOperatorExpression : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17591")]
public void Test_UnaryOperatorExpression_Type_Plus_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt32) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int64) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.UInt64) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '+Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Single) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: System.Double) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()')
Operand:
IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int64) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '-Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Decimal) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Single) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Double) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()')
Operand:
IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_LogicalNot_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/!i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_LogicalNot_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/!Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!Method()')
Operand:
IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.SByte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt16, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt64) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Char, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Decimal, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Single, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Boolean, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_SByte()
{
string source = @"
class A
{
System.SByte Method()
{
System.SByte i = default(System.SByte);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.SByte A.Method()) (OperationKind.Invocation, Type: System.SByte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Byte()
{
string source = @"
class A
{
System.Byte Method()
{
System.Byte i = default(System.Byte);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Byte A.Method()) (OperationKind.Invocation, Type: System.Byte, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int16()
{
string source = @"
class A
{
System.Int16 Method()
{
System.Int16 i = default(System.Int16);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Int16 A.Method()) (OperationKind.Invocation, Type: System.Int16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt16()
{
string source = @"
class A
{
System.UInt16 Method()
{
System.UInt16 i = default(System.UInt16);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.UInt16 A.Method()) (OperationKind.Invocation, Type: System.UInt16, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int32()
{
string source = @"
class A
{
System.Int32 Method()
{
System.Int32 i = default(System.Int32);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Int32 A.Method()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt32()
{
string source = @"
class A
{
System.UInt32 Method()
{
System.UInt32 i = default(System.UInt32);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt32) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.UInt32 A.Method()) (OperationKind.Invocation, Type: System.UInt32) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Int64()
{
string source = @"
class A
{
System.Int64 Method()
{
System.Int64 i = default(System.Int64);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int64) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Int64 A.Method()) (OperationKind.Invocation, Type: System.Int64) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_UInt64()
{
string source = @"
class A
{
System.UInt64 Method()
{
System.UInt64 i = default(System.UInt64);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.UInt64) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.UInt64 A.Method()) (OperationKind.Invocation, Type: System.UInt64) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Char()
{
string source = @"
class A
{
System.Char Method()
{
System.Char i = default(System.Char);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: System.Int32, IsInvalid) (Syntax: '~Method()')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Method()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ( System.Char A.Method()) (OperationKind.Invocation, Type: System.Char, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Decimal()
{
string source = @"
class A
{
System.Decimal Method()
{
System.Decimal i = default(System.Decimal);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Decimal A.Method()) (OperationKind.Invocation, Type: System.Decimal, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Single()
{
string source = @"
class A
{
System.Single Method()
{
System.Single i = default(System.Single);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Single A.Method()) (OperationKind.Invocation, Type: System.Single, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Double()
{
string source = @"
class A
{
System.Double Method()
{
System.Double i = default(System.Double);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Double A.Method()) (OperationKind.Invocation, Type: System.Double, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Boolean()
{
string source = @"
class A
{
System.Boolean Method()
{
System.Boolean i = default(System.Boolean);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Boolean A.Method()) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_System_Object()
{
string source = @"
class A
{
System.Object Method()
{
System.Object i = default(System.Object);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '~Method()')
Operand:
IInvocationOperation ( System.Object A.Method()) (OperationKind.Invocation, Type: System.Object, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/+i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/-i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/~i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_LogicalNot_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/!i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: dynamic) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/+Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: dynamic) (Syntax: '+Method()')
Operand:
IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/-Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: dynamic) (Syntax: '-Method()')
Operand:
IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/~Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: dynamic) (Syntax: '~Method()')
Operand:
IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_LogicalNot_dynamic()
{
string source = @"
class A
{
dynamic Method()
{
dynamic i = default(dynamic);
return /*<bind>*/!Method()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!Method()')
Operand:
IInvocationOperation ( dynamic A.Method()) (OperationKind.Invocation, Type: dynamic) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/+i/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/-i/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/~i/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: Enum) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/+Method()/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+Method()')
Operand:
IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/-Method()/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '-Method()')
Operand:
IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum, IsInvalid) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsInvalid, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_Enum()
{
string source = @"
class A
{
Enum Method()
{
Enum i = default(Enum);
return /*<bind>*/~Method()/*</bind>*/;
}
}
enum Enum { A, B }
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperationKind.Unary, Type: Enum) (Syntax: '~Method()')
Operand:
IInvocationOperation ( Enum A.Method()) (OperationKind.Invocation, Type: Enum) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Plus_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/+i/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_Minus_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/-i/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_BitwiseNot_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/~i/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Type_LogicalNot_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/!i/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Plus_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/+Method()/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: CustomType CustomType.op_UnaryPlus(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '+Method()')
Operand:
IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_Minus_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/-Method()/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: CustomType CustomType.op_UnaryNegation(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '-Method()')
Operand:
IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_BitwiseNot_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/~Method()/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.BitwiseNegation) (OperatorMethod: CustomType CustomType.op_OnesComplement(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '~Method()')
Operand:
IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Method_LogicalNot_CustomType()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/!Method()/*</bind>*/;
}
}
public struct CustomType
{
public static CustomType operator +(CustomType x)
{
return x;
}
public static CustomType operator -(CustomType x)
{
return x;
}
public static CustomType operator !(CustomType x)
{
return x;
}
public static CustomType operator ~(CustomType x)
{
return x;
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Not) (OperatorMethod: CustomType CustomType.op_LogicalNot(CustomType x)) (OperationKind.Unary, Type: CustomType) (Syntax: '!Method()')
Operand:
IInvocationOperation ( CustomType A.Method()) (OperationKind.Invocation, Type: CustomType) (Syntax: 'Method()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Method')
Arguments(0)
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")]
[WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")]
public void Test_UnaryOperatorExpression_Type_And_TrueFalse()
{
string source = @"
public struct S
{
private int value;
public S(int v)
{
value = v;
}
public static S operator |(S x, S y)
{
return new S(x.value - y.value);
}
public static S operator &(S x, S y)
{
return new S(x.value + y.value);
}
public static bool operator true(S x)
{
return x.value > 0;
}
public static bool operator false(S x)
{
return x.value <= 0;
}
}
class C
{
public void M()
{
var x = new S(2);
var y = new S(1);
/*<bind>*/if (x && y) { }/*</bind>*/
}
}
";
string expectedOperationTree = @"
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x && y) { }')
Condition:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x && y')
Operand:
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y')
WhenTrue:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
WhenFalse:
null
";
VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(18135, "https://github.com/dotnet/roslyn/issues/18135")]
[WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")]
public void Test_UnaryOperatorExpression_Type_Or_TrueFalse()
{
string source = @"
public struct S
{
private int value;
public S(int v)
{
value = v;
}
public static S operator |(S x, S y)
{
return new S(x.value - y.value);
}
public static S operator &(S x, S y)
{
return new S(x.value + y.value);
}
public static bool operator true(S x)
{
return x.value > 0;
}
public static bool operator false(S x)
{
return x.value <= 0;
}
}
class C
{
public void M()
{
var x = new S(2);
var y = new S(1);
/*<bind>*/if (x || y) { }/*</bind>*/
}
}
";
string expectedOperationTree = @"
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (x || y) { }')
Condition:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: System.Boolean S.op_True(S x)) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'x || y')
Operand:
IBinaryOperation (BinaryOperatorKind.ConditionalOr) (OperatorMethod: S S.op_BitwiseOr(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x || y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y')
WhenTrue:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
WhenFalse:
null
";
VerifyOperationTreeForTest<IfStatementSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_With_CustomType_NoRightOperator()
{
string source = @"
class A
{
CustomType Method()
{
CustomType i = default(CustomType);
return /*<bind>*/+i/*</bind>*/;
}
}
public struct CustomType
{
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: CustomType, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_With_CustomType_DerivedTypes()
{
string source = @"
class A
{
BaseType Method()
{
var i = default(DerivedType);
return /*<bind>*/+i/*</bind>*/;
}
}
public class BaseType
{
public static BaseType operator +(BaseType x)
{
return new BaseType();
}
}
public class DerivedType : BaseType
{
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperatorMethod: BaseType BaseType.op_UnaryPlus(BaseType x)) (OperationKind.Unary, Type: BaseType) (Syntax: '+i')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: BaseType, IsImplicit) (Syntax: 'i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_With_CustomType_ImplicitConversion()
{
string source = @"
class A
{
BaseType Method()
{
var i = default(DerivedType);
return /*<bind>*/+i/*</bind>*/;
}
}
public class BaseType
{
public static BaseType operator +(BaseType x)
{
return new BaseType();
}
}
public class DerivedType
{
public static implicit operator BaseType(DerivedType x)
{
return new BaseType();
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_With_CustomType_ExplicitConversion()
{
string source = @"
class A
{
BaseType Method()
{
var i = default(DerivedType);
return /*<bind>*/+i/*</bind>*/;
}
}
public class BaseType
{
public static BaseType operator +(BaseType x)
{
return new BaseType();
}
}
public class DerivedType
{
public static explicit operator BaseType(DerivedType x)
{
return new BaseType();
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: DerivedType, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_With_CustomType_Malformed_Operator()
{
string source = @"
class A
{
BaseType Method()
{
var i = default(BaseType);
return /*<bind>*/+i/*</bind>*/;
}
}
public class BaseType
{
public static BaseType operator +(int x)
{
return new BaseType();
}
}
";
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Plus) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+i')
Operand:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: BaseType, IsInvalid) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
[WorkItem(18160, "https://github.com/dotnet/roslyn/issues/18160")]
public void Test_BinaryExpressionSyntax_Type_And_TrueFalse_Condition()
{
string source = @"
public struct S
{
private int value;
public S(int v)
{
value = v;
}
public static S operator |(S x, S y)
{
return new S(x.value - y.value);
}
public static S operator &(S x, S y)
{
return new S(x.value + y.value);
}
public static bool operator true(S x)
{
return x.value > 0;
}
public static bool operator false(S x)
{
return x.value <= 0;
}
}
class C
{
public void M()
{
var x = new S(2);
var y = new S(1);
if (/*<bind>*/x && y/*</bind>*/) { }
}
}
";
string expectedOperationTree = @"
IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperatorMethod: S S.op_BitwiseAnd(S x, S y)) (OperationKind.Binary, Type: S) (Syntax: 'x && y')
Left:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: S) (Syntax: 'x')
Right:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: S) (Syntax: 'y')
";
VerifyOperationTreeForTest<BinaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_IncrementExpression()
{
string source = @"
class A
{
int Method()
{
var i = 1;
return /*<bind>*/++i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++i')
Target:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_DecrementExpression()
{
string source = @"
class A
{
int Method()
{
var i = 1;
return /*<bind>*/--i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IIncrementOrDecrementOperation (Prefix) (OperationKind.Decrement, Type: System.Int32) (Syntax: '--i')
Target:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Nullable()
{
string source = @"
class A
{
void Method()
{
var i = /*<bind>*/(int?)1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?) (Syntax: '(int?)1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
";
VerifyOperationTreeForTest<CastExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void Test_UnaryOperatorExpression_Pointer()
{
string source = @"
class A
{
unsafe void Method()
{
int[] a = new int[5] {10, 20, 30, 40, 50};
fixed (int* p = &a[0])
{
int* p2 = p;
int p1 = /*<bind>*/*p2/*</bind>*/;
}
}
}
";
string expectedOperationTree = @"
IOperation: (OperationKind.None, Type: null) (Syntax: '*p2')
Children(1):
ILocalReferenceOperation: p2 (OperationKind.LocalReference, Type: System.Int32*) (Syntax: 'p2')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VerifyLiftedUnaryOperators1()
{
var source = @"
class C
{
void F(int? x)
{
var y = /*<bind>*/-x/*</bind>*/;
}
}";
string expectedOperationTree =
@"
IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperationKind.Unary, Type: System.Int32?) (Syntax: '-x')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VerifyNonLiftedUnaryOperators1()
{
var source = @"
class C
{
void F(int x)
{
var y = /*<bind>*/-x/*</bind>*/;
}
}";
string expectedOperationTree =
@"
IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32) (Syntax: '-x')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VerifyLiftedUserDefinedUnaryOperators1()
{
var source = @"
struct C
{
public static C operator -(C c) { }
void F(C? x)
{
var y = /*<bind>*/-x/*</bind>*/;
}
}";
string expectedOperationTree =
@"
IUnaryOperation (UnaryOperatorKind.Minus, IsLifted) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C?) (Syntax: '-x')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C?) (Syntax: 'x')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VerifyNonLiftedUserDefinedUnaryOperators1()
{
var source = @"
struct C
{
public static C operator -(C c) { }
void F(C x)
{
var y = /*<bind>*/-x/*</bind>*/;
}
}";
string expectedOperationTree =
@"
IUnaryOperation (UnaryOperatorKind.Minus) (OperatorMethod: C C.op_UnaryNegation(C c)) (OperationKind.Unary, Type: C) (Syntax: '-x')
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x')
";
VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void LogicalNotFlow_01()
{
string source = @"
class P
{
void M(bool a, bool b)
/*<bind>*/{
GetArray()[0] = !(a || b);
}/*</bind>*/
static bool[] GetArray() => null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetArray()[0]')
Value:
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Boolean) (Syntax: 'GetArray()[0]')
Array reference:
IInvocationOperation (System.Boolean[] P.GetArray()) (OperationKind.Invocation, Type: System.Boolean[]) (Syntax: 'GetArray()')
Instance Receiver:
null
Arguments(0)
Indices(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Jump if True (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'b')
Operand:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'a')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'GetArray()[ ... !(a || b);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'GetArray()[ ... !(a || b)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'GetArray()[0]')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'a || b')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void LogicalNotFlow_02()
{
var source = @"
class C
{
bool F(bool f)
/*<bind>*/{
return !f;
}/*</bind>*/
}";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Return) Block[B2]
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: System.Boolean) (Syntax: '!f')
Operand:
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f')
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void LogicalNotFlow_03()
{
var source = @"
class C
{
bool F(bool f)
/*<bind>*/{
return !!f;
}/*</bind>*/
}";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Return) Block[B2]
IParameterReferenceOperation: f (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'f')
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DynamicNotFlow_01()
{
string source = @"
class P
{
void M(dynamic a, dynamic b)
/*<bind>*/{
a = !b;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = !b;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'a = !b')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'a')
Right:
IUnaryOperation (UnaryOperatorKind.Not) (OperationKind.Unary, Type: dynamic) (Syntax: '!b')
Operand:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
public void VerifyIndexOperator_Int()
{
var compilation = CreateCompilationWithIndexAndRange(@"
class Test
{
void M(int arg)
{
var x = /*<bind>*/^arg/*</bind>*/;
}
}").VerifyDiagnostics();
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg')
Operand:
IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'arg')
";
var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree);
Assert.Null(operation.OperatorMethod);
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
public void VerifyIndexOperator_NullableInt()
{
var compilation = CreateCompilationWithIndexAndRange(@"
class Test
{
void M(int? arg)
{
var x = /*<bind>*/^arg/*</bind>*/;
}
}").VerifyDiagnostics();
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Hat, IsLifted) (OperationKind.Unary, Type: System.Index?) (Syntax: '^arg')
Operand:
IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'arg')
";
var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree);
Assert.Null(operation.OperatorMethod);
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
public void VerifyIndexOperator_ConvertibleToInt()
{
var compilation = CreateCompilationWithIndexAndRange(@"
class Test
{
void M(byte arg)
{
var x = /*<bind>*/^arg/*</bind>*/;
}
}").VerifyDiagnostics();
string expectedOperationTree = @"
IUnaryOperation (UnaryOperatorKind.Hat) (OperationKind.Unary, Type: System.Index) (Syntax: '^arg')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'arg')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: arg (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'arg')
";
var operation = (IUnaryOperation)VerifyOperationTreeForTest<PrefixUnaryExpressionSyntax>(compilation, expectedOperationTree);
Assert.Null(operation.OperatorMethod);
}
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/ProjectKey.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.PersistentStorage
{
/// <summary>
/// Handle that can be used with <see cref="IChecksummedPersistentStorage"/> to read data for a
/// <see cref="Project"/> without needing to have the entire <see cref="Project"/> snapshot available.
/// This is useful for cases where acquiring an entire snapshot might be expensive (for example, during
/// solution load), but querying the data is still desired.
/// </summary>
[DataContract]
internal readonly struct ProjectKey
{
[DataMember(Order = 0)]
public readonly SolutionKey Solution;
[DataMember(Order = 1)]
public readonly ProjectId Id;
[DataMember(Order = 2)]
public readonly string? FilePath;
[DataMember(Order = 3)]
public readonly string Name;
[DataMember(Order = 4)]
public readonly Checksum ParseOptionsChecksum;
public ProjectKey(SolutionKey solution, ProjectId id, string? filePath, string name, Checksum parseOptionsChecksum)
{
Solution = solution;
Id = id;
FilePath = filePath;
Name = name;
ParseOptionsChecksum = parseOptionsChecksum;
}
public static ProjectKey ToProjectKey(Project project)
=> ToProjectKey(project.Solution.State, project.State);
public static ProjectKey ToProjectKey(SolutionState solutionState, ProjectState projectState)
=> ToProjectKey(SolutionKey.ToSolutionKey(solutionState), projectState);
public static ProjectKey ToProjectKey(SolutionKey solutionKey, ProjectState projectState)
=> new(solutionKey, projectState.Id, projectState.FilePath, projectState.Name, projectState.GetParseOptionsChecksum());
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.PersistentStorage
{
/// <summary>
/// Handle that can be used with <see cref="IChecksummedPersistentStorage"/> to read data for a
/// <see cref="Project"/> without needing to have the entire <see cref="Project"/> snapshot available.
/// This is useful for cases where acquiring an entire snapshot might be expensive (for example, during
/// solution load), but querying the data is still desired.
/// </summary>
[DataContract]
internal readonly struct ProjectKey
{
[DataMember(Order = 0)]
public readonly SolutionKey Solution;
[DataMember(Order = 1)]
public readonly ProjectId Id;
[DataMember(Order = 2)]
public readonly string? FilePath;
[DataMember(Order = 3)]
public readonly string Name;
[DataMember(Order = 4)]
public readonly Checksum ParseOptionsChecksum;
public ProjectKey(SolutionKey solution, ProjectId id, string? filePath, string name, Checksum parseOptionsChecksum)
{
Solution = solution;
Id = id;
FilePath = filePath;
Name = name;
ParseOptionsChecksum = parseOptionsChecksum;
}
public static ProjectKey ToProjectKey(Project project)
=> ToProjectKey(project.Solution.State, project.State);
public static ProjectKey ToProjectKey(SolutionState solutionState, ProjectState projectState)
=> ToProjectKey(SolutionKey.ToSolutionKey(solutionState), projectState);
public static ProjectKey ToProjectKey(SolutionKey solutionKey, ProjectState projectState)
=> new(solutionKey, projectState.Id, projectState.FilePath, projectState.Name, projectState.GetParseOptionsChecksum());
}
}
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Compilers/Core/Portable/DiaSymReader/Readme.md | The content of this directory is a copy of a subset of https://github.com/dotnet/symreader/tree/main/src/Microsoft.DiaSymReader.
The only difference is in top-level class visibility (public in DiaSymReader, internal here). | The content of this directory is a copy of a subset of https://github.com/dotnet/symreader/tree/main/src/Microsoft.DiaSymReader.
The only difference is in top-level class visibility (public in DiaSymReader, internal here). | -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Compilers/VisualBasic/Test/Semantic/ExtensionMethods/SemanticModelTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods
Public Class ExtendedSemanticInfoTests : Inherits SemanticModelTestBase
<Fact>
Public Sub Test_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"F1"
End Sub
<Extension()>
Function F1(ByRef this As C1) As Integer
Return 0
End Function
End Module
Class C1
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol)
Assert.Equal("Function C1.F1() As System.Int32", method.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, method.Kind)
Assert.Equal(MethodKind.ReducedExtension, method.MethodKind)
Assert.Equal("C1", method.ReceiverType.ToTestDisplayString())
Assert.Equal("Function Module1.F1(ByRef this As C1) As System.Int32", method.ReducedFrom.ToTestDisplayString())
Assert.Equal(MethodKind.Ordinary, method.CallsiteReducedFromMethod.MethodKind)
Assert.Equal("Function Module1.F1(ByRef this As C1) As System.Int32", method.CallsiteReducedFromMethod.ToTestDisplayString())
Dim reducedMethod As MethodSymbol = method.ReducedFrom.ReduceExtensionMethod(method.ReceiverType)
Assert.Equal("Function C1.F1() As System.Int32", reducedMethod.ToTestDisplayString())
Assert.Equal(MethodKind.ReducedExtension, reducedMethod.MethodKind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(1, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact>
Public Sub Test_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"F1"
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function C1.F1() As System.Int32", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(2, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact>
Public Sub Test_3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"x.F1()"
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb")
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function C1.F1() As System.Int32", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
End Class
End Namespace
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class SemanticModelTests
<Fact>
Public Sub ExtensionMethodsLookupSymbols1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"x"
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim c1 = compilation.GetTypeByMetadataName("C1")
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(2, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", container:=c1, includeReducedExtensionMethods:=False)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
Shared Sub Main()
F1()'BIND:"F1"
End Sub
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", includeReducedExtensionMethods:=True)
Assert.Equal(2, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString())
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")>
Public Sub ExtensionMethodsLookupSymbols3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As New C1()
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
End Class
End Module
Module Module2
<Extension()>
Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString())
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray()
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1)
Assert.Equal(0, actual_lookupSymbols.Count)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")>
Public Sub ExtensionMethodsLookupSymbols4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
Sub Main()
Test1() 'BIND:"Test1"
End Sub
End Class
End Module
Module Module2
<Extension()>
Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray()
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1")
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")>
Public Sub ExtensionMethodsLookupSymbols5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As C1 = Nothing
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Interface C1
End Interface
End Module
Module Module2
<Extension()>
Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString())
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray()
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1)
Assert.Equal(0, actual_lookupSymbols.Count)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")>
Public Sub ExtensionMethodsLookupSymbols6()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main(Of T)(x as T)
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T, T1)(this As T)
End Sub
End Module
Module Module2
<Extension()>
Sub Test1(Of T, T1, T2)(this As T)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T, T1, T2, T3)(this As T)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4)(this As T)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5)(this As T)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6)(this As T)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7)(this As T)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7, T8)(this As T)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As T)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T, T1)(this As T)", actual_lookupSymbols(0).ToTestDisplayString())
Dim module1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1")
Dim main = DirectCast(module1.GetMember("Main"), MethodSymbol)
Dim t = main.TypeParameters(0)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t, includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray()
Dim expected() As String = {"Sub T.Test1(Of T1)()",
"Sub T.Test1(Of T1, T2)()",
"Sub T.Test1(Of T1, T2, T3)()",
"Sub T.Test1(Of T1, T2, T3, T4)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t)
Assert.Equal(0, actual_lookupSymbols.Count)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t, arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub T.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols7()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As New C1()
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
End Class
End Module
Module Module2
<Extension()>
Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(14, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Dim expected() As String = {"Function System.Object.Equals(obj As System.Object) As System.Boolean",
"Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.GetHashCode() As System.Int32",
"Function System.Object.GetType() As System.Type",
"Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.ToString() As System.String",
"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1)
Assert.Equal(6, actual_lookupSymbols.Count)
sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
For i As Integer = 0 To sortedMethodGroup.Length - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols8()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
Sub Main()
Test1() 'BIND:"Test1"
End Sub
End Class
End Module
Module Module2
<Extension()>
Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", includeReducedExtensionMethods:=True)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Dim expected() As String = {"Function System.Object.Equals(obj As System.Object) As System.Boolean",
"Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.GetHashCode() As System.Int32",
"Function System.Object.GetType() As System.Type",
"Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.ToString() As System.String",
"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb")
Assert.Equal(0, Aggregate symbol In actual_lookupSymbols Join name In expected.Skip(6)
On symbol.ToTestDisplayString() Equals name Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols9()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As C1 = Nothing
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Interface C1
End Interface
End Module
Module Module2
<Extension()>
Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, includeReducedExtensionMethods:=True)
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1)
Assert.Equal(0, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols10()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main(Of T)(x as T)
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T, T1)(this As T)
End Sub
End Module
Module Module2
<Extension()>
Sub Test2(Of T, T1, T2)(this As T)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T, T1, T2, T3)(this As T)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T, T1, T2, T3, T4)(this As T)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T, T1, T2, T3, T4, T5)(this As T)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T, T1, T2, T3, T4, T5, T6)(this As T)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T, T1, T2, T3, T4, T5, T6, T7)(this As T)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T, T1, T2, T3, T4, T5, T6, T7, T8)(this As T)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T, T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As T)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim module1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1")
Dim main = DirectCast(module1.GetMember("Main"), MethodSymbol)
Dim t = main.TypeParameters(0)
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, includeReducedExtensionMethods:=True)
Dim expected() As String = {"Sub T.Test1(Of T1)()",
"Sub T.Test2(Of T1, T2)()",
"Sub T.Test3(Of T1, T2, T3)()",
"Sub T.Test4(Of T1, T2, T3, T4)()",
"Sub T.Test5(Of T1, T2, T3, T4, T5)()",
"Sub T.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub T.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub T.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, includeReducedExtensionMethods:=False)
Assert.Equal(0, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub T.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub Bug8942_1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System
Imports System.Runtime.CompilerServices
Module M
<Extension()>
Sub Goo(x As Exception)
End Sub
End Module
Class E
Inherits Exception
Sub Bar()
Me.Goo() 'BIND:"Goo"
End Sub
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Sub System.Exception.Goo()", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(1, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Sub System.Exception.Goo()", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact>
Public Sub Bug8942_2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System
Imports System.Runtime.CompilerServices
Module M
<Extension()>
Sub Goo(x As Exception)
End Sub
End Module
Class E
Inherits Exception
Sub Bar()
Goo() 'BIND:"Goo"
End Sub
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Sub System.Exception.Goo()", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(1, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Sub System.Exception.Goo()", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<WorkItem(544933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544933")>
<Fact>
Public Sub LookupSymbolsGenericExtensionMethodWithConstraints()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Class A
End Class
Class B
End Class
Module E
Sub M(_a As A, _b As B)
_a.F()
_b.F()
End Sub
<Extension()>
Sub F(Of T As A)(o As T)
End Sub
End Module
]]></file>
</compilation>, {TestMetadata.Net40.SystemCore})
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30456: 'F' is not a member of 'B'.
_b.F()
~~~~
]]></errors>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim position = FindNodeFromText(tree, "_a.F()").SpanStart
Dim method = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("E").GetMember(Of MethodSymbol)("M")
' No type.
Dim symbols = model.LookupSymbols(position, container:=Nothing, name:="F", includeReducedExtensionMethods:=True)
CheckSymbols(symbols, "Sub E.F(Of T)(o As T)")
' Type satisfying constraints.
symbols = model.LookupSymbols(position, container:=method.Parameters(0).Type, name:="F", includeReducedExtensionMethods:=True)
CheckSymbols(symbols, "Sub A.F()")
' Type not satisfying constraints.
symbols = model.LookupSymbols(position, container:=method.Parameters(1).Type, name:="F", includeReducedExtensionMethods:=True)
CheckSymbols(symbols)
End Sub
<Fact, WorkItem(963125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/963125")>
Public Sub Bug963125()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports alias2 = System
Module Module1
Sub Main()
alias1.Console.WriteLine()
alias2.Console.WriteLine()
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"alias1 = System"})))
compilation.AssertNoDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "alias1").Single()
Dim alias1 = model.GetAliasInfo(node1)
Assert.Equal("alias1=System", alias1.ToTestDisplayString())
Assert.Equal(LocationKind.None, alias1.Locations.Single().Kind)
Dim node2 = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "alias2").Single()
Dim alias2 = model.GetAliasInfo(node2)
Assert.Equal("alias2=System", alias2.ToTestDisplayString())
Assert.Equal(LocationKind.SourceFile, alias2.Locations.Single().Kind)
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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods
Public Class ExtendedSemanticInfoTests : Inherits SemanticModelTestBase
<Fact>
Public Sub Test_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"F1"
End Sub
<Extension()>
Function F1(ByRef this As C1) As Integer
Return 0
End Function
End Module
Class C1
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Dim method = DirectCast(semanticInfo.Symbol, MethodSymbol)
Assert.Equal("Function C1.F1() As System.Int32", method.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, method.Kind)
Assert.Equal(MethodKind.ReducedExtension, method.MethodKind)
Assert.Equal("C1", method.ReceiverType.ToTestDisplayString())
Assert.Equal("Function Module1.F1(ByRef this As C1) As System.Int32", method.ReducedFrom.ToTestDisplayString())
Assert.Equal(MethodKind.Ordinary, method.CallsiteReducedFromMethod.MethodKind)
Assert.Equal("Function Module1.F1(ByRef this As C1) As System.Int32", method.CallsiteReducedFromMethod.ToTestDisplayString())
Dim reducedMethod As MethodSymbol = method.ReducedFrom.ReduceExtensionMethod(method.ReceiverType)
Assert.Equal("Function C1.F1() As System.Int32", reducedMethod.ToTestDisplayString())
Assert.Equal(MethodKind.ReducedExtension, reducedMethod.MethodKind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(1, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact>
Public Sub Test_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"F1"
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function C1.F1() As System.Int32", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(2, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact>
Public Sub Test_3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"x.F1()"
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of InvocationExpressionSyntax)(compilation, "a.vb")
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind)
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Function C1.F1() As System.Int32", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
End Class
End Namespace
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class SemanticModelTests
<Fact>
Public Sub ExtensionMethodsLookupSymbols1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim x As New C1()
x.F1()'BIND:"x"
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim c1 = compilation.GetTypeByMetadataName("C1")
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(2, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", container:=c1, includeReducedExtensionMethods:=False)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
End Sub
<Extension()>
Function F1(this As C1) As Integer
Return 0
End Function
End Module
Class C1
Function F1(x As Integer) As Integer
Return 0
End Function
Shared Sub Main()
F1()'BIND:"F1"
End Sub
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
]]></file>
</compilation>)
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="F1", includeReducedExtensionMethods:=True)
Assert.Equal(2, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray()
Assert.Equal("Function C1.F1() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.Equal("Function C1.F1(x As System.Int32) As System.Int32", sortedMethodGroup(1).ToTestDisplayString())
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")>
Public Sub ExtensionMethodsLookupSymbols3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As New C1()
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
End Class
End Module
Module Module2
<Extension()>
Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString())
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray()
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1)
Assert.Equal(0, actual_lookupSymbols.Count)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")>
Public Sub ExtensionMethodsLookupSymbols4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
Sub Main()
Test1() 'BIND:"Test1"
End Sub
End Class
End Module
Module Module2
<Extension()>
Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray()
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1")
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")>
Public Sub ExtensionMethodsLookupSymbols5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As C1 = Nothing
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Interface C1
End Interface
End Module
Module Module2
<Extension()>
Sub Test1(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T1)(this As NS1.NS2.Module1.C1)", actual_lookupSymbols(0).ToTestDisplayString())
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray()
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1)
Assert.Equal(0, actual_lookupSymbols.Count)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=c1, arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")>
Public Sub ExtensionMethodsLookupSymbols6()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main(Of T)(x as T)
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T, T1)(this As T)
End Sub
End Module
Module Module2
<Extension()>
Sub Test1(Of T, T1, T2)(this As T)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test1(Of T, T1, T2, T3)(this As T)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4)(this As T)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5)(this As T)
End Sub
End Module
Module Module6
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6)(this As T)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7)(this As T)
End Sub
End Module
Module Module8
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7, T8)(this As T)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test1(Of T, T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As T)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.Test1(Of T, T1)(this As T)", actual_lookupSymbols(0).ToTestDisplayString())
Dim module1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1")
Dim main = DirectCast(module1.GetMember("Main"), MethodSymbol)
Dim t = main.TypeParameters(0)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t, includeReducedExtensionMethods:=True)
Assert.Equal(8, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString(), StringComparer.Ordinal).ToArray()
Dim expected() As String = {"Sub T.Test1(Of T1)()",
"Sub T.Test1(Of T1, T2)()",
"Sub T.Test1(Of T1, T2, T3)()",
"Sub T.Test1(Of T1, T2, T3, T4)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5, T6)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub T.Test1(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t)
Assert.Equal(0, actual_lookupSymbols.Count)
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test1", container:=t, arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub T.Test1(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols7()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As New C1()
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
End Class
End Module
Module Module2
<Extension()>
Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, includeReducedExtensionMethods:=True)
Assert.Equal(14, actual_lookupSymbols.Count)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Dim expected() As String = {"Function System.Object.Equals(obj As System.Object) As System.Boolean",
"Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.GetHashCode() As System.Int32",
"Function System.Object.GetType() As System.Type",
"Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.ToString() As System.String",
"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
For i As Integer = 0 To Math.Max(sortedMethodGroup.Length, expected.Length) - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1)
Assert.Equal(6, actual_lookupSymbols.Count)
sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
For i As Integer = 0 To sortedMethodGroup.Length - 1
Assert.Equal(expected(i), sortedMethodGroup(i).ToTestDisplayString())
Next
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols8()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Class C1
Sub Main()
Test1() 'BIND:"Test1"
End Sub
End Class
End Module
Module Module2
<Extension()>
Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", includeReducedExtensionMethods:=True)
Dim sortedMethodGroup = actual_lookupSymbols.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Dim expected() As String = {"Function System.Object.Equals(obj As System.Object) As System.Boolean",
"Function System.Object.Equals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.GetHashCode() As System.Int32",
"Function System.Object.GetType() As System.Type",
"Function System.Object.ReferenceEquals(objA As System.Object, objB As System.Object) As System.Boolean",
"Function System.Object.ToString() As System.String",
"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb")
Assert.Equal(0, Aggregate symbol In actual_lookupSymbols Join name In expected.Skip(6)
On symbol.ToTestDisplayString() Equals name Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols9()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main()
Dim x As C1 = Nothing
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T1)(this As NS1.NS2.Module1.C1)
End Sub
Interface C1
End Interface
End Module
Module Module2
<Extension()>
Sub Test2(Of T1, T2)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T1, T2, T3)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T1, T2, T3, T4)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T1, T2, T3, T4, T5)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T1, T2, T3, T4, T5, T6)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T1, T2, T3, T4, T5, T6, T7)(this As NS1.NS2.Module1.C1)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As NS1.NS2.Module1.C1)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim c1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1+C1")
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, includeReducedExtensionMethods:=True)
Dim expected() As String = {"Sub NS1.NS2.Module1.C1.Test1(Of T1)()",
"Sub NS1.NS2.Module1.C1.Test2(Of T1, T2)()",
"Sub NS1.NS2.Module1.C1.Test3(Of T1, T2, T3)()",
"Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()",
"Sub NS1.NS2.Module1.C1.Test5(Of T1, T2, T3, T4, T5)()",
"Sub NS1.NS2.Module1.C1.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub NS1.NS2.Module1.C1.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub NS1.NS2.Module1.C1.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1)
Assert.Equal(0, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=c1, name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub NS1.NS2.Module1.C1.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub ExtensionMethodsLookupSymbols10()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System.Console
Imports System.Runtime.CompilerServices
Imports NS3.Module5
Imports NS3
Namespace NS1
Namespace NS2
Module Module1
Sub Main(Of T)(x as T)
x.Test1() 'BIND:"Test1"
End Sub
<Extension()>
Sub Test1(Of T, T1)(this As T)
End Sub
End Module
Module Module2
<Extension()>
Sub Test2(Of T, T1, T2)(this As T)
End Sub
End Module
End Namespace
Module Module3
<Extension()>
Sub Test3(Of T, T1, T2, T3)(this As T)
End Sub
End Module
End Namespace
Module Module4
<Extension()>
Sub Test4(Of T, T1, T2, T3, T4)(this As T)
End Sub
End Module
Namespace NS3
Module Module5
<Extension()>
Sub Test5(Of T, T1, T2, T3, T4, T5)(this As T)
End Sub
End Module
Module Module6
<Extension()>
Sub Test6(Of T, T1, T2, T3, T4, T5, T6)(this As T)
End Sub
End Module
End Namespace
Namespace NS4
Module Module7
<Extension()>
Sub Test7(Of T, T1, T2, T3, T4, T5, T6, T7)(this As T)
End Sub
End Module
Module Module8
<Extension()>
Sub Test8(Of T, T1, T2, T3, T4, T5, T6, T7, T8)(this As T)
End Sub
End Module
End Namespace
Namespace NS5
Module Module9
<Extension()>
Sub Test9(Of T, T1, T2, T3, T4, T5, T6, T7, T8, T9)(this As T)
End Sub
End Module
End Namespace
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"NS4.Module7", "NS4"})))
Dim module1 = compilation.GetTypeByMetadataName("NS1.NS2.Module1")
Dim main = DirectCast(module1.GetMember("Main"), MethodSymbol)
Dim t = main.TypeParameters(0)
Dim actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, includeReducedExtensionMethods:=True)
Dim expected() As String = {"Sub T.Test1(Of T1)()",
"Sub T.Test2(Of T1, T2)()",
"Sub T.Test3(Of T1, T2, T3)()",
"Sub T.Test4(Of T1, T2, T3, T4)()",
"Sub T.Test5(Of T1, T2, T3, T4, T5)()",
"Sub T.Test6(Of T1, T2, T3, T4, T5, T6)()",
"Sub T.Test7(Of T1, T2, T3, T4, T5, T6, T7)()",
"Sub T.Test8(Of T1, T2, T3, T4, T5, T6, T7, T8)()"}
Assert.Equal(expected.Length, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, includeReducedExtensionMethods:=False)
Assert.Equal(0, Aggregate name In expected Join symbol In actual_lookupSymbols
On symbol.ToTestDisplayString() Equals name Select name Distinct Into Count())
actual_lookupSymbols = GetLookupSymbols(compilation, "a.vb", container:=t, name:="Test4", arity:=4, includeReducedExtensionMethods:=True)
Assert.Equal(1, actual_lookupSymbols.Count)
Assert.Equal("Sub T.Test4(Of T1, T2, T3, T4)()", actual_lookupSymbols(0).ToTestDisplayString())
End Sub
<Fact>
Public Sub Bug8942_1()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System
Imports System.Runtime.CompilerServices
Module M
<Extension()>
Sub Goo(x As Exception)
End Sub
End Module
Class E
Inherits Exception
Sub Bar()
Me.Goo() 'BIND:"Goo"
End Sub
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Sub System.Exception.Goo()", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(1, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Sub System.Exception.Goo()", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<Fact>
Public Sub Bug8942_2()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Imports System
Imports System.Runtime.CompilerServices
Module M
<Extension()>
Sub Goo(x As Exception)
End Sub
End Module
Class E
Inherits Exception
Sub Bar()
Goo() 'BIND:"Goo"
End Sub
End Class
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Type)
Assert.Null(semanticInfo.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Sub System.Exception.Goo()", semanticInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(1, semanticInfo.MemberGroup.Length)
Dim sortedMethodGroup = semanticInfo.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Sub System.Exception.Goo()", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticInfo.ConstantValue.HasValue)
End Sub
<WorkItem(544933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544933")>
<Fact>
Public Sub LookupSymbolsGenericExtensionMethodWithConstraints()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Class A
End Class
Class B
End Class
Module E
Sub M(_a As A, _b As B)
_a.F()
_b.F()
End Sub
<Extension()>
Sub F(Of T As A)(o As T)
End Sub
End Module
]]></file>
</compilation>, {TestMetadata.Net40.SystemCore})
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30456: 'F' is not a member of 'B'.
_b.F()
~~~~
]]></errors>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim position = FindNodeFromText(tree, "_a.F()").SpanStart
Dim method = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("E").GetMember(Of MethodSymbol)("M")
' No type.
Dim symbols = model.LookupSymbols(position, container:=Nothing, name:="F", includeReducedExtensionMethods:=True)
CheckSymbols(symbols, "Sub E.F(Of T)(o As T)")
' Type satisfying constraints.
symbols = model.LookupSymbols(position, container:=method.Parameters(0).Type, name:="F", includeReducedExtensionMethods:=True)
CheckSymbols(symbols, "Sub A.F()")
' Type not satisfying constraints.
symbols = model.LookupSymbols(position, container:=method.Parameters(1).Type, name:="F", includeReducedExtensionMethods:=True)
CheckSymbols(symbols)
End Sub
<Fact, WorkItem(963125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/963125")>
Public Sub Bug963125()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports alias2 = System
Module Module1
Sub Main()
alias1.Console.WriteLine()
alias2.Console.WriteLine()
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"alias1 = System"})))
compilation.AssertNoDiagnostics()
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "alias1").Single()
Dim alias1 = model.GetAliasInfo(node1)
Assert.Equal("alias1=System", alias1.ToTestDisplayString())
Assert.Equal(LocationKind.None, alias1.Locations.Single().Kind)
Dim node2 = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "alias2").Single()
Dim alias2 = model.GetAliasInfo(node2)
Assert.Equal("alias2=System", alias2.ToTestDisplayString())
Assert.Equal(LocationKind.SourceFile, alias2.Locations.Single().Kind)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,265 | Fix crash in FindReferences | Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | CyrusNajmabadi | "2021-09-08T21:21:24Z" | "2021-09-09T00:35:36Z" | e0909cfd0157f3d1e20fb7275c533a8cf40f50fa | dd58ccee717854f3b91862ae40dcd927c59a44dd | Fix crash in FindReferences. Fixes https://github.com/dotnet/roslyn/issues/55955
Different parts of the FAR stack were inconsistently making sets/dictionaries keyed by symbols. In one part we weren't properly 'unifying' multi-targetted symbols, causing us to report another set of results for what was effectively teh same symbol. A later receiver of this information then crashed as it wsa unifying and thought we were announcing the same symbol it already knew about for a second time.
--
With multi-targetting you can end up with symbols that look the same to the user, but are considered not exactly equivalent under teh covers (for example, core types in one are in mscorlib.dll, but may be in system.dll in another). The IDE code unifies these to give a cohesive representation and display for the user. | ./src/Compilers/Test/Resources/Core/SymbolsTests/V2/MTTestModule1.netmodule | MZ @ !L!This program cannot be run in DOS mode.
$ PE L N
) @ @ ` @ ) O @ H .text
`.reloc @ @ B ) H ` < (
*(
*BSJB v4.0.30319 l #~ < #Strings ( #US 0 #GUID @ #Blob G %3
' ` Y m Y Y Y Y Y K9 b9 9 ) 0 7 A L P g X g g F F % F F F+ F0 F#6 F1: FE? FS+ FaC
Fo0
F}H FM F}S FZ F}b Fo F} F} F F ! F " F # F $ F# % F1 % F & |